Coverage for python/lsst/ip/diffim/makeKernel.py: 20%
147 statements
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-26 08:37 +0000
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-26 08:37 +0000
1# This file is part of ip_diffim.
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/>.
22__all__ = ["MakeKernelConfig", "MakeKernelTask"]
24import numpy as np
26import lsst.afw.detection
27import lsst.afw.image
28import lsst.afw.math
29import lsst.afw.table
30import lsst.daf.base
31import lsst.geom
32from lsst.meas.algorithms import SourceDetectionTask, SubtractBackgroundTask
33from lsst.meas.base import SingleFrameMeasurementTask
34from lsst.pex.exceptions import InvalidParameterError, RangeError
35import lsst.pex.config
36import lsst.pipe.base
38from .makeKernelBasisList import makeKernelBasisList
39from .psfMatch import PsfMatchConfig, PsfMatchTask, PsfMatchConfigAL, PsfMatchConfigDF
41from . import diffimLib
42from .utils import evaluateMeanPsfFwhm, getPsfFwhm
45class MakeKernelConfig(PsfMatchConfig):
46 kernel = lsst.pex.config.ConfigChoiceField(
47 doc="kernel type",
48 typemap=dict(
49 AL=PsfMatchConfigAL,
50 DF=PsfMatchConfigDF
51 ),
52 default="AL",
53 )
54 selectDetection = lsst.pex.config.ConfigurableField(
55 target=SourceDetectionTask,
56 doc="Initial detections used to feed stars to kernel fitting",
57 )
58 selectMeasurement = lsst.pex.config.ConfigurableField(
59 target=SingleFrameMeasurementTask,
60 doc="Initial measurements used to feed stars to kernel fitting",
61 )
62 fwhmExposureGrid = lsst.pex.config.Field(
63 doc="Grid size to compute the average PSF FWHM in an exposure",
64 dtype=int,
65 default=10,
66 )
67 fwhmExposureBuffer = lsst.pex.config.Field(
68 doc="Fractional buffer margin to be left out of all sides of the image during construction"
69 "of grid to compute average PSF FWHM in an exposure",
70 dtype=float,
71 default=0.05,
72 )
74 def setDefaults(self):
75 # High sigma detections only
76 self.selectDetection.reEstimateBackground = False
77 self.selectDetection.thresholdValue = 10.0
78 self.selectDetection.excludeMaskPlanes = ["EDGE"]
80 # Minimal set of measurments for star selection
81 self.selectMeasurement.algorithms.names.clear()
82 self.selectMeasurement.algorithms.names = ('base_SdssCentroid', 'base_PsfFlux', 'base_PixelFlags',
83 'base_SdssShape', 'base_GaussianFlux', 'base_SkyCoord')
84 self.selectMeasurement.slots.modelFlux = None
85 self.selectMeasurement.slots.apFlux = None
86 self.selectMeasurement.slots.calibFlux = None
89class MakeKernelTask(PsfMatchTask):
90 """Construct a kernel for PSF matching two exposures.
91 """
93 ConfigClass = MakeKernelConfig
94 _DefaultName = "makeALKernel"
96 def __init__(self, *args, **kwargs):
97 super().__init__(*args, **kwargs)
98 # the background subtraction task uses a config from an unusual location,
99 # so cannot easily be constructed with makeSubtask
100 self.background = SubtractBackgroundTask(config=self.kConfig.afwBackgroundConfig, name="background",
101 parentTask=self)
103 self.selectSchema = lsst.afw.table.SourceTable.makeMinimalSchema()
104 self.selectAlgMetadata = lsst.daf.base.PropertyList()
105 self.makeSubtask("selectDetection", schema=self.selectSchema)
106 self.makeSubtask("selectMeasurement", schema=self.selectSchema, algMetadata=self.selectAlgMetadata)
108 def run(self, template, science, kernelSources, preconvolved=False,
109 templateFwhmPix=None, scienceFwhmPix=None):
110 """Solve for the kernel and background model that best match two
111 Exposures evaluated at the given source locations.
113 Parameters
114 ----------
115 template : `lsst.afw.image.Exposure`
116 Exposure that will be convolved.
117 science : `lsst.afw.image.Exposure`
118 The exposure that will be matched.
119 kernelSources : `lsst.afw.table.SourceCatalog`
120 Kernel candidate sources with appropriately sized footprints.
121 Typically the output of `MakeKernelTask.selectKernelSources`.
122 preconvolved : `bool`, optional
123 Was the science image convolved with its own PSF?
125 Returns
126 -------
127 results : `lsst.pipe.base.Struct`
129 ``psfMatchingKernel`` : `lsst.afw.math.LinearCombinationKernel`
130 Spatially varying Psf-matching kernel.
131 ``backgroundModel`` : `lsst.afw.math.Function2D`
132 Spatially varying background-matching function.
133 """
134 kernelCellSet = self._buildCellSet(template.maskedImage, science.maskedImage, kernelSources)
135 if (scienceFwhmPix is None) or (templateFwhmPix is None):
136 # Calling getPsfFwhm on template.psf fails on some rare occasions when
137 # the template has no input exposures at the average position of the
138 # stars. So we try getPsfFwhm first on template, and if that fails we
139 # evaluate the PSF on a grid specified by fwhmExposure* fields.
140 # To keep consistent definitions for PSF size on the template and
141 # science images, we use the same method for both.
142 try:
143 templateFwhmPix = getPsfFwhm(template.psf)
144 scienceFwhmPix = getPsfFwhm(science.psf)
145 except (InvalidParameterError, RangeError):
146 self.log.debug("Unable to evaluate PSF at the average position. "
147 "Evaluting PSF on a grid of points."
148 )
149 templateFwhmPix = evaluateMeanPsfFwhm(template,
150 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
151 fwhmExposureGrid=self.config.fwhmExposureGrid
152 )
153 scienceFwhmPix = evaluateMeanPsfFwhm(science,
154 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
155 fwhmExposureGrid=self.config.fwhmExposureGrid
156 )
158 if preconvolved:
159 scienceFwhmPix *= np.sqrt(2)
160 basisList = self.makeKernelBasisList(templateFwhmPix, scienceFwhmPix,
161 metadata=self.metadata)
162 spatialSolution, psfMatchingKernel, backgroundModel = self._solve(kernelCellSet, basisList)
163 return lsst.pipe.base.Struct(
164 psfMatchingKernel=psfMatchingKernel,
165 backgroundModel=backgroundModel,
166 )
168 def selectKernelSources(self, template, science, candidateList=None, preconvolved=False,
169 templateFwhmPix=None, scienceFwhmPix=None):
170 """Select sources from a list of candidates, and extract footprints.
172 Parameters
173 ----------
174 template : `lsst.afw.image.Exposure`
175 Exposure that will be convolved.
176 science : `lsst.afw.image.Exposure`
177 The exposure that will be matched.
178 candidateList : `lsst.afw.table.SourceCatalog`
179 Sources to check as possible kernel candidates.
180 preconvolved : `bool`, optional
181 Was the science image convolved with its own PSF?
183 Returns
184 -------
185 kernelSources : `lsst.afw.table.SourceCatalog`
186 Kernel candidates with appropriate sized footprints.
187 """
188 if (scienceFwhmPix is None) or (templateFwhmPix is None):
189 # Calling getPsfFwhm on template.psf fails on some rare occasions when
190 # the template has no input exposures at the average position of the
191 # stars. So we try getPsfFwhm first on template, and if that fails we
192 # evaluate the PSF on a grid specified by fwhmExposure* fields.
193 # To keep consistent definitions for PSF size on the template and
194 # science images, we use the same method for both.
195 try:
196 templateFwhmPix = getPsfFwhm(template.psf)
197 scienceFwhmPix = getPsfFwhm(science.psf)
198 except (InvalidParameterError, RangeError):
199 self.log.debug("Unable to evaluate PSF at the average position. "
200 "Evaluting PSF on a grid of points."
201 )
202 templateFwhmPix = evaluateMeanPsfFwhm(template,
203 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
204 fwhmExposureGrid=self.config.fwhmExposureGrid
205 )
206 scienceFwhmPix = evaluateMeanPsfFwhm(science,
207 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
208 fwhmExposureGrid=self.config.fwhmExposureGrid
209 )
210 if preconvolved:
211 scienceFwhmPix *= np.sqrt(2)
212 kernelSize = self.makeKernelBasisList(templateFwhmPix, scienceFwhmPix)[0].getWidth()
213 kernelSources = self.makeCandidateList(template, science, kernelSize,
214 candidateList=candidateList,
215 preconvolved=preconvolved)
216 return kernelSources
218 def getSelectSources(self, exposure, sigma=None, doSmooth=True, idFactory=None):
219 """Get sources to use for Psf-matching.
221 This method runs detection and measurement on an exposure.
222 The returned set of sources will be used as candidates for
223 Psf-matching.
225 Parameters
226 ----------
227 exposure : `lsst.afw.image.Exposure`
228 Exposure on which to run detection/measurement
229 sigma : `float`, optional
230 PSF sigma, in pixels, used for smoothing the image for detection.
231 If `None`, the PSF width will be used.
232 doSmooth : `bool`
233 Whether or not to smooth the Exposure with Psf before detection
234 idFactory : `lsst.afw.table.IdFactory`
235 Factory for the generation of Source ids
237 Returns
238 -------
239 selectSources :
240 source catalog containing candidates for the Psf-matching
241 """
242 if idFactory:
243 table = lsst.afw.table.SourceTable.make(self.selectSchema, idFactory)
244 else:
245 table = lsst.afw.table.SourceTable.make(self.selectSchema)
246 mi = exposure.getMaskedImage()
248 imArr = mi.image.array
249 maskArr = mi.mask.array
250 miArr = np.ma.masked_array(imArr, mask=maskArr)
251 try:
252 fitBg = self.background.fitBackground(mi)
253 bkgd = fitBg.getImageF(self.background.config.algorithm,
254 self.background.config.undersampleStyle)
255 except Exception:
256 self.log.warning("Failed to get background model. Falling back to median background estimation")
257 bkgd = np.ma.median(miArr)
259 # Take off background for detection
260 mi -= bkgd
261 try:
262 table.setMetadata(self.selectAlgMetadata)
263 detRet = self.selectDetection.run(
264 table=table,
265 exposure=exposure,
266 sigma=sigma,
267 doSmooth=doSmooth
268 )
269 selectSources = detRet.sources
270 self.selectMeasurement.run(measCat=selectSources, exposure=exposure)
271 finally:
272 # Put back on the background in case it is needed down stream
273 mi += bkgd
274 del bkgd
276 self.log.info("Selected %d sources via detection measurement.", len(selectSources))
277 return selectSources
279 def makeCandidateList(self, convolved, reference, kernelSize,
280 candidateList, preconvolved=False, sigma=None):
281 """Make a list of acceptable KernelCandidates.
283 Generate a list of candidate sources for Psf-matching, remove sources
284 with bad pixel masks set or that extend off the image.
286 Parameters
287 ----------
288 convolved : `lsst.afw.image.Exposure`
289 Exposure that will be convolved. This is typically the template
290 image, and may have a large bbox than the reference exposure.
291 reference : `lsst.afw.image.Exposure`
292 Exposure that will be matched-to. This is typically the science
293 image.
294 kernelSize : `float`
295 Dimensions of the Psf-matching Kernel, used to set detection
296 footprints.
297 candidateList : `lsst.afw.table.SourceCatalog`
298 List of Sources to examine for kernel candidacy.
299 preconvolved : `bool`, optional
300 Was the science exposure already convolved with its PSF?
302 Returns
303 -------
304 candidates : `lsst.afw.table.SourceCatalog`
305 Candidates with footprints extended to a ``kernelSize`` box.
307 Raises
308 ------
309 RuntimeError
310 If ``candidateList`` is empty after sub-selection.
311 """
312 if candidateList is None:
313 candidateList = self.getSelectSources(reference, doSmooth=not preconvolved, sigma=sigma)
314 if len(candidateList) < 1:
315 raise RuntimeError("No kernel candidates after detection and measurement.")
317 bitmask = reference.mask.getPlaneBitMask(self.config.badMaskPlanes)
318 good = np.ones(len(candidateList), dtype=bool)
319 # Make all candidates have the same size footprint, based on kernelSize.
320 for i, candidate in enumerate(candidateList):
321 # Only use the brightest peak; the input should be pre-deblended!
322 peak = candidate.getFootprint().getPeaks()[0]
323 size = 2*kernelSize + 1 # ensure the resulting box is odd
324 bbox = lsst.geom.Box2I.makeCenteredBox(candidate.getCentroid(),
325 lsst.geom.Extent2I(size, size))
326 boxFootprint = lsst.afw.detection.Footprint(lsst.afw.geom.SpanSet(bbox))
327 boxFootprint.addPeak(peak.getFx(), peak.getFy(), peak.getPeakValue())
328 candidate.setFootprint(boxFootprint)
330 # Reject footprints not contained in either image.
331 if not reference.getBBox().contains(bbox) or not convolved.getBBox().contains(bbox):
332 good[i] = False
333 continue
334 # Reject footprints with any bad mask bits set.
335 if (reference.subset(bbox).mask.array & bitmask).any():
336 good[i] = False
337 continue
339 # Reject footprints with any bad mask bits set.
340 if (convolved.subset(bbox).mask.array & bitmask).any():
341 good[i] = False
342 continue
343 candidates = candidateList[good].copy(deep=True)
345 self.log.info("Selected %d / %d sources as kernel candidates.", good.sum(), len(candidateList))
347 if len(candidates) < 1:
348 raise RuntimeError("No good kernel candidates available.")
350 return candidates
352 def makeKernelBasisList(self, targetFwhmPix=None, referenceFwhmPix=None,
353 basisDegGauss=None, basisSigmaGauss=None, metadata=None):
354 """Wrapper to set log messages for
355 `lsst.ip.diffim.makeKernelBasisList`.
357 Parameters
358 ----------
359 targetFwhmPix : `float`, optional
360 Passed on to `lsst.ip.diffim.generateAlardLuptonBasisList`.
361 Not used for delta function basis sets.
362 referenceFwhmPix : `float`, optional
363 Passed on to `lsst.ip.diffim.generateAlardLuptonBasisList`.
364 Not used for delta function basis sets.
365 basisDegGauss : `list` of `int`, optional
366 Passed on to `lsst.ip.diffim.generateAlardLuptonBasisList`.
367 Not used for delta function basis sets.
368 basisSigmaGauss : `list` of `int`, optional
369 Passed on to `lsst.ip.diffim.generateAlardLuptonBasisList`.
370 Not used for delta function basis sets.
371 metadata : `lsst.daf.base.PropertySet`, optional
372 Passed on to `lsst.ip.diffim.generateAlardLuptonBasisList`.
373 Not used for delta function basis sets.
375 Returns
376 -------
377 basisList: `list` of `lsst.afw.math.kernel.FixedKernel`
378 List of basis kernels.
379 """
380 basisList = makeKernelBasisList(self.kConfig,
381 targetFwhmPix=targetFwhmPix,
382 referenceFwhmPix=referenceFwhmPix,
383 basisDegGauss=basisDegGauss,
384 basisSigmaGauss=basisSigmaGauss,
385 metadata=metadata)
386 if targetFwhmPix == referenceFwhmPix:
387 self.log.info("Target and reference psf fwhms are equal, falling back to config values")
388 elif referenceFwhmPix > targetFwhmPix:
389 self.log.info("Reference psf fwhm is the greater, normal convolution mode")
390 else:
391 self.log.info("Target psf fwhm is the greater, deconvolution mode")
393 return basisList
395 def _buildCellSet(self, convolved, reference, candidateList):
396 """Build a SpatialCellSet for use with the solve method.
398 Parameters
399 ----------
400 convolved : `lsst.afw.image.MaskedImage`
401 MaskedImage to PSF-matched to reference.
402 reference : `lsst.afw.image.MaskedImage`
403 Reference MaskedImage.
404 candidateList : `lsst.afw.table.SourceCatalog`
405 Kernel candidate sources with footprints.
407 Returns
408 -------
409 kernelCellSet : `lsst.afw.math.SpatialCellSet`
410 A SpatialCellSet for use with self._solve.
411 """
412 sizeCellX, sizeCellY = self._adaptCellSize(candidateList)
414 imageBBox = convolved.getBBox()
415 imageBBox.clip(reference.getBBox())
416 # Object to store the KernelCandidates for spatial modeling
417 kernelCellSet = lsst.afw.math.SpatialCellSet(imageBBox, sizeCellX, sizeCellY)
419 candidateConfig = lsst.pex.config.makePropertySet(self.kConfig)
420 # Place candidates within the spatial grid
421 for candidate in candidateList:
422 bbox = candidate.getFootprint().getBBox()
423 templateCutout = lsst.afw.image.MaskedImageF(convolved, bbox)
424 scienceCutout = lsst.afw.image.MaskedImageF(reference, bbox)
426 kernelCandidate = diffimLib.makeKernelCandidate(candidate,
427 templateCutout,
428 scienceCutout,
429 candidateConfig)
431 self.log.debug("Candidate %d at %.2f, %.2f rating=%f",
432 kernelCandidate.getId(),
433 kernelCandidate.getXCenter(),
434 kernelCandidate.getYCenter(),
435 kernelCandidate.getCandidateRating())
436 kernelCellSet.insertCandidate(kernelCandidate)
438 return kernelCellSet
440 def _adaptCellSize(self, candidateList):
441 """NOT IMPLEMENTED YET.
443 Parameters
444 ----------
445 candidateList : `list`
446 A list of footprints/maskedImages for kernel candidates;
448 Returns
449 -------
450 sizeCellX, sizeCellY : `int`
451 New dimensions to use for the kernel.
452 """
453 return self.kConfig.sizeCellX, self.kConfig.sizeCellY