22__all__ = [
"MakeKernelConfig",
"MakeKernelTask"]
32from lsst.meas.algorithms
import SourceDetectionTask, SubtractBackgroundTask
38from .makeKernelBasisList
import makeKernelBasisList
39from .psfMatch
import PsfMatchConfig, PsfMatchTask, PsfMatchConfigAL, PsfMatchConfigDF
41from .
import diffimLib
42from .utils
import evaluateMeanPsfFwhm, getPsfFwhm
46 kernel = lsst.pex.config.ConfigChoiceField(
54 selectDetection = lsst.pex.config.ConfigurableField(
55 target=SourceDetectionTask,
56 doc=
"Initial detections used to feed stars to kernel fitting",
58 selectMeasurement = lsst.pex.config.ConfigurableField(
59 target=SingleFrameMeasurementTask,
60 doc=
"Initial measurements used to feed stars to kernel fitting",
62 fwhmExposureGrid = lsst.pex.config.Field(
63 doc=
"Grid size to compute the average PSF FWHM in an exposure",
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",
82 self.
selectMeasurement.algorithms.names = (
'base_SdssCentroid',
'base_PsfFlux',
'base_PixelFlags',
83 'base_SdssShape',
'base_GaussianFlux',
'base_SkyCoord')
90 """Construct a kernel for PSF matching two exposures.
93 ConfigClass = MakeKernelConfig
94 _DefaultName =
"makeALKernel"
100 self.
background = SubtractBackgroundTask(config=self.
kConfig.afwBackgroundConfig, name=
"background",
105 self.makeSubtask(
"selectDetection", schema=self.
selectSchema)
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.
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?
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.
134 kernelCellSet = self.
_buildCellSet(template.maskedImage, science.maskedImage, kernelSources)
135 if (scienceFwhmPix
is None)
or (templateFwhmPix
is None):
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."
149 templateFwhmPix = evaluateMeanPsfFwhm(template,
150 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
151 fwhmExposureGrid=self.config.fwhmExposureGrid
153 scienceFwhmPix = evaluateMeanPsfFwhm(science,
154 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
155 fwhmExposureGrid=self.config.fwhmExposureGrid
159 scienceFwhmPix *= np.sqrt(2)
161 metadata=self.metadata)
162 spatialSolution, psfMatchingKernel, backgroundModel = self.
_solve(kernelCellSet, basisList)
163 return lsst.pipe.base.Struct(
164 psfMatchingKernel=psfMatchingKernel,
165 backgroundModel=backgroundModel,
169 templateFwhmPix=None, scienceFwhmPix=None):
170 """Select sources from a list of candidates, and extract footprints.
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?
185 kernelSources : `lsst.afw.table.SourceCatalog`
186 Kernel candidates with appropriate sized footprints.
188 if (scienceFwhmPix
is None)
or (templateFwhmPix
is None):
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."
202 templateFwhmPix = evaluateMeanPsfFwhm(template,
203 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
204 fwhmExposureGrid=self.config.fwhmExposureGrid
206 scienceFwhmPix = evaluateMeanPsfFwhm(science,
207 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
208 fwhmExposureGrid=self.config.fwhmExposureGrid
211 scienceFwhmPix *= np.sqrt(2)
214 candidateList=candidateList,
215 preconvolved=preconvolved)
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
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.
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
240 source catalog containing candidates for the Psf-matching
246 mi = exposure.getMaskedImage()
248 imArr = mi.image.array
249 maskArr = mi.mask.array
250 miArr = np.ma.masked_array(imArr, mask=maskArr)
253 bkgd = fitBg.getImageF(self.
background.config.algorithm,
256 self.log.warning(
"Failed to get background model. Falling back to median background estimation")
257 bkgd = np.ma.median(miArr)
263 detRet = self.selectDetection.
run(
269 selectSources = detRet.sources
270 self.selectMeasurement.
run(measCat=selectSources, exposure=exposure)
276 self.log.info(
"Selected %d sources via detection measurement.", len(selectSources))
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.
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
295 Dimensions of the Psf-matching Kernel, used to set detection
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?
304 candidates : `lsst.afw.table.SourceCatalog`
305 Candidates with footprints extended to a ``kernelSize`` box.
310 If ``candidateList`` is empty after sub-selection.
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)
320 for i, candidate
in enumerate(candidateList):
322 peak = candidate.getFootprint().getPeaks()[0]
323 size = 2*kernelSize + 1
327 boxFootprint.addPeak(peak.getFx(), peak.getFy(), peak.getPeakValue())
328 candidate.setFootprint(boxFootprint)
331 if not reference.getBBox().contains(bbox)
or not convolved.getBBox().contains(bbox):
335 if (reference.subset(bbox).mask.array & bitmask).any():
340 if (convolved.subset(bbox).mask.array & bitmask).any():
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.")
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`.
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.
377 basisList: `list` of `lsst.afw.math.kernel.FixedKernel`
378 List of basis kernels.
380 basisList = makeKernelBasisList(self.
kConfig,
381 targetFwhmPix=targetFwhmPix,
382 referenceFwhmPix=referenceFwhmPix,
383 basisDegGauss=basisDegGauss,
384 basisSigmaGauss=basisSigmaGauss,
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")
391 self.log.info(
"Target psf fwhm is the greater, deconvolution mode")
396 """Build a SpatialCellSet for use with the solve method.
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.
409 kernelCellSet : `lsst.afw.math.SpatialCellSet`
410 A SpatialCellSet for use with self._solve.
414 imageBBox = convolved.getBBox()
415 imageBBox.clip(reference.getBBox())
419 candidateConfig = lsst.pex.config.makePropertySet(self.
kConfig)
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,
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)
441 """NOT IMPLEMENTED YET.
445 candidateList : `list`
446 A list of footprints/maskedImages for kernel candidates;
450 sizeCellX, sizeCellY : `int`
451 New dimensions to use for the kernel.
static std::shared_ptr< SourceTable > make(Schema const &schema, std::shared_ptr< IdFactory > const &idFactory)
static Schema makeMinimalSchema()
static Box2I makeCenteredBox(Point2D const ¢er, Extent const &size)
makeCandidateList(self, convolved, reference, kernelSize, candidateList, preconvolved=False, sigma=None)
run(self, template, science, kernelSources, preconvolved=False, templateFwhmPix=None, scienceFwhmPix=None)
__init__(self, *args, **kwargs)
_buildCellSet(self, convolved, reference, candidateList)
_adaptCellSize(self, candidateList)
makeKernelBasisList(self, targetFwhmPix=None, referenceFwhmPix=None, basisDegGauss=None, basisSigmaGauss=None, metadata=None)
selectKernelSources(self, template, science, candidateList=None, preconvolved=False, templateFwhmPix=None, scienceFwhmPix=None)
getSelectSources(self, exposure, sigma=None, doSmooth=True, idFactory=None)
_solve(self, kernelCellSet, basisList)