Coverage for python/lsst/ip/isr/isrFunctions.py: 86%
570 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 07:52 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 07:52 +0000
1#
2# LSST Data Management System
3# Copyright 2008, 2009, 2010 LSST Corporation.
4#
5# This product includes software developed by the
6# LSST Project (http://www.lsst.org/).
7#
8# This program is free software: you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation, either version 3 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the LSST License Statement and
19# the GNU General Public License along with this program. If not,
20# see <http://www.lsstcorp.org/LegalNotices/>.
21#
23__all__ = [
24 "applyGains",
25 "attachTransmissionCurve",
26 "biasCorrection",
27 "checkFilter",
28 "compareCameraKeywords",
29 "countMaskedPixels",
30 "createPsf",
31 "darkCorrection",
32 "flatCorrection",
33 "gainContext",
34 "getPhysicalFilter",
35 "growMasks",
36 "maskDECamEdgeBleed",
37 "maskE2VEdgeBleed",
38 "maskITLEdgeBleed",
39 "maskITLSatSag",
40 "maskITLDip",
41 "illuminationCorrection",
42 "interpolateDefectList",
43 "interpolateFromMask",
44 "makeThresholdMask",
45 "saturationCorrection",
46 "setBadRegions",
47 "transposeMaskedImage",
48 "trimToMatchCalibBBox",
49 "updateVariance",
50 "widenSaturationTrails",
51 "getExposureGains",
52 "getExposureReadNoises",
53]
55import logging
56import math
57import numpy
59import lsst.geom
60import lsst.afw.image as afwImage
61import lsst.afw.detection as afwDetection
62import lsst.afw.math as afwMath
63import lsst.meas.algorithms as measAlg
64import lsst.afw.cameraGeom as camGeom
66from lsst.afw.geom import SpanSet, Stencil
67from lsst.meas.algorithms.detection import SourceDetectionTask
69from contextlib import contextmanager
71from .defects import Defects
74def createPsf(fwhm):
75 """Make a double Gaussian PSF.
77 Parameters
78 ----------
79 fwhm : scalar
80 FWHM of double Gaussian smoothing kernel.
82 Returns
83 -------
84 psf : `lsst.meas.algorithms.DoubleGaussianPsf`
85 The created smoothing kernel.
86 """
87 ksize = 4*int(fwhm) + 1
88 return measAlg.DoubleGaussianPsf(ksize, ksize, fwhm/(2*math.sqrt(2*math.log(2))))
91def transposeMaskedImage(maskedImage):
92 """Make a transposed copy of a masked image.
94 Parameters
95 ----------
96 maskedImage : `lsst.afw.image.MaskedImage`
97 Image to process.
99 Returns
100 -------
101 transposed : `lsst.afw.image.MaskedImage`
102 The transposed copy of the input image.
103 """
104 transposed = maskedImage.Factory(lsst.geom.Extent2I(maskedImage.getHeight(), maskedImage.getWidth()))
105 transposed.getImage().getArray()[:] = maskedImage.getImage().getArray().T
106 transposed.getMask().getArray()[:] = maskedImage.getMask().getArray().T
107 transposed.getVariance().getArray()[:] = maskedImage.getVariance().getArray().T
108 return transposed
111def interpolateDefectList(maskedImage, defectList, fwhm, fallbackValue=None,
112 maskNameList=None, useLegacyInterp=True):
113 """Interpolate over defects specified in a defect list.
115 Parameters
116 ----------
117 maskedImage : `lsst.afw.image.MaskedImage`
118 Image to process.
119 defectList : `lsst.meas.algorithms.Defects`
120 List of defects to interpolate over.
121 fwhm : `float`
122 FWHM of double Gaussian smoothing kernel.
123 fallbackValue : scalar, optional
124 Fallback value if an interpolated value cannot be determined.
125 If None, then the clipped mean of the image is used.
126 maskNameList : `list [string]`
127 List of the defects to interpolate over (used for GP interpolator).
128 useLegacyInterp : `bool`
129 Use the legacy interpolation (polynomial interpolation) if True. Use
130 Gaussian Process interpolation if False.
132 Notes
133 -----
134 The ``fwhm`` parameter is used to create a PSF, but the underlying
135 interpolation code (`lsst.meas.algorithms.interpolateOverDefects`) does
136 not currently make use of this information in legacy Interpolation, but use
137 if for the Gaussian Process as an estimation of the correlation lenght.
138 """
139 psf = createPsf(fwhm)
140 if fallbackValue is None: 140 ↛ 143line 140 didn't jump to line 143 because the condition on line 140 was always true
141 # Very fast computation of a reasonable fallback value.
142 fallbackValue = numpy.nanmedian(maskedImage.image.array[::4, ::4])
143 if 'INTRP' not in maskedImage.getMask().getMaskPlaneDict(): 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true
144 maskedImage.getMask().addMaskPlane('INTRP')
146 # Hardcoded fwhm value. PSF estimated latter in step1,
147 # not in ISR.
148 if useLegacyInterp:
149 kwargs = {}
150 fwhm = fwhm
151 else:
152 # tested on a dozens of images and looks a good set of
153 # hyperparameters, but cannot guarrenty this is optimal,
154 # need further testing.
155 kwargs = {"bin_spacing": 20,
156 "threshold_dynamic_binning": 2000,
157 "threshold_subdivide": 20000}
158 fwhm = 15
160 measAlg.interpolateOverDefects(maskedImage, psf, defectList,
161 fallbackValue=fallbackValue,
162 useFallbackValueAtEdge=True,
163 fwhm=fwhm,
164 useLegacyInterp=useLegacyInterp,
165 maskNameList=maskNameList, **kwargs)
166 return maskedImage
169def makeThresholdMask(maskedImage, threshold, growFootprints=1, maskName='SAT'):
170 """Mask pixels based on threshold detection.
172 Parameters
173 ----------
174 maskedImage : `lsst.afw.image.MaskedImage`
175 Image to process. Only the mask plane is updated.
176 threshold : scalar
177 Detection threshold.
178 growFootprints : scalar, optional
179 Number of pixels to grow footprints of detected regions.
180 maskName : str, optional
181 Mask plane name, or list of names to convert
183 Returns
184 -------
185 defectList : `lsst.meas.algorithms.Defects`
186 Defect list constructed from pixels above the threshold.
187 """
188 # find saturated regions
189 thresh = afwDetection.Threshold(threshold)
190 fs = afwDetection.FootprintSet(maskedImage, thresh)
192 if growFootprints > 0:
193 fs = afwDetection.FootprintSet(fs, rGrow=growFootprints, isotropic=False)
194 fpList = fs.getFootprints()
196 # set mask
197 mask = maskedImage.getMask()
198 bitmask = mask.getPlaneBitMask(maskName)
199 afwDetection.setMaskFromFootprintList(mask, fpList, bitmask)
201 return Defects.fromFootprintList(fpList)
204def growMasks(mask, radius=0, maskNameList=['BAD'], maskValue="BAD"):
205 """Grow a mask by an amount and add to the requested plane.
207 Parameters
208 ----------
209 mask : `lsst.afw.image.Mask`
210 Mask image to process.
211 radius : scalar
212 Amount to grow the mask.
213 maskNameList : `str` or `list` [`str`]
214 Mask names that should be grown.
215 maskValue : `str`
216 Mask plane to assign the newly masked pixels to.
217 """
218 if radius > 0: 218 ↛ exitline 218 didn't return from function 'growMasks' because the condition on line 218 was always true
219 spans = SpanSet.fromMask(mask, mask.getPlaneBitMask(maskNameList))
220 # Use MANHATTAN for equivalence with 'isotropic=False` footprint grows,
221 # but CIRCLE is probably better and might be just as fast.
222 spans = spans.dilated(radius, Stencil.MANHATTAN)
223 spans = spans.clippedTo(mask.getBBox())
224 spans.setMask(mask, mask.getPlaneBitMask(maskValue))
227def maskE2VEdgeBleed(exposure, e2vEdgeBleedSatMinArea=10000,
228 e2vEdgeBleedSatMaxArea=100000,
229 e2vEdgeBleedYMax=350,
230 saturatedMaskName="SAT", log=None):
231 """Mask edge bleeds in E2V detectors.
233 Parameters
234 ----------
235 exposure : `lsst.afw.image.Exposure`
236 Exposure to apply masking to.
237 e2vEdgeBleedSatMinArea : `int`, optional
238 Minimum limit of saturated cores footprint area.
239 e2vEdgeBleedSatMaxArea : `int`, optional
240 Maximum limit of saturated cores footprint area.
241 e2vEdgeBleedYMax: `float`, optional
242 Height of edge bleed masking.
243 saturatedMaskName : `str`, optional
244 Mask name for saturation.
245 log : `logging.Logger`, optional
246 Logger to handle messages.
247 """
249 log = log if log else logging.getLogger(__name__)
251 maskedImage = exposure.maskedImage
252 saturatedBit = maskedImage.mask.getPlaneBitMask(saturatedMaskName)
254 thresh = afwDetection.Threshold(saturatedBit, afwDetection.Threshold.BITMASK)
256 fpList = afwDetection.FootprintSet(exposure.mask, thresh).getFootprints()
258 satAreas = numpy.asarray([fp.getArea() for fp in fpList])
259 largeAreas, = numpy.where((satAreas >= e2vEdgeBleedSatMinArea)
260 & (satAreas < e2vEdgeBleedSatMaxArea))
261 for largeAreasIndex in largeAreas:
262 fpCore = fpList[largeAreasIndex]
263 xCore, yCore = fpCore.getCentroid()
264 xCore = int(xCore)
265 yCore = int(yCore)
267 for amp in exposure.getDetector():
268 if amp.getBBox().contains(xCore, yCore):
269 ampName = amp.getName()
270 if ampName[:2] == 'C0': 270 ↛ 267line 270 didn't jump to line 267 because the condition on line 270 was always true
271 # Check that the footprint reaches the bottom of the
272 # amplifier.
273 if fpCore.getBBox().getMinY() == 0: 273 ↛ 267line 273 didn't jump to line 267 because the condition on line 273 was always true
274 # This is a large saturation footprint that hits the
275 # edge, and is thus classified as an edge bleed.
277 # TODO DM-50587: Optimize number of rows to mask by
278 # looking at the median signal level as a function of
279 # row number on the right side of the saturation trail.
281 log.info("Found E2V edge bleed in amp %s, column %d.", ampName, xCore)
282 maskedImage.mask[amp.getBBox()].array[:e2vEdgeBleedYMax, :] |= saturatedBit
285def maskDECamEdgeBleed(exposure, satMinArea=10000, approachRows=20, nSigma=5.0,
286 nRowsCheck=20, nRowsCheckShort=5, minUsablePixelsPerRow=30,
287 minLowFraction=0.03, minLowFractionExtent=0.01, minBlockedRows=5,
288 marginFraction=0.125, saturatedMaskName="SAT", log=None):
289 """Mask DECam-style edge bleeds with low rows next to the read register.
291 For each amplifier that contains a large saturated footprint reaching
292 within ``approachRows`` of its read edge, this function identifies a dip
293 using the per-row fraction of usable pixels more than ``nSigma`` below
294 the clipped sky, measures how far the dip extends inward, and marks
295 those rows (plus a margin) with the saturation mask plane.
297 Rows next to the read edge that are unusable are the signature of a
298 drained serial register, which the overscan correction flags as bad;
299 ``minBlockedRows`` rows are also flagged, despite not having a
300 dip measurement.
302 Parameters
303 ----------
304 exposure : `lsst.afw.image.Exposure`
305 Assembled exposure to mask.
306 satMinArea : `int`, optional
307 Minimum area (pixels) of a saturated footprint to be considered.
308 approachRows : `int`, optional
309 A saturated footprint must come within this many rows of the read edge
310 to trigger the edge bleed check.
311 nSigma : `float`, optional
312 A pixel is "low" if it is more than this many sigma below sky.
313 nRowsCheck : `int`, optional
314 Number of rows from the read edge to check for an edge bleed dip.
315 nRowsCheckShort : `int`, optional
316 A second, shorter window from the read edge to check for a short
317 edge bleed dip.
318 minUsablePixelsPerRow : `int`, optional
319 Minimum number of pixels not saturated, bad or missing to search for
320 dips. Rows with fewer pixels may be "blocked" due to a drained
321 register.
322 minLowFraction : `float`, optional
323 Mean fraction of usable pixels that are low, over either ``nRowsCheck``
324 or ``nRowsCheckShort``, to confirm a dip.
325 minLowFractionExtent : `float`, optional
326 Fraction of usable pixels that are low that each row must exceed
327 to count toward the bleed height; the scan stops after five consecutive
328 rows that do not. Should not exceed ``minLowFraction``.
329 minBlockedRows : `int`, optional
330 Minimum number of blocked rows beyond the normal border at the read
331 edge to be masked if found.
332 marginFraction : `float`, optional
333 Extra rows masked beyond the measured height, as a fraction of
334 that height (plus one row).
335 saturatedMaskName : `str`, optional
336 Mask plane name for saturation.
337 log : `logging.Logger`, optional
338 Logger to handle messages.
340 Raises
341 ------
342 RuntimeError
343 Raised if the exposure has no detector with amplifiers.
344 """
345 log = log if log else logging.getLogger(__name__)
347 detector = exposure.getDetector()
348 if detector is None or len(detector) == 0:
349 raise RuntimeError("Cannot mask DECam edge bleeds: exposure has no detector with amplifiers.")
351 maskedImage = exposure.maskedImage
352 saturatedBit = maskedImage.mask.getPlaneBitMask(saturatedMaskName)
353 borderBits = maskedImage.mask.getPlaneBitMask(["BAD", "NO_DATA"])
354 unusableBits = borderBits | saturatedBit
355 excludeStatsBits = unusableBits | maskedImage.mask.getPlaneBitMask("SUSPECT")
357 # find saturated footprints
358 thresh = afwDetection.Threshold(saturatedBit, afwDetection.Threshold.BITMASK)
359 fpList = afwDetection.FootprintSet(maskedImage.mask, thresh).getFootprints()
360 candidates = []
361 for fp in fpList:
362 if fp.getArea() >= satMinArea:
363 xCore, yCore = fp.getCentroid()
364 candidates.append((int(xCore), int(yCore), fp.getBBox()))
365 if not candidates:
366 log.debug("No saturated footprints large enough for the DECam edge bleed check.")
367 return
369 statsCtrl = afwMath.StatisticsControl()
370 statsCtrl.setAndMask(excludeStatsBits)
372 # End the dip scan after this many consecutive rows without a dip.
373 nRowsStop = 5
375 for amp in detector:
376 ampBBox = amp.getBBox()
377 if not exposure.getBBox().contains(ampBBox):
378 continue
379 readTop = amp.getReadoutCorner() in (camGeom.ReadoutCorner.UL, camGeom.ReadoutCorner.UR)
381 # check to see if saturated footprints reach the readout edge
382 if readTop:
383 reachesReadEdge = any(ampBBox.contains(x, y)
384 and fpBBox.getMaxY() >= ampBBox.getMaxY() - approachRows
385 for x, y, fpBBox in candidates)
386 else:
387 reachesReadEdge = any(ampBBox.contains(x, y)
388 and fpBBox.getMinY() <= ampBBox.getMinY() + approachRows
389 for x, y, fpBBox in candidates)
390 if not reachesReadEdge:
391 continue
393 ampImage = maskedImage[ampBBox]
394 stats = afwMath.makeStatistics(ampImage, afwMath.MEANCLIP | afwMath.STDEVCLIP | afwMath.NPOINT,
395 statsCtrl)
396 if stats.getValue(afwMath.NPOINT) < 1000: 396 ↛ 397line 396 didn't jump to line 397 because the condition on line 396 was never true
397 log.debug("Skipping DECam edge bleed check in amp %s: too few unmasked pixels.",
398 amp.getName())
399 continue
400 sky = stats.getValue(afwMath.MEANCLIP)
401 sigma = stats.getValue(afwMath.STDEVCLIP)
403 usable = (ampImage.mask.array & unusableBits) == 0
404 low = (ampImage.image.array < sky - nSigma*sigma) & usable
405 # Row profiles with index 0 at the read edge, increasing inward.
406 nLow = low.sum(axis=1)
407 nUsable = usable.sum(axis=1)
408 nBorderUsable = ((ampImage.mask.array & borderBits) == 0).sum(axis=1)
409 if readTop:
410 nLow = nLow[::-1]
411 nUsable = nUsable[::-1]
412 else:
413 nBorderUsable = nBorderUsable[::-1]
415 enoughUsable = numpy.nonzero(nUsable >= minUsablePixelsPerRow)[0]
416 if len(enoughUsable) == 0: 416 ↛ 417line 416 didn't jump to line 417 because the condition on line 416 was never true
417 log.debug("Skipping DECam edge bleed check in amp %s: no rows with usable pixels.",
418 amp.getName())
419 continue
420 start = int(enoughUsable[0])
421 borderRows = numpy.nonzero(nBorderUsable >= minUsablePixelsPerRow)[0]
422 border = int(borderRows[0]) if len(borderRows) else 0
423 blocked = start - border
425 fraction = numpy.zeros(len(nLow), dtype=float)
426 good = nUsable >= minUsablePixelsPerRow
427 fraction[good] = nLow[good]/nUsable[good]
429 dipFound = fraction[start:start + nRowsCheck].mean() > minLowFraction
430 if nRowsCheckShort > 0:
431 dipFound |= fraction[start:start + nRowsCheckShort].mean() > minLowFraction
432 if not dipFound and blocked < minBlockedRows:
433 log.debug("Saturated footprint reaches read edge of amp %s but no dip found.",
434 amp.getName())
435 continue
437 height = start if blocked >= minBlockedRows else 0
438 nBelow = 0
439 for i in range(start, len(fraction)): 439 ↛ 447line 439 didn't jump to line 447 because the loop on line 439 didn't complete
440 if fraction[i] > minLowFractionExtent:
441 height = i + 1
442 nBelow = 0
443 else:
444 nBelow += 1
445 if nBelow >= nRowsStop:
446 break
447 height += int(height*marginFraction) + 1
448 height = min(height, ampBBox.getHeight())
450 if readTop:
451 maskedImage.mask[ampBBox].array[-height:, :] |= saturatedBit
452 else:
453 maskedImage.mask[ampBBox].array[:height, :] |= saturatedBit
454 log.info("Found DECam edge bleed in amp %s at the %s read edge (%d blocked rows); masked %d rows.",
455 amp.getName(), "top" if readTop else "bottom", max(blocked, 0), height)
458def maskITLEdgeBleed(ccdExposure, badAmpDict,
459 fpCore, itlEdgeBleedSatMinArea=10000,
460 itlEdgeBleedSatMaxArea=100000,
461 itlEdgeBleedThreshold=5000.,
462 itlEdgeBleedModelConstant=0.02,
463 saturatedMaskName="SAT", log=None):
464 """Mask edge bleeds in ITL detectors.
466 Parameters
467 ----------
468 ccdExposure : `lsst.afw.image.Exposure`
469 Exposure to apply masking to.
470 badAmpDict : `dict` [`str`, `bool`]
471 Dictionary of amplifiers, keyed by name, value is True if
472 amplifier is fully masked.
473 fpCore : `lsst.afw.detection._detection.Footprint`
474 Footprint of saturated core.
475 itlEdgeBleedThreshold : `float`, optional
476 Threshold above median sky background for edge bleed detection
477 (electron units).
478 itlEdgeBleedModelConstant : `float`, optional
479 Constant in the decaying exponential in the edge bleed masking.
480 saturatedMaskName : `str`, optional
481 Mask name for saturation.
482 log : `logging.Logger`, optional
483 Logger to handle messages.
484 """
486 log = log if log else logging.getLogger(__name__)
488 # Get median of amplifier saturation level
489 satLevel = numpy.nanmedian([ccdExposure.metadata[f"LSST ISR SATURATION LEVEL {amp.getName()}"]
490 for amp in ccdExposure.getDetector() if not badAmpDict[amp.getName()]])
492 # 1. we check if there are several cores in the footprint:
493 # Get centroid of saturated core
494 xCore, yCore = fpCore.getCentroid()
495 # Turn the Y detector coordinate into Y footprint coordinate
496 yCoreFP = int(yCore) - fpCore.getBBox().getMinY()
497 # Now test if there is one or more cores by checking if the slice at the
498 # center is full of saturated pixels or has several segments of saturated
499 # columns (i.e. several cores with trails)
500 checkCoreNbRow = fpCore.getSpans().asArray()[yCoreFP, :]
501 nbCore = 0
502 indexSwitchTrue = []
503 indexSwitchFalse = []
504 if checkCoreNbRow[0]:
505 # If the slice starts with saturated pixels
506 inSatSegment = True
507 nbCore = 1
508 indexSwitchTrue.append(0)
509 else:
510 # If the slice starts with non saturated pixels
511 inSatSegment = False
513 for i, value in enumerate(checkCoreNbRow):
514 if value:
515 if not inSatSegment:
516 indexSwitchTrue.append(i)
517 # nbCore is the number of detected cores.
518 nbCore += 1
519 inSatSegment = True
520 elif inSatSegment:
521 indexSwitchFalse.append(i)
522 inSatSegment = False
524 # 1. we look for edge bleed in saturated cores in the footprint
525 if nbCore == 2:
526 # we now estimate the x coordinates of the edges of the subfootprint
527 # for each core
528 xEdgesCores = [0]
529 xEdgesCores.append(int((indexSwitchTrue[1] + indexSwitchFalse[0])/2))
530 xEdgesCores.append(fpCore.getSpans().asArray().shape[1])
531 # Get the X and Y footprint coordinates of the cores
532 for i in range(nbCore):
533 subfp = fpCore.getSpans().asArray()[:, xEdgesCores[i]:xEdgesCores[i+1]]
534 xCoreFP = int(xEdgesCores[i] + numpy.argmax(numpy.sum(subfp, axis=0)))
535 # turn into X coordinate in detector space
536 xCore = xCoreFP + fpCore.getBBox().getMinX()
537 # get Y footprint coordinate of the core
538 # by trimming the edges where edge bleeds are potentially dominant
539 if subfp.shape[0] <= 200: 539 ↛ 542line 539 didn't jump to line 542 because the condition on line 539 was always true
540 yCoreFP = int(numpy.argmax(numpy.sum(subfp, axis=1)))
541 else:
542 yCoreFP = int(numpy.argmax(numpy.sum(subfp[100:-100, :],
543 axis=1)))
544 yCoreFP = 100+yCoreFP
546 # Estimate the width of the saturated core
547 widthSat = numpy.sum(subfp[int(yCoreFP), :])
549 subfpArea = numpy.sum(subfp)
550 if subfpArea > itlEdgeBleedSatMinArea and subfpArea < itlEdgeBleedSatMaxArea: 550 ↛ 532line 550 didn't jump to line 532 because the condition on line 550 was always true
551 _applyMaskITLEdgeBleed(ccdExposure, xCore,
552 satLevel, widthSat,
553 itlEdgeBleedThreshold,
554 itlEdgeBleedModelConstant,
555 saturatedMaskName, log)
556 elif nbCore > 2: 556 ↛ 558line 556 didn't jump to line 558 because the condition on line 556 was never true
557 # TODO DM-49736: support N cores in saturated footprint
558 log.warning(
559 "Too many (%d) cores in saturated footprint to mask edge bleeds.",
560 nbCore,
561 )
562 else:
563 # Get centroid of saturated core
564 xCore, yCore = fpCore.getCentroid()
565 # Turn the Y detector coordinate into Y footprint coordinate
566 yCoreFP = yCore - fpCore.getBBox().getMinY()
567 # Get the number of saturated columns around the centroid
568 widthSat = numpy.sum(fpCore.getSpans().asArray()[int(yCoreFP), :])
569 _applyMaskITLEdgeBleed(ccdExposure, xCore,
570 satLevel, widthSat, itlEdgeBleedThreshold,
571 itlEdgeBleedModelConstant, saturatedMaskName, log)
574def _applyMaskITLEdgeBleed(ccdExposure, xCore,
575 satLevel, widthSat,
576 itlEdgeBleedThreshold=5000.,
577 itlEdgeBleedModelConstant=0.03,
578 saturatedMaskName="SAT", log=None):
579 """Apply ITL edge bleed masking model.
581 Parameters
582 ----------
583 ccdExposure : `lsst.afw.image.Exposure`
584 Exposure to apply masking to.
585 xCore: `int`
586 X coordinate of the saturated core.
587 satLevel: `float`
588 Minimum saturation level of the detector.
589 widthSat: `float`
590 Width of the saturated core.
591 itlEdgeBleedThreshold : `float`, optional
592 Threshold above median sky background for edge bleed detection
593 (electron units).
594 itlEdgeBleedModelConstant : `float`, optional
595 Constant in the decaying exponential in the edge bleed masking.
596 saturatedMaskName : `str`, optional
597 Mask name for saturation.
598 log : `logging.Logger`, optional
599 Logger to handle messages.
600 """
601 log = log if log else logging.getLogger(__name__)
603 maskedImage = ccdExposure.maskedImage
604 xmax = maskedImage.image.array.shape[1]
605 saturatedBit = maskedImage.mask.getPlaneBitMask(saturatedMaskName)
607 for amp in ccdExposure.getDetector():
608 # Select the 2 top and bottom amplifiers around the saturated
609 # core with a potential edge bleed by selecting the amplifiers
610 # that have the same X coordinate as the saturated core.
611 # As we don't care about the Y coordinate, we set it to the
612 # center of the BBox.
613 yBox = amp.getBBox().getCenter()[1]
614 if amp.getBBox().contains(xCore, yBox):
616 # Get the amp name
617 ampName = amp.getName()
619 # Because in ITLs the edge bleed happens on both edges
620 # of the detector, we make a cutout around
621 # both the top and bottom
622 # edge bleed candidates around the saturated core.
623 # We flip the cutout of the top amplifier
624 # to then work with the same coordinates for both.
625 # The way of selecting top vs bottom amp
626 # is very specific to ITL.
627 if ampName[:2] == 'C1':
628 sliceImage = maskedImage.image.array[:200, :]
629 sliceMask = maskedImage.mask.array[:200, :]
630 elif ampName[:2] == 'C0': 630 ↛ 644line 630 didn't jump to line 644 because the condition on line 630 was always true
631 sliceImage = numpy.flipud(maskedImage.image.array[-200:, :])
632 sliceMask = numpy.flipud(maskedImage.mask.array[-200:, :])
634 # The middle columns of edge bleeds often have
635 # high counts, so we check there is an edge bleed
636 # by looking at a small image up to 50 pixels from the edge
637 # and around the saturated columns
638 # of the saturated core, and checking its median is
639 # above the sky background by itlEdgeBleedThreshold
641 # If the centroid is too close to the edge of the detector
642 # (within 5 pixels), we set the limit to the mean check
643 # to the edge of the detector
644 lowerRangeSmall = int(xCore)-5
645 upperRangeSmall = int(xCore)+5
646 if lowerRangeSmall < 0:
647 lowerRangeSmall = 0
648 if upperRangeSmall > xmax: 648 ↛ 649line 648 didn't jump to line 649 because the condition on line 648 was never true
649 upperRangeSmall = xmax
650 ampImageBG = numpy.median(maskedImage[amp.getBBox()].image.array)
651 edgeMedian = numpy.median(sliceImage[:50, lowerRangeSmall:upperRangeSmall])
652 if edgeMedian > (ampImageBG + itlEdgeBleedThreshold):
654 log.info("Found ITL edge bleed in amp %s, column %d.", ampName, xCore)
656 # We need an estimate of the maximum width
657 # of the edge bleed for our masking model
658 # so we now estimate it by measuring the width of
659 # areas above 60 percent of the saturation level
660 # close to the edge,
661 # in a cutout up to 100 pixels from the edge,
662 # with a width of around the width of an amplifier.
663 subImageXMin = int(xCore)-250
664 subImageXMax = int(xCore)+250
665 if subImageXMin < 0:
666 subImageXMin = 0
667 elif subImageXMax > xmax:
668 subImageXMax = xmax
670 subImage = sliceImage[:100, subImageXMin:subImageXMax]
671 maxWidthEdgeBleed = numpy.max(numpy.sum(subImage > 0.45*satLevel,
672 axis=1))
674 # Mask edge bleed with a decaying exponential model
675 for y in range(200):
676 edgeBleedHalfWidth = \
677 int(((maxWidthEdgeBleed)*numpy.exp(-itlEdgeBleedModelConstant*y)
678 + widthSat)/2.)
679 lowerRange = int(xCore)-edgeBleedHalfWidth
680 upperRange = int(xCore)+edgeBleedHalfWidth
681 # If the edge bleed model goes outside the detector
682 # we set the limit for the masking
683 # to the edge of the detector
684 if lowerRange < 0:
685 lowerRange = 0
686 if upperRange > xmax:
687 upperRange = xmax
688 sliceMask[y, lowerRange:upperRange] |= saturatedBit
691def maskITLSatSag(ccdExposure, fpCore, saturatedMaskName="SAT"):
692 """Mask columns presenting saturation sag in saturated footprints in
693 ITL detectors.
695 Parameters
696 ----------
697 ccdExposure : `lsst.afw.image.Exposure`
698 Exposure to apply masking to.
699 fpCore : `lsst.afw.detection._detection.Footprint`
700 Footprint of saturated core.
701 saturatedMaskName : `str`, optional
702 Mask name for saturation.
703 """
705 # TODO DM-49736: add a flux level check to apply masking
707 maskedImage = ccdExposure.maskedImage
708 saturatedBit = maskedImage.mask.getPlaneBitMask(saturatedMaskName)
710 cc = numpy.sum(fpCore.getSpans().asArray(), axis=0)
711 # Mask full columns that have 20 percent of the height of the footprint
712 # saturated
713 columnsToMaskFP = numpy.where(cc > fpCore.getSpans().asArray().shape[0]/5.)
715 columnsToMask = [x + int(fpCore.getBBox().getMinX()) for x in columnsToMaskFP]
716 maskedImage.mask.array[:, columnsToMask] |= saturatedBit
719def maskITLDip(exposure, detectorConfig, maskPlaneNames=["SUSPECT", "ITL_DIP"], log=None):
720 """Add mask bits according to the ITL dip model.
722 Parameters
723 ----------
724 exposure : `lsst.afw.image.Exposure`
725 Exposure to do ITL dip masking.
726 detectorConfig : `lsst.ip.isr.overscanAmpConfig.OverscanDetectorConfig`
727 Configuration for this detector.
728 maskPlaneNames : `list [`str`], optional
729 Name of the ITL Dip mask planes.
730 log : `logging.Logger`, optional
731 If not set, a default logger will be used.
732 """
733 if detectorConfig.itlDipBackgroundFraction == 0.0:
734 # Nothing to do.
735 return
737 if log is None: 737 ↛ 740line 737 didn't jump to line 740 because the condition on line 737 was always true
738 log = logging.getLogger(__name__)
740 thresh = afwDetection.Threshold(
741 exposure.mask.getPlaneBitMask("SAT"),
742 afwDetection.Threshold.BITMASK,
743 )
744 fpList = afwDetection.FootprintSet(exposure.mask, thresh).getFootprints()
746 heights = numpy.asarray([fp.getBBox().getHeight() for fp in fpList])
748 largeHeights, = numpy.where(heights >= detectorConfig.itlDipMinHeight)
750 if len(largeHeights) == 0: 750 ↛ 751line 750 didn't jump to line 751 because the condition on line 750 was never true
751 return
753 # Get the approximate image background.
754 approxBackground = numpy.median(exposure.image.array)
755 maskValue = exposure.mask.getPlaneBitMask(maskPlaneNames)
757 maskBak = exposure.mask.array.copy()
758 nMaskedCols = 0
760 for index in largeHeights:
761 fp = fpList[index]
762 center = fp.getCentroid()
764 nSat = numpy.sum(fp.getSpans().asArray(), axis=0)
765 width = numpy.sum(nSat > detectorConfig.itlDipMinHeight)
767 if width < detectorConfig.itlDipMinWidth:
768 continue
770 width = numpy.clip(width, None, detectorConfig.itlDipMaxWidth)
772 dipMax = detectorConfig.itlDipBackgroundFraction * approxBackground * width
774 # Assume sky-noise dominated; we could add in read noise here.
775 if dipMax < detectorConfig.itlDipMinBackgroundNoiseFraction * numpy.sqrt(approxBackground):
776 continue
778 minCol = int(center.getX() - (detectorConfig.itlDipWidthScale * width) / 2.)
779 maxCol = int(center.getX() + (detectorConfig.itlDipWidthScale * width) / 2.)
780 minCol = numpy.clip(minCol, 0, None)
781 maxCol = numpy.clip(maxCol, None, exposure.mask.array.shape[1] - 1)
783 log.info(
784 "Found ITL dip (width %d; bkg %.2f); masking column %d to %d.",
785 width,
786 approxBackground,
787 minCol,
788 maxCol,
789 )
791 exposure.mask.array[:, minCol: maxCol + 1] |= maskValue
793 nMaskedCols += (maxCol - minCol + 1)
795 if nMaskedCols > detectorConfig.itlDipMaxColsPerImage:
796 log.warning(
797 "Too many (%d) columns would be masked on this image from dip masking; restoring original mask.",
798 nMaskedCols,
799 )
800 exposure.mask.array[:, :] = maskBak
803def interpolateFromMask(maskedImage, fwhm, growSaturatedFootprints=1,
804 maskNameList=['SAT'], fallbackValue=None, useLegacyInterp=True):
805 """Interpolate over defects identified by a particular set of mask planes.
807 Parameters
808 ----------
809 maskedImage : `lsst.afw.image.MaskedImage`
810 Image to process.
811 fwhm : `float`
812 FWHM of double Gaussian smoothing kernel.
813 growSaturatedFootprints : scalar, optional
814 Number of pixels to grow footprints for saturated pixels.
815 maskNameList : `List` of `str`, optional
816 Mask plane name.
817 fallbackValue : scalar, optional
818 Value of last resort for interpolation.
820 Notes
821 -----
822 The ``fwhm`` parameter is used to create a PSF, but the underlying
823 interpolation code (`lsst.meas.algorithms.interpolateOverDefects`) does
824 not currently make use of this information.
825 """
826 mask = maskedImage.getMask()
828 if growSaturatedFootprints > 0 and "SAT" in maskNameList:
829 # If we are interpolating over an area larger than the original masked
830 # region, we need to expand the original mask bit to the full area to
831 # explain why we interpolated there.
832 growMasks(mask, radius=growSaturatedFootprints, maskNameList=['SAT'], maskValue="SAT")
834 thresh = afwDetection.Threshold(mask.getPlaneBitMask(maskNameList), afwDetection.Threshold.BITMASK)
835 fpSet = afwDetection.FootprintSet(mask, thresh)
836 defectList = Defects.fromFootprintList(fpSet.getFootprints())
838 interpolateDefectList(maskedImage, defectList, fwhm, fallbackValue=fallbackValue,
839 maskNameList=maskNameList, useLegacyInterp=useLegacyInterp)
841 return maskedImage
844def saturationCorrection(maskedImage, saturation, fwhm, growFootprints=1, interpolate=True, maskName='SAT',
845 fallbackValue=None, useLegacyInterp=True):
846 """Mark saturated pixels and optionally interpolate over them
848 Parameters
849 ----------
850 maskedImage : `lsst.afw.image.MaskedImage`
851 Image to process.
852 saturation : scalar
853 Saturation level used as the detection threshold.
854 fwhm : `float`
855 FWHM of double Gaussian smoothing kernel.
856 growFootprints : scalar, optional
857 Number of pixels to grow footprints of detected regions.
858 interpolate : Bool, optional
859 If True, saturated pixels are interpolated over.
860 maskName : str, optional
861 Mask plane name.
862 fallbackValue : scalar, optional
863 Value of last resort for interpolation.
865 Notes
866 -----
867 The ``fwhm`` parameter is used to create a PSF, but the underlying
868 interpolation code (`lsst.meas.algorithms.interpolateOverDefects`) does
869 not currently make use of this information.
870 """
871 defectList = makeThresholdMask(
872 maskedImage=maskedImage,
873 threshold=saturation,
874 growFootprints=growFootprints,
875 maskName=maskName,
876 )
877 if interpolate:
878 interpolateDefectList(maskedImage, defectList, fwhm, fallbackValue=fallbackValue,
879 maskNameList=[maskName], useLegacyInterp=useLegacyInterp)
881 return maskedImage
884def trimToMatchCalibBBox(rawMaskedImage, calibMaskedImage):
885 """Compute number of edge trim pixels to match the calibration data.
887 Use the dimension difference between the raw exposure and the
888 calibration exposure to compute the edge trim pixels. This trim
889 is applied symmetrically, with the same number of pixels masked on
890 each side.
892 Parameters
893 ----------
894 rawMaskedImage : `lsst.afw.image.MaskedImage`
895 Image to trim.
896 calibMaskedImage : `lsst.afw.image.MaskedImage`
897 Calibration image to draw new bounding box from.
899 Returns
900 -------
901 replacementMaskedImage : `lsst.afw.image.MaskedImage`
902 ``rawMaskedImage`` trimmed to the appropriate size.
904 Raises
905 ------
906 RuntimeError
907 Raised if ``rawMaskedImage`` cannot be symmetrically trimmed to
908 match ``calibMaskedImage``.
909 """
910 nx, ny = rawMaskedImage.getBBox().getDimensions() - calibMaskedImage.getBBox().getDimensions()
911 if nx != ny: 911 ↛ 912line 911 didn't jump to line 912 because the condition on line 911 was never true
912 raise RuntimeError("Raw and calib maskedImages are trimmed differently in X and Y.")
913 if nx % 2 != 0: 913 ↛ 914line 913 didn't jump to line 914 because the condition on line 913 was never true
914 raise RuntimeError("Calibration maskedImage is trimmed unevenly in X.")
915 if nx < 0: 915 ↛ 916line 915 didn't jump to line 916 because the condition on line 915 was never true
916 raise RuntimeError("Calibration maskedImage is larger than raw data.")
918 nEdge = nx//2
919 if nEdge > 0:
920 replacementMaskedImage = rawMaskedImage[nEdge:-nEdge, nEdge:-nEdge, afwImage.LOCAL]
921 SourceDetectionTask.setEdgeBits(
922 rawMaskedImage,
923 replacementMaskedImage.getBBox(),
924 rawMaskedImage.getMask().getPlaneBitMask("EDGE")
925 )
926 else:
927 replacementMaskedImage = rawMaskedImage
929 return replacementMaskedImage
932def biasCorrection(maskedImage, biasMaskedImage, trimToFit=False, imageOnly=False):
933 """Apply bias correction in place.
935 Parameters
936 ----------
937 maskedImage : `lsst.afw.image.MaskedImage`
938 Image to process. The image is modified by this method.
939 biasMaskedImage : `lsst.afw.image.MaskedImage`
940 Bias image of the same size as ``maskedImage``
941 trimToFit : `Bool`, optional
942 If True, raw data is symmetrically trimmed to match
943 calibration size.
944 imageOnly : `bool`, optional
945 Apply the bias to the image plane only, skipping mask
946 and variance.
948 Raises
949 ------
950 RuntimeError
951 Raised if ``maskedImage`` and ``biasMaskedImage`` do not have
952 the same size.
954 """
955 if trimToFit:
956 maskedImage = trimToMatchCalibBBox(maskedImage, biasMaskedImage)
958 if maskedImage.getBBox(afwImage.LOCAL) != biasMaskedImage.getBBox(afwImage.LOCAL):
959 raise RuntimeError("maskedImage bbox %s != biasMaskedImage bbox %s" %
960 (maskedImage.getBBox(afwImage.LOCAL), biasMaskedImage.getBBox(afwImage.LOCAL)))
961 if imageOnly: 961 ↛ 962line 961 didn't jump to line 962 because the condition on line 961 was never true
962 maskedImage.image -= biasMaskedImage.image
963 else:
964 maskedImage -= biasMaskedImage
967def darkCorrection(
968 maskedImage,
969 darkMaskedImage,
970 expScale,
971 darkScale,
972 invert=False,
973 trimToFit=False,
974 imageOnly=False,
975):
976 """Apply dark correction in place.
978 Parameters
979 ----------
980 maskedImage : `lsst.afw.image.MaskedImage`
981 Image to process. The image is modified by this method.
982 darkMaskedImage : `lsst.afw.image.MaskedImage`
983 Dark image of the same size as ``maskedImage``.
984 expScale : scalar
985 Dark exposure time for ``maskedImage``.
986 darkScale : scalar
987 Dark exposure time for ``darkMaskedImage``.
988 invert : `Bool`, optional
989 If True, re-add the dark to an already corrected image.
990 trimToFit : `Bool`, optional
991 If True, raw data is symmetrically trimmed to match
992 calibration size.
993 imageOnly : `bool`, optional
994 Apply the dark to the image plane only, skipping mask
995 and variance.
997 Raises
998 ------
999 RuntimeError
1000 Raised if ``maskedImage`` and ``darkMaskedImage`` do not have
1001 the same size.
1003 Notes
1004 -----
1005 The dark correction is applied by calculating:
1006 maskedImage -= dark * expScaling / darkScaling
1007 """
1008 if trimToFit:
1009 maskedImage = trimToMatchCalibBBox(maskedImage, darkMaskedImage)
1011 if maskedImage.getBBox(afwImage.LOCAL) != darkMaskedImage.getBBox(afwImage.LOCAL):
1012 raise RuntimeError("maskedImage bbox %s != darkMaskedImage bbox %s" %
1013 (maskedImage.getBBox(afwImage.LOCAL), darkMaskedImage.getBBox(afwImage.LOCAL)))
1015 scale = expScale / darkScale
1016 if not invert:
1017 if imageOnly: 1017 ↛ 1018line 1017 didn't jump to line 1018 because the condition on line 1017 was never true
1018 maskedImage.image.scaledMinus(scale, darkMaskedImage.image)
1019 else:
1020 maskedImage.scaledMinus(scale, darkMaskedImage)
1021 else:
1022 if imageOnly: 1022 ↛ 1023line 1022 didn't jump to line 1023 because the condition on line 1022 was never true
1023 maskedImage.image.scaledPlus(scale, darkMaskedImage.image)
1024 else:
1025 maskedImage.scaledPlus(scale, darkMaskedImage)
1028def updateVariance(maskedImage, gain, readNoise, replace=True):
1029 """Set the variance plane based on the image plane.
1031 The maskedImage must have units of `adu` (if gain != 1.0) or
1032 electron (if gain == 1.0). This routine will always produce a
1033 variance plane in the same units as the image.
1035 Parameters
1036 ----------
1037 maskedImage : `lsst.afw.image.MaskedImage`
1038 Image to process. The variance plane is modified.
1039 gain : scalar
1040 The amplifier gain in electron/adu.
1041 readNoise : scalar
1042 The amplifier read noise in electron/pixel.
1043 replace : `bool`, optional
1044 Replace the current variance? If False, the image
1045 variance will be added to the current variance plane.
1046 """
1047 var = maskedImage.variance
1048 if replace:
1049 var[:, :] = maskedImage.image
1050 else:
1051 var[:, :] += maskedImage.image
1052 var /= gain
1053 var += (readNoise/gain)**2
1056def flatCorrection(
1057 maskedImage,
1058 flatMaskedImage,
1059 scalingType,
1060 userScale=1.0,
1061 invert=False,
1062 trimToFit=False,
1063 imageOnly=False,
1064):
1065 """Apply flat correction in place.
1067 Parameters
1068 ----------
1069 maskedImage : `lsst.afw.image.MaskedImage`
1070 Image to process. The image is modified.
1071 flatMaskedImage : `lsst.afw.image.MaskedImage`
1072 Flat image of the same size as ``maskedImage``
1073 scalingType : str
1074 Flat scale computation method. Allowed values are 'MEAN',
1075 'MEDIAN', or 'USER'.
1076 userScale : scalar, optional
1077 Scale to use if ``scalingType='USER'``.
1078 invert : `bool`, optional
1079 If True, unflatten an already flattened image.
1080 trimToFit : `bool`, optional
1081 If True, raw data is symmetrically trimmed to match
1082 calibration size.
1083 imageOnly : `bool`, optional
1084 Apply the flat to the image plane only, skipping mask
1085 and variance.
1087 Raises
1088 ------
1089 RuntimeError
1090 Raised if ``maskedImage`` and ``flatMaskedImage`` do not have
1091 the same size or if ``scalingType`` is not an allowed value.
1092 """
1093 if trimToFit:
1094 maskedImage = trimToMatchCalibBBox(maskedImage, flatMaskedImage)
1096 if maskedImage.getBBox(afwImage.LOCAL) != flatMaskedImage.getBBox(afwImage.LOCAL):
1097 raise RuntimeError("maskedImage bbox %s != flatMaskedImage bbox %s" %
1098 (maskedImage.getBBox(afwImage.LOCAL), flatMaskedImage.getBBox(afwImage.LOCAL)))
1100 # Figure out scale from the data
1101 # Ideally the flats are normalized by the calibration product pipeline,
1102 # but this allows some flexibility in the case that the flat is created by
1103 # some other mechanism.
1104 if scalingType in ('MEAN', 'MEDIAN'):
1105 scalingType = afwMath.stringToStatisticsProperty(scalingType)
1106 flatScale = afwMath.makeStatistics(flatMaskedImage.image, scalingType).getValue()
1107 elif scalingType == 'USER':
1108 flatScale = userScale
1109 else:
1110 raise RuntimeError('%s : %s not implemented' % ("flatCorrection", scalingType))
1112 if not invert:
1113 if imageOnly: 1113 ↛ 1114line 1113 didn't jump to line 1114 because the condition on line 1113 was never true
1114 maskedImage.image.scaledDivides(1.0/flatScale, flatMaskedImage.image)
1115 else:
1116 maskedImage.scaledDivides(1.0/flatScale, flatMaskedImage)
1117 else:
1118 if imageOnly: 1118 ↛ 1119line 1118 didn't jump to line 1119 because the condition on line 1118 was never true
1119 maskedImage.image.scaledMultiplies(1.0/flatScale, flatMaskedImage.image)
1120 else:
1121 maskedImage.scaledMultiplies(1.0/flatScale, flatMaskedImage)
1124def illuminationCorrection(maskedImage, illumMaskedImage, illumScale, trimToFit=True):
1125 """Apply illumination correction in place.
1127 Parameters
1128 ----------
1129 maskedImage : `lsst.afw.image.MaskedImage`
1130 Image to process. The image is modified.
1131 illumMaskedImage : `lsst.afw.image.MaskedImage`
1132 Illumination correction image of the same size as ``maskedImage``.
1133 illumScale : scalar
1134 Scale factor for the illumination correction.
1135 trimToFit : `Bool`, optional
1136 If True, raw data is symmetrically trimmed to match
1137 calibration size.
1139 Raises
1140 ------
1141 RuntimeError
1142 Raised if ``maskedImage`` and ``illumMaskedImage`` do not have
1143 the same size.
1144 """
1145 if trimToFit:
1146 maskedImage = trimToMatchCalibBBox(maskedImage, illumMaskedImage)
1148 if maskedImage.getBBox(afwImage.LOCAL) != illumMaskedImage.getBBox(afwImage.LOCAL):
1149 raise RuntimeError("maskedImage bbox %s != illumMaskedImage bbox %s" %
1150 (maskedImage.getBBox(afwImage.LOCAL), illumMaskedImage.getBBox(afwImage.LOCAL)))
1152 maskedImage.scaledDivides(1.0/illumScale, illumMaskedImage)
1155@contextmanager
1156def gainContext(exp, image, apply, gains=None, invert=False, isTrimmed=True):
1157 """Context manager that applies and removes gain.
1159 Parameters
1160 ----------
1161 exp : `lsst.afw.image.Exposure`
1162 Exposure to apply/remove gain.
1163 image : `lsst.afw.image.Image`
1164 Image to apply/remove gain.
1165 apply : `bool`
1166 If True, apply and remove the amplifier gain.
1167 gains : `dict` [`str`, `float`], optional
1168 A dictionary, keyed by amplifier name, of the gains to use.
1169 If gains is None, the nominal gains in the amplifier object are used.
1170 invert : `bool`, optional
1171 Invert the gains (e.g. convert electrons to adu temporarily)?
1172 isTrimmed : `bool`, optional
1173 Is this a trimmed exposure?
1175 Yields
1176 ------
1177 exp : `lsst.afw.image.Exposure`
1178 Exposure with the gain applied.
1179 """
1180 # check we have all of them if provided because mixing and matching would
1181 # be a real mess
1182 if gains and apply is True:
1183 ampNames = [amp.getName() for amp in exp.getDetector()]
1184 for ampName in ampNames:
1185 if ampName not in gains.keys(): 1185 ↛ 1186line 1185 didn't jump to line 1186 because the condition on line 1185 was never true
1186 raise RuntimeError(f"Gains provided to gain context, but no entry found for amp {ampName}")
1188 if apply:
1189 ccd = exp.getDetector()
1190 for amp in ccd:
1191 sim = image.Factory(image, amp.getBBox() if isTrimmed else amp.getRawBBox())
1192 if gains:
1193 gain = gains[amp.getName()]
1194 else:
1195 gain = amp.getGain()
1196 if invert: 1196 ↛ 1197line 1196 didn't jump to line 1197 because the condition on line 1196 was never true
1197 sim /= gain
1198 else:
1199 sim *= gain
1201 try:
1202 yield exp
1203 finally:
1204 if apply:
1205 ccd = exp.getDetector()
1206 for amp in ccd:
1207 sim = image.Factory(image, amp.getBBox() if isTrimmed else amp.getRawBBox())
1208 if gains:
1209 gain = gains[amp.getName()]
1210 else:
1211 gain = amp.getGain()
1212 if invert: 1212 ↛ 1213line 1212 didn't jump to line 1213 because the condition on line 1212 was never true
1213 sim *= gain
1214 else:
1215 sim /= gain
1218def attachTransmissionCurve(exposure, opticsTransmission=None, filterTransmission=None,
1219 sensorTransmission=None, atmosphereTransmission=None):
1220 """Attach a TransmissionCurve to an Exposure, given separate curves for
1221 different components.
1223 Parameters
1224 ----------
1225 exposure : `lsst.afw.image.Exposure`
1226 Exposure object to modify by attaching the product of all given
1227 ``TransmissionCurves`` in post-assembly trimmed detector coordinates.
1228 Must have a valid ``Detector`` attached that matches the detector
1229 associated with sensorTransmission.
1230 opticsTransmission : `lsst.afw.image.TransmissionCurve`
1231 A ``TransmissionCurve`` that represents the throughput of the optics,
1232 to be evaluated in focal-plane coordinates.
1233 filterTransmission : `lsst.afw.image.TransmissionCurve`
1234 A ``TransmissionCurve`` that represents the throughput of the filter
1235 itself, to be evaluated in focal-plane coordinates.
1236 sensorTransmission : `lsst.afw.image.TransmissionCurve`
1237 A ``TransmissionCurve`` that represents the throughput of the sensor
1238 itself, to be evaluated in post-assembly trimmed detector coordinates.
1239 atmosphereTransmission : `lsst.afw.image.TransmissionCurve`
1240 A ``TransmissionCurve`` that represents the throughput of the
1241 atmosphere, assumed to be spatially constant.
1243 Returns
1244 -------
1245 combined : `lsst.afw.image.TransmissionCurve`
1246 The TransmissionCurve attached to the exposure.
1248 Notes
1249 -----
1250 All ``TransmissionCurve`` arguments are optional; if none are provided, the
1251 attached ``TransmissionCurve`` will have unit transmission everywhere.
1252 """
1253 combined = afwImage.TransmissionCurve.makeIdentity()
1254 if atmosphereTransmission is not None:
1255 combined *= atmosphereTransmission
1256 if opticsTransmission is not None:
1257 combined *= opticsTransmission
1258 if filterTransmission is not None:
1259 combined *= filterTransmission
1260 detector = exposure.getDetector()
1261 fpToPix = detector.getTransform(fromSys=camGeom.FOCAL_PLANE,
1262 toSys=camGeom.PIXELS)
1263 combined = combined.transformedBy(fpToPix)
1264 if sensorTransmission is not None:
1265 combined *= sensorTransmission
1266 exposure.getInfo().setTransmissionCurve(combined)
1267 return combined
1270def applyGains(exposure, normalizeGains=False, ptcGains=None, isTrimmed=True):
1271 """Scale an exposure by the amplifier gains.
1273 Parameters
1274 ----------
1275 exposure : `lsst.afw.image.Exposure`
1276 Exposure to process. The image is modified.
1277 normalizeGains : `Bool`, optional
1278 If True, then amplifiers are scaled to force the median of
1279 each amplifier to equal the median of those medians.
1280 ptcGains : `dict`[`str`], optional
1281 Dictionary keyed by amp name containing the PTC gains.
1282 isTrimmed : `bool`, optional
1283 Is the input image trimmed?
1284 """
1285 ccd = exposure.getDetector()
1286 ccdImage = exposure.getMaskedImage()
1288 medians = []
1289 for amp in ccd:
1290 if isTrimmed:
1291 sim = ccdImage.Factory(ccdImage, amp.getBBox())
1292 else:
1293 sim = ccdImage.Factory(ccdImage, amp.getRawBBox())
1294 if ptcGains: 1294 ↛ 1297line 1294 didn't jump to line 1297 because the condition on line 1294 was always true
1295 sim *= ptcGains[amp.getName()]
1296 else:
1297 sim *= amp.getGain()
1299 if normalizeGains: 1299 ↛ 1300line 1299 didn't jump to line 1300 because the condition on line 1299 was never true
1300 medians.append(numpy.median(sim.getImage().getArray()))
1302 if normalizeGains: 1302 ↛ 1303line 1302 didn't jump to line 1303 because the condition on line 1302 was never true
1303 median = numpy.median(numpy.array(medians))
1304 for index, amp in enumerate(ccd):
1305 if isTrimmed:
1306 sim = ccdImage.Factory(ccdImage, amp.getBBox())
1307 else:
1308 sim = ccdImage.Factory(ccdImage, amp.getRawBBox())
1309 if medians[index] != 0.0:
1310 sim *= median/medians[index]
1313def widenSaturationTrails(mask):
1314 """Grow the saturation trails by an amount dependent on the width of the
1315 trail.
1317 Parameters
1318 ----------
1319 mask : `lsst.afw.image.Mask`
1320 Mask which will have the saturated areas grown.
1321 """
1323 extraGrowDict = {}
1324 for i in range(1, 6):
1325 extraGrowDict[i] = 0
1326 for i in range(6, 8):
1327 extraGrowDict[i] = 1
1328 for i in range(8, 10):
1329 extraGrowDict[i] = 3
1330 extraGrowMax = 4
1332 if extraGrowMax <= 0: 1332 ↛ 1333line 1332 didn't jump to line 1333 because the condition on line 1332 was never true
1333 return
1335 saturatedBit = mask.getPlaneBitMask("SAT")
1337 xmin, ymin = mask.getBBox().getMin()
1338 width = mask.getWidth()
1340 thresh = afwDetection.Threshold(saturatedBit, afwDetection.Threshold.BITMASK)
1341 fpList = afwDetection.FootprintSet(mask, thresh).getFootprints()
1343 for fp in fpList: 1343 ↛ 1344line 1343 didn't jump to line 1344 because the loop on line 1343 never started
1344 for s in fp.getSpans():
1345 x0, x1 = s.getX0(), s.getX1()
1347 extraGrow = extraGrowDict.get(x1 - x0 + 1, extraGrowMax)
1348 if extraGrow > 0:
1349 y = s.getY() - ymin
1350 x0 -= xmin + extraGrow
1351 x1 -= xmin - extraGrow
1353 if x0 < 0:
1354 x0 = 0
1355 if x1 >= width - 1:
1356 x1 = width - 1
1358 mask.array[y, x0:x1+1] |= saturatedBit
1361def setBadRegions(exposure, badStatistic="MEDIAN"):
1362 """Set all BAD areas of the chip to the average of the rest of the exposure
1364 Parameters
1365 ----------
1366 exposure : `lsst.afw.image.Exposure`
1367 Exposure to mask. The exposure mask is modified.
1368 badStatistic : `str`, optional
1369 Statistic to use to generate the replacement value from the
1370 image data. Allowed values are 'MEDIAN' or 'MEANCLIP'.
1372 Returns
1373 -------
1374 badPixelCount : scalar
1375 Number of bad pixels masked.
1376 badPixelValue : scalar
1377 Value substituted for bad pixels.
1379 Raises
1380 ------
1381 RuntimeError
1382 Raised if `badStatistic` is not an allowed value.
1383 """
1384 if badStatistic == "MEDIAN":
1385 statistic = afwMath.MEDIAN
1386 elif badStatistic == "MEANCLIP":
1387 statistic = afwMath.MEANCLIP
1388 else:
1389 raise RuntimeError("Impossible method %s of bad region correction" % badStatistic)
1391 mi = exposure.getMaskedImage()
1392 mask = mi.getMask()
1393 BAD = mask.getPlaneBitMask("BAD")
1394 INTRP = mask.getPlaneBitMask("INTRP")
1396 sctrl = afwMath.StatisticsControl()
1397 sctrl.setAndMask(BAD)
1398 value = afwMath.makeStatistics(mi, statistic, sctrl).getValue()
1400 maskArray = mask.getArray()
1401 imageArray = mi.getImage().getArray()
1402 badPixels = numpy.logical_and((maskArray & BAD) > 0, (maskArray & INTRP) == 0)
1403 imageArray[:] = numpy.where(badPixels, value, imageArray)
1405 return badPixels.sum(), value
1408def checkFilter(exposure, filterList, log):
1409 """Check to see if an exposure is in a filter specified by a list.
1411 The goal of this is to provide a unified filter checking interface
1412 for all filter dependent stages.
1414 Parameters
1415 ----------
1416 exposure : `lsst.afw.image.Exposure`
1417 Exposure to examine.
1418 filterList : `list` [`str`]
1419 List of physical_filter names to check.
1420 log : `logging.Logger`
1421 Logger to handle messages.
1423 Returns
1424 -------
1425 result : `bool`
1426 True if the exposure's filter is contained in the list.
1427 """
1428 if len(filterList) == 0:
1429 return False
1430 thisFilter = exposure.getFilter()
1431 if thisFilter is None: 1431 ↛ 1432line 1431 didn't jump to line 1432 because the condition on line 1431 was never true
1432 log.warning("No FilterLabel attached to this exposure!")
1433 return False
1435 thisPhysicalFilter = getPhysicalFilter(thisFilter, log)
1436 if thisPhysicalFilter in filterList: 1436 ↛ 1438line 1436 didn't jump to line 1438 because the condition on line 1436 was always true
1437 return True
1438 elif thisFilter.bandLabel in filterList:
1439 if log:
1440 log.warning("Physical filter (%s) should be used instead of band %s for filter configurations"
1441 " (%s)", thisPhysicalFilter, thisFilter.bandLabel, filterList)
1442 return True
1443 else:
1444 return False
1447def getPhysicalFilter(filterLabel, log):
1448 """Get the physical filter label associated with the given filterLabel.
1450 If ``filterLabel`` is `None` or there is no physicalLabel attribute
1451 associated with the given ``filterLabel``, the returned label will be
1452 "Unknown".
1454 Parameters
1455 ----------
1456 filterLabel : `lsst.afw.image.FilterLabel`
1457 The `lsst.afw.image.FilterLabel` object from which to derive the
1458 physical filter label.
1459 log : `logging.Logger`
1460 Logger to handle messages.
1462 Returns
1463 -------
1464 physicalFilter : `str`
1465 The value returned by the physicalLabel attribute of ``filterLabel`` if
1466 it exists, otherwise set to \"Unknown\".
1467 """
1468 if filterLabel is None:
1469 physicalFilter = "Unknown"
1470 log.warning("filterLabel is None. Setting physicalFilter to \"Unknown\".")
1471 else:
1472 try:
1473 physicalFilter = filterLabel.physicalLabel
1474 except RuntimeError:
1475 log.warning("filterLabel has no physicalLabel attribute. Setting physicalFilter to \"Unknown\".")
1476 physicalFilter = "Unknown"
1477 return physicalFilter
1480def countMaskedPixels(maskedIm, maskPlane):
1481 """Count the number of pixels in a given mask plane.
1483 Parameters
1484 ----------
1485 maskedIm : `~lsst.afw.image.MaskedImage`
1486 Masked image to examine.
1487 maskPlane : `str`
1488 Name of the mask plane to examine.
1490 Returns
1491 -------
1492 nPix : `int`
1493 Number of pixels in the requested mask plane.
1494 """
1495 maskBit = maskedIm.mask.getPlaneBitMask(maskPlane)
1496 nPix = numpy.where(numpy.bitwise_and(maskedIm.mask.array, maskBit))[0].flatten().size
1497 return nPix
1500def getExposureGains(exposure):
1501 """Get the per-amplifier gains used for this exposure.
1503 Parameters
1504 ----------
1505 exposure : `lsst.afw.image.Exposure`
1506 The exposure to find gains for.
1508 Returns
1509 -------
1510 gains : `dict` [`str` `float`]
1511 Dictionary of gain values, keyed by amplifier name.
1512 Returns empty dict when detector is None.
1513 """
1514 det = exposure.getDetector()
1515 if det is None: 1515 ↛ 1516line 1515 didn't jump to line 1516 because the condition on line 1515 was never true
1516 return dict()
1518 metadata = exposure.getMetadata()
1519 gains = {}
1520 for amp in det:
1521 ampName = amp.getName()
1522 # The key may use the new LSST ISR or the old LSST prefix
1523 if (key1 := f"LSST ISR GAIN {ampName}") in metadata:
1524 gains[ampName] = metadata[key1]
1525 elif (key2 := f"LSST GAIN {ampName}") in metadata:
1526 gains[ampName] = metadata[key2]
1527 else:
1528 gains[ampName] = amp.getGain()
1529 return gains
1532def getExposureReadNoises(exposure):
1533 """Get the per-amplifier read noise used for this exposure.
1535 Parameters
1536 ----------
1537 exposure : `lsst.afw.image.Exposure`
1538 The exposure to find read noise for.
1540 Returns
1541 -------
1542 readnoises : `dict` [`str` `float`]
1543 Dictionary of read noise values, keyed by amplifier name.
1544 Returns empty dict when detector is None.
1545 """
1546 det = exposure.getDetector()
1547 if det is None: 1547 ↛ 1548line 1547 didn't jump to line 1548 because the condition on line 1547 was never true
1548 return dict()
1550 metadata = exposure.getMetadata()
1551 readnoises = {}
1552 for amp in det:
1553 ampName = amp.getName()
1554 # The key may use the new LSST ISR or the old LSST prefix
1555 if (key1 := f"LSST ISR READNOISE {ampName}") in metadata:
1556 readnoises[ampName] = metadata[key1]
1557 elif (key2 := f"LSST READNOISE {ampName}") in metadata:
1558 readnoises[ampName] = metadata[key2]
1559 else:
1560 readnoises[ampName] = amp.getReadNoise()
1561 return readnoises
1564def isTrimmedExposure(exposure):
1565 """Check if the unused pixels (pre-/over-scan pixels) have
1566 been trimmed from an exposure.
1568 Parameters
1569 ----------
1570 exposure : `lsst.afw.image.Exposure`
1571 The exposure to check.
1573 Returns
1574 -------
1575 result : `bool`
1576 True if the image is trimmed, else False.
1577 """
1578 return exposure.getDetector().getBBox() == exposure.getBBox()
1581def isTrimmedImage(image, detector):
1582 """Check if the unused pixels (pre-/over-scan pixels) have
1583 been trimmed from an image
1585 Parameters
1586 ----------
1587 image : `lsst.afw.image.Image`
1588 The image to check.
1589 detector : `lsst.afw.cameraGeom.Detector`
1590 The detector associated with the image.
1592 Returns
1593 -------
1594 result : `bool`
1595 True if the image is trimmed, else False.
1596 """
1597 return detector.getBBox() == image.getBBox()
1600def compareCameraKeywords(
1601 doRaiseOnCalibMismatch,
1602 cameraKeywordsToCompare,
1603 exposureMetadata,
1604 calib,
1605 calibName,
1606 log=None,
1607):
1608 """Compare header keywords to confirm camera states match.
1610 Parameters
1611 ----------
1612 doRaiseOnCalibMismatch : `bool`
1613 Raise on calibration mismatch? Otherwise, log a warning.
1614 cameraKeywordsToCompare : `list` [`str`]
1615 List of camera keywords to compare.
1616 exposureMetadata : `lsst.daf.base.PropertyList`
1617 Header for the exposure being processed.
1618 calib : `lsst.afw.image.Exposure` or `lsst.ip.isr.IsrCalib`
1619 Calibration to be applied.
1620 calibName : `str`
1621 Calib type for log message.
1622 log : `logging.Logger`, optional
1623 Logger to handle messages.
1624 """
1625 try:
1626 calibMetadata = calib.metadata
1627 except AttributeError:
1628 return
1630 log = log if log else logging.getLogger(__name__)
1632 missingKeywords = []
1633 for keyword in cameraKeywordsToCompare:
1634 exposureValue = exposureMetadata.get(keyword, None)
1635 if exposureValue is None:
1636 log.debug("Sequencer keyword %s not found in exposure metadata.", keyword)
1637 continue
1639 calibValue = calibMetadata.get(keyword, None)
1641 # We don't log here if there is a missing keyword.
1642 if calibValue is None:
1643 missingKeywords.append(keyword)
1644 continue
1646 if exposureValue != calibValue:
1647 if doRaiseOnCalibMismatch:
1648 raise RuntimeError(
1649 "Sequencer mismatch for %s [%s]: exposure: %s calib: %s",
1650 calibName,
1651 keyword,
1652 exposureValue,
1653 calibValue,
1654 )
1655 else:
1656 log.warning(
1657 "Sequencer mismatch for %s [%s]: exposure: %s calib: %s",
1658 calibName,
1659 keyword,
1660 exposureValue,
1661 calibValue,
1662 )
1663 exposureMetadata[f"ISR {calibName.upper()} SEQUENCER MISMATCH"] = True
1665 if missingKeywords:
1666 log.info(
1667 "Calibration %s missing keywords %s, which were not checked.",
1668 calibName,
1669 ",".join(missingKeywords),
1670 )
1673def symmetrize(inputArray):
1674 """ Copy array over 4 quadrants prior to convolution.
1676 Parameters
1677 ----------
1678 inputarray : `numpy.array`
1679 Input array to symmetrize.
1681 Returns
1682 -------
1683 aSym : `numpy.array`
1684 Symmetrized array.
1685 """
1686 targetShape = list(inputArray.shape)
1687 r1, r2 = inputArray.shape[-1], inputArray.shape[-2]
1688 targetShape[-1] = 2*r1-1
1689 targetShape[-2] = 2*r2-1
1690 aSym = numpy.ndarray(tuple(targetShape))
1691 aSym[..., r2-1:, r1-1:] = inputArray
1692 aSym[..., r2-1:, r1-1::-1] = inputArray
1693 aSym[..., r2-1::-1, r1-1::-1] = inputArray
1694 aSym[..., r2-1::-1, r1-1:] = inputArray
1696 return aSym