LSST Applications g063fba187b+cac8b7c890,g0f08755f38+6aee506743,g1653933729+a8ce1bb630,g168dd56ebc+a8ce1bb630,g1a2382251a+b4475c5878,g1dcb35cd9c+8f9bc1652e,g20f6ffc8e0+6aee506743,g217e2c1bcf+73dee94bd0,g28da252d5a+1f19c529b9,g2bbee38e9b+3f2625acfc,g2bc492864f+3f2625acfc,g3156d2b45e+6e55a43351,g32e5bea42b+1bb94961c2,g347aa1857d+3f2625acfc,g35bb328faa+a8ce1bb630,g3a166c0a6a+3f2625acfc,g3e281a1b8c+c5dd892a6c,g3e8969e208+a8ce1bb630,g414038480c+5927e1bc1e,g41af890bb2+8a9e676b2a,g7af13505b9+809c143d88,g80478fca09+6ef8b1810f,g82479be7b0+f568feb641,g858d7b2824+6aee506743,g89c8672015+f4add4ffd5,g9125e01d80+a8ce1bb630,ga5288a1d22+2903d499ea,gb58c049af0+d64f4d3760,gc28159a63d+3f2625acfc,gcab2d0539d+b12535109e,gcf0d15dbbd+46a3f46ba9,gda6a2b7d83+46a3f46ba9,gdaeeff99f8+1711a396fd,ge79ae78c31+3f2625acfc,gef2f8181fd+0a71e47438,gf0baf85859+c1f95f4921,gfa517265be+6aee506743,gfa999e8aa5+17cd334064,w.2024.51
LSST Data Management Base Package
Loading...
Searching...
No Matches
skyCorrection.py
Go to the documentation of this file.
1# This file is part of pipe_tasks.
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__ = ["SkyCorrectionTask", "SkyCorrectionConfig"]
23
24import warnings
25
26import lsst.afw.image as afwImage
27import lsst.afw.math as afwMath
28import lsst.pipe.base.connectionTypes as cT
29import numpy as np
30from lsst.pex.config import Config, ConfigField, ConfigurableField, Field
31from lsst.pipe.base import PipelineTask, PipelineTaskConfig, PipelineTaskConnections, Struct
33 FocalPlaneBackground,
34 FocalPlaneBackgroundConfig,
35 MaskObjectsTask,
36 SkyMeasurementTask,
37)
38from lsst.pipe.tasks.visualizeVisit import VisualizeMosaicExpConfig, VisualizeMosaicExpTask
39
40
41def _skyFrameLookup(datasetType, registry, quantumDataId, collections):
42 """Lookup function to identify sky frames.
43
44 Parameters
45 ----------
46 datasetType : `lsst.daf.butler.DatasetType`
47 Dataset to lookup.
48 registry : `lsst.daf.butler.Registry`
49 Butler registry to query.
50 quantumDataId : `lsst.daf.butler.DataCoordinate`
51 Data id to transform to find sky frames.
52 The ``detector`` entry will be stripped.
53 collections : `lsst.daf.butler.CollectionSearch`
54 Collections to search through.
55
56 Returns
57 -------
58 results : `list` [`lsst.daf.butler.DatasetRef`]
59 List of datasets that will be used as sky calibration frames.
60 """
61 newDataId = quantumDataId.subset(registry.dimensions.conform(["instrument", "visit"]))
62 skyFrames = []
63 for dataId in registry.queryDataIds(["visit", "detector"], dataId=newDataId).expanded():
64 skyFrame = registry.findDataset(
65 datasetType, dataId, collections=collections, timespan=dataId.timespan
66 )
67 skyFrames.append(skyFrame)
68 return skyFrames
69
70
71def _reorderAndPadList(inputList, inputKeys, outputKeys, padWith=None):
72 """Match the order of one list to another, padding if necessary.
73
74 Parameters
75 ----------
76 inputList : `list`
77 List to be reordered and padded. Elements can be any type.
78 inputKeys : iterable
79 Iterable of values to be compared with outputKeys.
80 Length must match `inputList`.
81 outputKeys : iterable
82 Iterable of values to be compared with inputKeys.
83 padWith :
84 Any value to be inserted where one of inputKeys is not in outputKeys.
85
86 Returns
87 -------
88 outputList : `list`
89 Copy of inputList reordered per outputKeys and padded with `padWith`
90 so that the length matches length of outputKeys.
91 """
92 outputList = []
93 for outputKey in outputKeys:
94 if outputKey in inputKeys:
95 outputList.append(inputList[inputKeys.index(outputKey)])
96 else:
97 outputList.append(padWith)
98 return outputList
99
100
101class SkyCorrectionConnections(PipelineTaskConnections, dimensions=("instrument", "visit")):
102 rawLinker = cT.Input(
103 doc="Raw data to provide exp-visit linkage to connect calExp inputs to camera/sky calibs.",
104 name="raw",
105 multiple=True,
106 deferLoad=True,
107 storageClass="Exposure",
108 dimensions=["instrument", "exposure", "detector"],
109 )
110 calExps = cT.Input(
111 doc="Background-subtracted calibrated exposures.",
112 name="calexp",
113 multiple=True,
114 storageClass="ExposureF",
115 dimensions=["instrument", "visit", "detector"],
116 )
117 calBkgs = cT.Input(
118 doc="Subtracted backgrounds for input calibrated exposures.",
119 multiple=True,
120 name="calexpBackground",
121 storageClass="Background",
122 dimensions=["instrument", "visit", "detector"],
123 )
124 skyFrames = cT.PrerequisiteInput(
125 doc="Calibration sky frames.",
126 name="sky",
127 multiple=True,
128 storageClass="ExposureF",
129 dimensions=["instrument", "physical_filter", "detector"],
130 isCalibration=True,
131 lookupFunction=_skyFrameLookup,
132 )
133 camera = cT.PrerequisiteInput(
134 doc="Input camera.",
135 name="camera",
136 storageClass="Camera",
137 dimensions=["instrument"],
138 isCalibration=True,
139 )
140 skyCorr = cT.Output(
141 doc="Sky correction data, to be subtracted from the calibrated exposures.",
142 name="skyCorr",
143 multiple=True,
144 storageClass="Background",
145 dimensions=["instrument", "visit", "detector"],
146 )
147 calExpMosaic = cT.Output(
148 doc="Full focal plane mosaicked image of the sky corrected calibrated exposures.",
149 name="calexp_skyCorr_visit_mosaic",
150 storageClass="ImageF",
151 dimensions=["instrument", "visit"],
152 )
153 calBkgMosaic = cT.Output(
154 doc="Full focal plane mosaicked image of the sky corrected calibrated exposure backgrounds.",
155 name="calexpBackground_skyCorr_visit_mosaic",
156 storageClass="ImageF",
157 dimensions=["instrument", "visit"],
158 )
159
160 def __init__(self, *, config: "SkyCorrectionConfig | None" = None):
161 super().__init__(config=config)
162 assert config is not None
163 if not config.doSky:
164 del self.skyFrames
165
166
167class SkyCorrectionConfig(PipelineTaskConfig, pipelineConnections=SkyCorrectionConnections):
168 maskObjects = ConfigurableField(
169 target=MaskObjectsTask,
170 doc="Mask Objects",
171 )
172 doMaskObjects = Field(
173 dtype=bool,
174 default=True,
175 doc="Iteratively mask objects to find good sky?",
176 )
177 bgModel1 = ConfigField(
178 dtype=FocalPlaneBackgroundConfig,
179 doc="Initial background model, prior to sky frame subtraction",
180 )
181 undoBgModel1 = Field(
182 dtype=bool,
183 default=False,
184 doc="If True, adds back initial background model after sky and removes bgModel1 from the list",
185 )
187 target=SkyMeasurementTask,
188 doc="Sky measurement",
189 )
190 doSky = Field(
191 dtype=bool,
192 default=True,
193 doc="Do sky frame subtraction?",
194 )
195 bgModel2 = ConfigField(
196 dtype=FocalPlaneBackgroundConfig,
197 doc="Final (cleanup) background model, after sky frame subtraction",
198 )
199 doBgModel2 = Field(
200 dtype=bool,
201 default=True,
202 doc="Do final (cleanup) background model subtraction, after sky frame subtraction?",
203 )
204 binning = Field(
205 dtype=int,
206 default=8,
207 doc="Binning factor for constructing full focal plane '*_camera' output datasets",
208 )
209
210 def setDefaults(self):
211 Config.setDefaults(self)
212 self.bgModel2.doSmooth = True
213 self.bgModel2.minFrac = 0.5
214 self.bgModel2.xSize = 256
215 self.bgModel2.ySize = 256
216 self.bgModel2.smoothScale = 1.0
217
218 def validate(self):
219 super().validate()
220 if self.undoBgModel1 and not self.doSky and not self.doBgModel2:
221 raise ValueError("If undoBgModel1 is True, task requires at least one of doSky or doBgModel2.")
222
223
224class SkyCorrectionTask(PipelineTask):
225 """Perform a full focal plane sky correction."""
226
227 ConfigClass = SkyCorrectionConfig
228 _DefaultName = "skyCorr"
229
230 def __init__(self, *args, **kwargs):
231 super().__init__(**kwargs)
232 self.makeSubtask("sky")
233 self.makeSubtask("maskObjects")
234
235 def runQuantum(self, butlerQC, inputRefs, outputRefs):
236 # Sort the calExps, calBkgs and skyFrames inputRefs and the
237 # skyCorr outputRef by detector ID to ensure reproducibility.
238 detectorOrder = [ref.dataId["detector"] for ref in inputRefs.calExps]
239 detectorOrder.sort()
240 inputRefs.calExps = _reorderAndPadList(
241 inputRefs.calExps, [ref.dataId["detector"] for ref in inputRefs.calExps], detectorOrder
242 )
243 inputRefs.calBkgs = _reorderAndPadList(
244 inputRefs.calBkgs, [ref.dataId["detector"] for ref in inputRefs.calBkgs], detectorOrder
245 )
246 # Only attempt to fetch sky frames if they are going to be applied.
247 if self.config.doSky:
248 inputRefs.skyFrames = _reorderAndPadList(
249 inputRefs.skyFrames, [ref.dataId["detector"] for ref in inputRefs.skyFrames], detectorOrder
250 )
251 else:
252 inputRefs.skyFrames = []
253 outputRefs.skyCorr = _reorderAndPadList(
254 outputRefs.skyCorr, [ref.dataId["detector"] for ref in outputRefs.skyCorr], detectorOrder
255 )
256 inputs = butlerQC.get(inputRefs)
257 inputs.pop("rawLinker", None)
258 outputs = self.run(**inputs)
259 butlerQC.put(outputs, outputRefs)
260
261 def run(self, calExps, calBkgs, skyFrames, camera):
262 """Perform sky correction on a visit.
263
264 The original visit-level background is first restored to the calibrated
265 exposure and the existing background model is inverted in-place. If
266 doMaskObjects is True, the mask map associated with this exposure will
267 be iteratively updated (over nIter loops) by re-estimating the
268 background each iteration and redetecting footprints.
269
270 An initial full focal plane sky subtraction (bgModel1) will take place
271 prior to scaling and subtracting the sky frame.
272
273 If doSky is True, the sky frame will be scaled to the flux in the input
274 visit.
275
276 If doBgModel2 is True, a final full focal plane sky subtraction will
277 take place after the sky frame has been subtracted.
278
279 The first N elements of the returned skyCorr will consist of inverted
280 elements of the calexpBackground model (i.e., subtractive). All
281 subsequent elements appended to skyCorr thereafter will be additive
282 such that, when skyCorr is subtracted from a calexp, the net result
283 will be to undo the initial per-detector background solution and then
284 apply the skyCorr model thereafter. Adding skyCorr to a
285 calexpBackground will effectively negate the calexpBackground,
286 returning only the additive background components of the skyCorr
287 background model.
288
289 Parameters
290 ----------
291 calExps : `list` [`lsst.afw.image.ExposureF`]
292 Detector calibrated exposure images for the visit.
293 calBkgs : `list` [`lsst.afw.math.BackgroundList`]
294 Detector background lists matching the calibrated exposures.
295 skyFrames : `list` [`lsst.afw.image.ExposureF`]
296 Sky frame calibration data for the input detectors.
297 camera : `lsst.afw.cameraGeom.Camera`
298 Camera matching the input data to process.
299
300 Returns
301 -------
302 results : `Struct` containing:
303 skyFrameScale : `float`
304 Scale factor applied to the sky frame.
305 skyCorr : `list` [`lsst.afw.math.BackgroundList`]
306 Detector-level sky correction background lists.
307 calExpMosaic : `lsst.afw.image.ExposureF`
308 Visit-level mosaic of the sky corrected data, binned.
309 Analogous to `calexp - skyCorr`.
310 calBkgMosaic : `lsst.afw.image.ExposureF`
311 Visit-level mosaic of the sky correction background, binned.
312 Analogous to `calexpBackground + skyCorr`.
313 """
314 # Restore original backgrounds in-place; optionally refine mask maps
315 numOrigBkgElements = [len(calBkg) for calBkg in calBkgs]
316 _ = self._restoreOriginalBackgroundRefineMask(calExps, calBkgs)
317
318 # Bin exposures, generate full-fp bg, map to CCDs and subtract in-place
319 _ = self._subtractVisitBackground(calExps, calBkgs, camera, self.config.bgModel1)
320 initialBackgroundIndex = len(calBkgs[0]._backgrounds) - 1
321
322 # Subtract a scaled sky frame from all input exposures
323 skyFrameScale = None
324 if self.config.doSky:
325 skyFrameScale = self._subtractSkyFrame(calExps, skyFrames, calBkgs)
326
327 # Adds full-fp bg back onto exposures, removes it from list
328 if self.config.undoBgModel1:
329 _ = self._undoInitialBackground(calExps, calBkgs, initialBackgroundIndex)
330
331 # Bin exposures, generate full-fp bg, map to CCDs and subtract in-place
332 if self.config.doBgModel2:
333 _ = self._subtractVisitBackground(calExps, calBkgs, camera, self.config.bgModel2)
334
335 # Make camera-level images of bg subtracted calexps and subtracted bgs
336 calExpIds = [exp.getDetector().getId() for exp in calExps]
337 skyCorrExtras = []
338 for calBkg, num in zip(calBkgs, numOrigBkgElements):
339 skyCorrExtra = calBkg.clone()
340 skyCorrExtra._backgrounds = skyCorrExtra._backgrounds[num:]
341 skyCorrExtras.append(skyCorrExtra)
342 calExpMosaic = self._binAndMosaic(calExps, camera, self.config.binning, ids=calExpIds, refExps=None)
343 calBkgMosaic = self._binAndMosaic(
344 skyCorrExtras, camera, self.config.binning, ids=calExpIds, refExps=calExps
345 )
346
347 return Struct(
348 skyFrameScale=skyFrameScale, skyCorr=calBkgs, calExpMosaic=calExpMosaic, calBkgMosaic=calBkgMosaic
349 )
350
351 def _restoreOriginalBackgroundRefineMask(self, calExps, calBkgs):
352 """Restore original background to each calexp and invert the related
353 background model; optionally refine the mask plane.
354
355 The original visit-level background is restored to each calibrated
356 exposure and the existing background model is inverted in-place. If
357 doMaskObjects is True, the mask map associated with the exposure will
358 be iteratively updated (over nIter loops) by re-estimating the
359 background each iteration and redetecting footprints.
360
361 The background model modified in-place in this method will comprise the
362 first N elements of the skyCorr dataset type, i.e., these N elements
363 are the inverse of the calexpBackground model. All subsequent elements
364 appended to skyCorr will be additive such that, when skyCorr is
365 subtracted from a calexp, the net result will be to undo the initial
366 per-detector background solution and then apply the skyCorr model
367 thereafter. Adding skyCorr to a calexpBackground will effectively
368 negate the calexpBackground, returning only the additive background
369 components of the skyCorr background model.
370
371 Parameters
372 ----------
373 calExps : `lsst.afw.image.ExposureF`
374 Detector level calexp images to process.
375 calBkgs : `lsst.afw.math.BackgroundList`
376 Detector level background lists associated with the calexps.
377
378 Returns
379 -------
380 calExps : `lsst.afw.image.ExposureF`
381 The calexps with the originally subtracted background restored.
382 skyCorrBases : `lsst.afw.math.BackgroundList`
383 The inverted original background models; the genesis for skyCorrs.
384 """
385 skyCorrBases = []
386 for calExp, calBkg in zip(calExps, calBkgs):
387 image = calExp.getMaskedImage()
388
389 # Invert all elements of the existing bg model; restore in calexp
390 for calBkgElement in calBkg:
391 statsImage = calBkgElement[0].getStatsImage()
392 statsImage *= -1
393 skyCorrBase = calBkg.getImage()
394 image -= skyCorrBase
395
396 # Iteratively subtract bg, re-detect sources, and add bg back on
397 if self.config.doMaskObjects:
398 self.maskObjects.findObjects(calExp)
399
400 stats = np.nanpercentile(skyCorrBase.array, [50, 75, 25])
401 self.log.info(
402 "Detector %d: Original background restored; BG median = %.1f counts, BG IQR = %.1f counts",
403 calExp.getDetector().getId(),
404 -stats[0],
405 np.subtract(*stats[1:]),
406 )
407 skyCorrBases.append(skyCorrBase)
408 return calExps, skyCorrBases
409
410 def _undoInitialBackground(self, calExps, calBkgs, initialBackgroundIndex):
411 """Undo the initial background subtraction (bgModel1) after sky frame
412 subtraction.
413
414 Parameters
415 ----------
416 calExps : `list` [`lsst.afw.image.ExposureF`]
417 Calibrated exposures to be background subtracted.
418 calBkgs : `list` [`lsst.afw.math.BackgroundList`]
419 Background lists associated with the input calibrated exposures.
420 initialBackgroundIndex : `int`
421 Index of the initial background (bgModel1) in the background list.
422
423 Notes
424 -----
425 Inputs are modified in-place.
426 """
427 for calExp, calBkg in zip(calExps, calBkgs):
428 image = calExp.getMaskedImage()
429
430 # Remove bgModel1 from the background list; restore in the image
431 initialBackground = calBkg[initialBackgroundIndex][0].getImageF()
432 image += initialBackground
433 calBkg._backgrounds.pop(initialBackgroundIndex)
434
435 self.log.info(
436 "Detector %d: The initial background model prior to sky frame subtraction (bgModel1) has "
437 "been removed from the background list",
438 calExp.getDetector().getId(),
439 )
440
441 def _subtractVisitBackground(self, calExps, calBkgs, camera, config):
442 """Perform a full focal-plane background subtraction for a visit.
443
444 Generate a full focal plane background model, binning all masked
445 detectors into bins of [bgModelN.xSize, bgModelN.ySize]. After,
446 subtract the resultant background model (translated back into CCD
447 coordinates) from the original detector exposure.
448
449 Return a list of background subtracted images and a list of full focal
450 plane background parameters.
451
452 Parameters
453 ----------
454 calExps : `list` [`lsst.afw.image.ExposureF`]
455 Calibrated exposures to be background subtracted.
456 calBkgs : `list` [`lsst.afw.math.BackgroundList`]
457 Background lists associated with the input calibrated exposures.
458 camera : `lsst.afw.cameraGeom.Camera`
459 Camera description.
460 config : `lsst.pipe.tasks.background.FocalPlaneBackgroundConfig`
461 Configuration to use for background subtraction.
462
463 Returns
464 -------
465 calExps : `list` [`lsst.afw.image.maskedImage.MaskedImageF`]
466 Background subtracted exposures for creating a focal plane image.
467 calBkgs : `list` [`lsst.afw.math.BackgroundList`]
468 Updated background lists with a visit-level model appended.
469 """
470 # Set up empty full focal plane background model object
471 bgModelBase = FocalPlaneBackground.fromCamera(config, camera)
472
473 # Loop over each detector, bin into [xSize, ySize] bins, and update
474 # summed flux (_values) and number of contributing pixels (_numbers)
475 # in focal plane coordinates. Append outputs to bgModels.
476 bgModels = []
477 for calExp in calExps:
478 bgModel = bgModelBase.clone()
479 bgModel.addCcd(calExp)
480 bgModels.append(bgModel)
481
482 # Merge detector models to make a single full focal plane bg model
483 for bgModel, calExp in zip(bgModels, calExps):
484 msg = (
485 "Detector %d: Merging %d unmasked pixels (%.1f%s of detector area) into focal plane "
486 "background model"
487 )
488 self.log.debug(
489 msg,
490 calExp.getDetector().getId(),
491 bgModel._numbers.getArray().sum(),
492 100 * bgModel._numbers.getArray().sum() / calExp.getBBox().getArea(),
493 "%",
494 )
495 bgModelBase.merge(bgModel)
496
497 # Map full focal plane bg solution to detector; subtract from exposure
498 calBkgElements = []
499 for calExp in calExps:
500 _, calBkgElement = self._subtractDetectorBackground(calExp, bgModelBase)
501 calBkgElements.append(calBkgElement)
502
503 msg = (
504 "Focal plane background model constructed using %.2f x %.2f mm (%d x %d pixel) superpixels; "
505 "FP BG median = %.1f counts, FP BG IQR = %.1f counts"
506 )
507 with warnings.catch_warnings():
508 warnings.filterwarnings("ignore", r"invalid value encountered")
509 stats = np.nanpercentile(bgModelBase.getStatsImage().array, [50, 75, 25])
510 self.log.info(
511 msg,
512 config.xSize,
513 config.ySize,
514 int(config.xSize / config.pixelSize),
515 int(config.ySize / config.pixelSize),
516 stats[0],
517 np.subtract(*stats[1:]),
518 )
519
520 for calBkg, calBkgElement in zip(calBkgs, calBkgElements):
521 calBkg.append(calBkgElement[0])
522 return calExps, calBkgs
523
524 def _subtractDetectorBackground(self, calExp, bgModel):
525 """Generate CCD background model and subtract from image.
526
527 Translate the full focal plane background into CCD coordinates and
528 subtract from the original science exposure image.
529
530 Parameters
531 ----------
532 calExp : `lsst.afw.image.ExposureF`
533 Exposure to subtract the background model from.
534 bgModel : `lsst.pipe.tasks.background.FocalPlaneBackground`
535 Full focal plane camera-level background model.
536
537 Returns
538 -------
539 calExp : `lsst.afw.image.ExposureF`
540 Background subtracted input exposure.
541 calBkgElement : `lsst.afw.math.BackgroundList`
542 Detector level realization of the full focal plane bg model.
543 """
544 image = calExp.getMaskedImage()
545 with warnings.catch_warnings():
546 warnings.filterwarnings("ignore", r"invalid value encountered")
547 calBkgElement = bgModel.toCcdBackground(calExp.getDetector(), image.getBBox())
548 image -= calBkgElement.getImage()
549 return calExp, calBkgElement
550
551 def _subtractSkyFrame(self, calExps, skyFrames, calBkgs):
552 """Determine the full focal plane sky frame scale factor relative to
553 an input list of calibrated exposures and subtract.
554
555 This method measures the sky frame scale on all inputs, resulting in
556 values equal to the background method solveScales(). The sky frame is
557 then subtracted as in subtractSkyFrame() using the appropriate scale.
558
559 Input calExps and calBkgs are updated in-place, returning sky frame
560 subtracted calExps and sky frame updated calBkgs, respectively.
561
562 Parameters
563 ----------
564 calExps : `list` [`lsst.afw.image.ExposureF`]
565 Calibrated exposures to be background subtracted.
566 skyFrames : `list` [`lsst.afw.image.ExposureF`]
567 Sky frame calibration data for the input detectors.
568 calBkgs : `list` [`lsst.afw.math.BackgroundList`]
569 Background lists associated with the input calibrated exposures.
570
571 Returns
572 -------
573 scale : `float`
574 Scale factor applied to the sky frame.
575 """
576 skyFrameBgModels = []
577 scales = []
578 for calExp, skyFrame in zip(calExps, skyFrames):
579 skyFrameBgModel = self.sky.exposureToBackground(skyFrame)
580 skyFrameBgModels.append(skyFrameBgModel)
581 # return a tuple of gridded image and sky frame clipped means
582 samples = self.sky.measureScale(calExp.getMaskedImage(), skyFrameBgModel)
583 scales.append(samples)
584 scale = self.sky.solveScales(scales)
585 for calExp, skyFrameBgModel, calBkg in zip(calExps, skyFrameBgModels, calBkgs):
586 # subtract the scaled sky frame model from each calExp in-place,
587 # also updating the calBkg list in-place
588 self.sky.subtractSkyFrame(calExp.getMaskedImage(), skyFrameBgModel, scale, calBkg)
589 self.log.info("Sky frame subtracted with a scale factor of %.5f", scale)
590 return scale
591
592 def _binAndMosaic(self, exposures, camera, binning, ids=None, refExps=None):
593 """Bin input exposures and mosaic across the entire focal plane.
594
595 Input exposures are binned and then mosaicked at the position of
596 the detector in the focal plane of the camera.
597
598 Parameters
599 ----------
600 exposures : `list`
601 Detector level list of either calexp `ExposureF` types or
602 calexpBackground `BackgroundList` types.
603 camera : `lsst.afw.cameraGeom.Camera`
604 Camera matching the input data to process.
605 binning : `int`
606 Binning size to be applied to input images.
607 ids : `list` [`int`], optional
608 List of detector ids to iterate over.
609 refExps : `list` [`lsst.afw.image.ExposureF`], optional
610 If supplied, mask planes from these reference images will be used.
611 Returns
612 -------
613 mosaicImage : `lsst.afw.image.ExposureF`
614 Mosaicked full focal plane image.
615 """
616 refExps = np.resize(refExps, len(exposures)) # type: ignore
617 binnedImages = []
618 for exp, refExp in zip(exposures, refExps):
619 try:
620 nativeImage = exp.getMaskedImage()
621 except AttributeError:
622 nativeImage = afwImage.makeMaskedImage(exp.getImage())
623 if refExp:
624 nativeImage.setMask(refExp.getMask())
625 binnedImage = afwMath.binImage(nativeImage, binning)
626 binnedImages.append(binnedImage)
627 mosConfig = VisualizeMosaicExpConfig()
628 mosConfig.binning = binning
629 mosTask = VisualizeMosaicExpTask(config=mosConfig)
630 imageStruct = mosTask.run(binnedImages, camera, inputIds=ids)
631 mosaicImage = imageStruct.outputData
632 return mosaicImage
__init__(self, *"SkyCorrectionConfig | None" config=None)
_subtractVisitBackground(self, calExps, calBkgs, camera, config)
run(self, calExps, calBkgs, skyFrames, camera)
_subtractSkyFrame(self, calExps, skyFrames, calBkgs)
runQuantum(self, butlerQC, inputRefs, outputRefs)
_binAndMosaic(self, exposures, camera, binning, ids=None, refExps=None)
_undoInitialBackground(self, calExps, calBkgs, initialBackgroundIndex)
_restoreOriginalBackgroundRefineMask(self, calExps, calBkgs)
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > * makeMaskedImage(typename std::shared_ptr< Image< ImagePixelT > > image, typename std::shared_ptr< Mask< MaskPixelT > > mask=Mask< MaskPixelT >(), typename std::shared_ptr< Image< VariancePixelT > > variance=Image< VariancePixelT >())
A function to return a MaskedImage of the correct type (cf.
std::shared_ptr< ImageT > binImage(ImageT const &inImage, int const binX, int const binY, lsst::afw::math::Property const flags=lsst::afw::math::MEAN)
Definition binImage.cc:44
_reorderAndPadList(inputList, inputKeys, outputKeys, padWith=None)
_skyFrameLookup(datasetType, registry, quantumDataId, collections)