Coverage for python/lsst/meas/extensions/scarlet/scarletDeblendTask.py : 15%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of meas_extensions_scarlet.
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/>.
22import logging
23import numpy as np
24import scarlet
25from scarlet.psf import ImagePSF, GaussianPSF
26from scarlet import Blend, Frame, Observation
27from scarlet.renderer import ConvolutionRenderer
28from scarlet.initialization import init_all_sources
30import lsst.log
31import lsst.pex.config as pexConfig
32from lsst.pex.exceptions import InvalidParameterError
33import lsst.pipe.base as pipeBase
34from lsst.geom import Point2I, Box2I, Point2D
35import lsst.afw.geom.ellipses as afwEll
36import lsst.afw.image.utils
37import lsst.afw.image as afwImage
38import lsst.afw.detection as afwDet
39import lsst.afw.table as afwTable
41from .source import modelToHeavy
43# Scarlet and proxmin have a different definition of log levels than the stack,
44# so even "warnings" occur far more often than we would like.
45# So for now we only display scarlet and proxmin errors, as all other
46# scarlet outputs would be considered "TRACE" by our standards.
47scarletLogger = logging.getLogger("scarlet")
48scarletLogger.setLevel(logging.ERROR)
49proxminLogger = logging.getLogger("proxmin")
50proxminLogger.setLevel(logging.ERROR)
52__all__ = ["deblend", "ScarletDeblendConfig", "ScarletDeblendTask"]
54logger = lsst.log.Log.getLogger("meas.deblender.deblend")
57class IncompleteDataError(Exception):
58 """The PSF could not be computed due to incomplete data
59 """
60 pass
63class ScarletGradientError(Exception):
64 """An error occurred during optimization
66 This error occurs when the optimizer encounters
67 a NaN value while calculating the gradient.
68 """
69 def __init__(self, iterations, sources):
70 self.iterations = iterations
71 self.sources = sources
72 msg = ("ScalarGradientError in iteration {0}. "
73 "NaN values introduced in sources {1}")
74 self.message = msg.format(iterations, sources)
76 def __str__(self):
77 return self.message
80def _checkBlendConvergence(blend, f_rel):
81 """Check whether or not a blend has converged
82 """
83 deltaLoss = np.abs(blend.loss[-2] - blend.loss[-1])
84 convergence = f_rel * np.abs(blend.loss[-1])
85 return deltaLoss < convergence
88def _getPsfFwhm(psf):
89 """Calculate the FWHM of the `psf`
90 """
91 return psf.computeShape().getDeterminantRadius() * 2.35
94def _computePsfImage(self, position=None):
95 """Get a multiband PSF image
96 The PSF Kernel Image is computed for each band
97 and combined into a (filter, y, x) array and stored
98 as `self._psfImage`.
99 The result is not cached, so if the same PSF is expected
100 to be used multiple times it is a good idea to store the
101 result in another variable.
102 Note: this is a temporary fix during the deblender sprint.
103 In the future this function will replace the current method
104 in `afw.MultibandExposure.computePsfImage` (DM-19789).
105 Parameters
106 ----------
107 position : `Point2D` or `tuple`
108 Coordinates to evaluate the PSF. If `position` is `None`
109 then `Psf.getAveragePosition()` is used.
110 Returns
111 -------
112 self._psfImage: array
113 The multiband PSF image.
114 """
115 psfs = []
116 # Make the coordinates into a Point2D (if necessary)
117 if not isinstance(position, Point2D) and position is not None:
118 position = Point2D(position[0], position[1])
120 for bidx, single in enumerate(self.singles):
121 try:
122 if position is None:
123 psf = single.getPsf().computeImage()
124 psfs.append(psf)
125 else:
126 psf = single.getPsf().computeKernelImage(position)
127 psfs.append(psf)
128 except InvalidParameterError:
129 # This band failed to compute the PSF due to incomplete data
130 # at that location. This is unlikely to be a problem for Rubin,
131 # however the edges of some HSC COSMOS fields contain incomplete
132 # data in some bands, so we track this error to distinguish it
133 # from unknown errors.
134 msg = "Failed to compute PSF at {} in band {}"
135 raise IncompleteDataError(msg.format(position, self.filters[bidx]))
137 left = np.min([psf.getBBox().getMinX() for psf in psfs])
138 bottom = np.min([psf.getBBox().getMinY() for psf in psfs])
139 right = np.max([psf.getBBox().getMaxX() for psf in psfs])
140 top = np.max([psf.getBBox().getMaxY() for psf in psfs])
141 bbox = Box2I(Point2I(left, bottom), Point2I(right, top))
142 psfs = [afwImage.utils.projectImage(psf, bbox) for psf in psfs]
143 psfImage = afwImage.MultibandImage.fromImages(self.filters, psfs)
144 return psfImage
147def getFootprintMask(footprint, mExposure):
148 """Mask pixels outside the footprint
150 Parameters
151 ----------
152 mExposure : `lsst.image.MultibandExposure`
153 - The multiband exposure containing the image,
154 mask, and variance data
155 footprint : `lsst.detection.Footprint`
156 - The footprint of the parent to deblend
158 Returns
159 -------
160 footprintMask : array
161 Boolean array with pixels not in the footprint set to one.
162 """
163 bbox = footprint.getBBox()
164 fpMask = afwImage.Mask(bbox)
165 footprint.spans.setMask(fpMask, 1)
166 fpMask = ~fpMask.getArray().astype(bool)
167 return fpMask
170def isPseudoSource(source, pseudoColumns):
171 """Check if a source is a pseudo source.
173 This is mostly for skipping sky objects,
174 but any other column can also be added to disable
175 deblending on a parent or individual source when
176 set to `True`.
178 Parameters
179 ----------
180 source : `lsst.afw.table.source.source.SourceRecord`
181 The source to check for the pseudo bit.
182 pseudoColumns : `list` of `str`
183 A list of columns to check for pseudo sources.
184 """
185 isPseudo = False
186 for col in pseudoColumns:
187 try:
188 isPseudo |= source[col]
189 except KeyError:
190 pass
191 return isPseudo
194def deblend(mExposure, footprint, config):
195 """Deblend a parent footprint
197 Parameters
198 ----------
199 mExposure : `lsst.image.MultibandExposure`
200 - The multiband exposure containing the image,
201 mask, and variance data
202 footprint : `lsst.detection.Footprint`
203 - The footprint of the parent to deblend
204 config : `ScarletDeblendConfig`
205 - Configuration of the deblending task
206 """
207 # Extract coordinates from each MultiColorPeak
208 bbox = footprint.getBBox()
210 # Create the data array from the masked images
211 images = mExposure.image[:, bbox].array
213 # Use the inverse variance as the weights
214 if config.useWeights:
215 weights = 1/mExposure.variance[:, bbox].array
216 else:
217 weights = np.ones_like(images)
218 badPixels = mExposure.mask.getPlaneBitMask(config.badMask)
219 mask = mExposure.mask[:, bbox].array & badPixels
220 weights[mask > 0] = 0
222 # Mask out the pixels outside the footprint
223 mask = getFootprintMask(footprint, mExposure)
224 weights *= ~mask
226 psfs = _computePsfImage(mExposure, footprint.getCentroid()).array.astype(np.float32)
227 psfs = ImagePSF(psfs)
228 model_psf = GaussianPSF(sigma=(config.modelPsfSigma,)*len(mExposure.filters))
230 frame = Frame(images.shape, psf=model_psf, channels=mExposure.filters)
231 observation = Observation(images, psf=psfs, weights=weights, channels=mExposure.filters)
232 if config.convolutionType == "fft":
233 observation.match(frame)
234 elif config.convolutionType == "real":
235 renderer = ConvolutionRenderer(observation, frame, convolution_type="real")
236 observation.match(frame, renderer=renderer)
237 else:
238 raise ValueError("Unrecognized convolution type {}".format(config.convolutionType))
240 assert(config.sourceModel in ["single", "double", "compact", "fit"])
242 # Set the appropriate number of components
243 if config.sourceModel == "single":
244 maxComponents = 1
245 elif config.sourceModel == "double":
246 maxComponents = 2
247 elif config.sourceModel == "compact":
248 maxComponents = 0
249 elif config.sourceModel == "point":
250 raise NotImplementedError("Point source photometry is currently not implemented")
251 elif config.sourceModel == "fit":
252 # It is likely in the future that there will be some heuristic
253 # used to determine what type of model to use for each source,
254 # but that has not yet been implemented (see DM-22551)
255 raise NotImplementedError("sourceModel 'fit' has not been implemented yet")
257 # Convert the centers to pixel coordinates
258 xmin = bbox.getMinX()
259 ymin = bbox.getMinY()
260 centers = [
261 np.array([peak.getIy() - ymin, peak.getIx() - xmin], dtype=int)
262 for peak in footprint.peaks
263 if not isPseudoSource(peak, config.pseudoColumns)
264 ]
266 # Choose whether or not to use the improved spectral initialization
267 if config.setSpectra:
268 if config.maxSpectrumCutoff <= 0:
269 spectrumInit = True
270 else:
271 spectrumInit = len(centers) * bbox.getArea() < config.maxSpectrumCutoff
272 else:
273 spectrumInit = False
275 # Only deblend sources that can be initialized
276 sources, skipped = init_all_sources(
277 frame=frame,
278 centers=centers,
279 observations=observation,
280 thresh=config.morphThresh,
281 max_components=maxComponents,
282 min_snr=config.minSNR,
283 shifting=False,
284 fallback=config.fallback,
285 silent=config.catchFailures,
286 set_spectra=spectrumInit,
287 )
289 # Attach the peak to all of the initialized sources
290 srcIndex = 0
291 for k, center in enumerate(centers):
292 if k not in skipped:
293 # This is just to make sure that there isn't a coding bug
294 assert np.all(sources[srcIndex].center == center)
295 # Store the record for the peak with the appropriate source
296 sources[srcIndex].detectedPeak = footprint.peaks[k]
297 srcIndex += 1
299 # Create the blend and attempt to optimize it
300 blend = Blend(sources, observation)
301 try:
302 blend.fit(max_iter=config.maxIter, e_rel=config.relativeError)
303 except ArithmeticError:
304 # This occurs when a gradient update produces a NaN value
305 # This is usually due to a source initialized with a
306 # negative SED or no flux, often because the peak
307 # is a noise fluctuation in one band and not a real source.
308 iterations = len(blend.loss)
309 failedSources = []
310 for k, src in enumerate(sources):
311 if np.any(~np.isfinite(src.get_model())):
312 failedSources.append(k)
313 raise ScarletGradientError(iterations, failedSources)
315 return blend, skipped, spectrumInit
318class ScarletDeblendConfig(pexConfig.Config):
319 """MultibandDeblendConfig
321 Configuration for the multiband deblender.
322 The parameters are organized by the parameter types, which are
323 - Stopping Criteria: Used to determine if the fit has converged
324 - Position Fitting Criteria: Used to fit the positions of the peaks
325 - Constraints: Used to apply constraints to the peaks and their components
326 - Other: Parameters that don't fit into the above categories
327 """
328 # Stopping Criteria
329 maxIter = pexConfig.Field(dtype=int, default=300,
330 doc=("Maximum number of iterations to deblend a single parent"))
331 relativeError = pexConfig.Field(dtype=float, default=1e-4,
332 doc=("Change in the loss function between"
333 "iterations to exit fitter"))
335 # Constraints
336 morphThresh = pexConfig.Field(dtype=float, default=1,
337 doc="Fraction of background RMS a pixel must have"
338 "to be included in the initial morphology")
339 # Other scarlet paremeters
340 useWeights = pexConfig.Field(
341 dtype=bool, default=True,
342 doc=("Whether or not use use inverse variance weighting."
343 "If `useWeights` is `False` then flat weights are used"))
344 modelPsfSize = pexConfig.Field(
345 dtype=int, default=11,
346 doc="Model PSF side length in pixels")
347 modelPsfSigma = pexConfig.Field(
348 dtype=float, default=0.8,
349 doc="Define sigma for the model frame PSF")
350 minSNR = pexConfig.Field(
351 dtype=float, default=50,
352 doc="Minimum Signal to noise to accept the source."
353 "Sources with lower flux will be initialized with the PSF but updated "
354 "like an ordinary ExtendedSource (known in scarlet as a `CompactSource`).")
355 saveTemplates = pexConfig.Field(
356 dtype=bool, default=True,
357 doc="Whether or not to save the SEDs and templates")
358 processSingles = pexConfig.Field(
359 dtype=bool, default=True,
360 doc="Whether or not to process isolated sources in the deblender")
361 convolutionType = pexConfig.Field(
362 dtype=str, default="fft",
363 doc="Type of convolution to render the model to the observations.\n"
364 "- 'fft': perform convolutions in Fourier space\n"
365 "- 'real': peform convolutions in real space.")
366 sourceModel = pexConfig.Field(
367 dtype=str, default="double",
368 doc=("How to determine which model to use for sources, from\n"
369 "- 'single': use a single component for all sources\n"
370 "- 'double': use a bulge disk model for all sources\n"
371 "- 'compact': use a single component model, initialzed with a point source morphology, "
372 " for all sources\n"
373 "- 'point': use a point-source model for all sources\n"
374 "- 'fit: use a PSF fitting model to determine the number of components (not yet implemented)")
375 )
376 setSpectra = pexConfig.Field(
377 dtype=bool, default=True,
378 doc="Whether or not to solve for the best-fit spectra during initialization. "
379 "This makes initialization slightly longer, as it requires a convolution "
380 "to set the optimal spectra, but results in a much better initial log-likelihood "
381 "and reduced total runtime, with convergence in fewer iterations."
382 "This option is only used when "
383 "peaks*area < `maxSpectrumCutoff` will use the improved initialization.")
385 # Mask-plane restrictions
386 badMask = pexConfig.ListField(
387 dtype=str, default=["BAD", "CR", "NO_DATA", "SAT", "SUSPECT", "EDGE"],
388 doc="Whether or not to process isolated sources in the deblender")
389 statsMask = pexConfig.ListField(dtype=str, default=["SAT", "INTRP", "NO_DATA"],
390 doc="Mask planes to ignore when performing statistics")
391 maskLimits = pexConfig.DictField(
392 keytype=str,
393 itemtype=float,
394 default={},
395 doc=("Mask planes with the corresponding limit on the fraction of masked pixels. "
396 "Sources violating this limit will not be deblended."),
397 )
399 # Size restrictions
400 maxNumberOfPeaks = pexConfig.Field(
401 dtype=int, default=0,
402 doc=("Only deblend the brightest maxNumberOfPeaks peaks in the parent"
403 " (<= 0: unlimited)"))
404 maxFootprintArea = pexConfig.Field(
405 dtype=int, default=1000000,
406 doc=("Maximum area for footprints before they are ignored as large; "
407 "non-positive means no threshold applied"))
408 maxFootprintSize = pexConfig.Field(
409 dtype=int, default=0,
410 doc=("Maximum linear dimension for footprints before they are ignored "
411 "as large; non-positive means no threshold applied"))
412 minFootprintAxisRatio = pexConfig.Field(
413 dtype=float, default=0.0,
414 doc=("Minimum axis ratio for footprints before they are ignored "
415 "as large; non-positive means no threshold applied"))
416 maxSpectrumCutoff = pexConfig.Field(
417 dtype=int, default=1000000,
418 doc=("Maximum number of pixels * number of sources in a blend. "
419 "This is different than `maxFootprintArea` because this isn't "
420 "the footprint area but the area of the bounding box that "
421 "contains the footprint, and is also multiplied by the number of"
422 "sources in the footprint. This prevents large skinny blends with "
423 "a high density of sources from running out of memory. "
424 "If `maxSpectrumCutoff == -1` then there is no cutoff.")
425 )
427 # Failure modes
428 fallback = pexConfig.Field(
429 dtype=bool, default=True,
430 doc="Whether or not to fallback to a smaller number of components if a source does not initialize"
431 )
432 notDeblendedMask = pexConfig.Field(
433 dtype=str, default="NOT_DEBLENDED", optional=True,
434 doc="Mask name for footprints not deblended, or None")
435 catchFailures = pexConfig.Field(
436 dtype=bool, default=True,
437 doc=("If True, catch exceptions thrown by the deblender, log them, "
438 "and set a flag on the parent, instead of letting them propagate up"))
440 # Other options
441 columnInheritance = pexConfig.DictField(
442 keytype=str, itemtype=str, default={
443 "deblend_nChild": "deblend_parentNChild",
444 "deblend_nPeaks": "deblend_parentNPeaks",
445 "deblend_spectrumInitFlag": "deblend_spectrumInitFlag",
446 "deblend_blendConvergenceFailedFlag": "deblend_blendConvergenceFailedFlag",
447 },
448 doc="Columns to pass from the parent to the child. "
449 "The key is the name of the column for the parent record, "
450 "the value is the name of the column to use for the child."
451 )
452 pseudoColumns = pexConfig.ListField(
453 dtype=str, default=['merge_peak_sky', 'sky_source'],
454 doc="Names of flags which should never be deblended."
455 )
458class ScarletDeblendTask(pipeBase.Task):
459 """ScarletDeblendTask
461 Split blended sources into individual sources.
463 This task has no return value; it only modifies the SourceCatalog in-place.
464 """
465 ConfigClass = ScarletDeblendConfig
466 _DefaultName = "scarletDeblend"
468 def __init__(self, schema, peakSchema=None, **kwargs):
469 """Create the task, adding necessary fields to the given schema.
471 Parameters
472 ----------
473 schema : `lsst.afw.table.schema.schema.Schema`
474 Schema object for measurement fields; will be modified in-place.
475 peakSchema : `lsst.afw.table.schema.schema.Schema`
476 Schema of Footprint Peaks that will be passed to the deblender.
477 Any fields beyond the PeakTable minimal schema will be transferred
478 to the main source Schema. If None, no fields will be transferred
479 from the Peaks.
480 filters : list of str
481 Names of the filters used for the eposures. This is needed to store
482 the SED as a field
483 **kwargs
484 Passed to Task.__init__.
485 """
486 pipeBase.Task.__init__(self, **kwargs)
488 peakMinimalSchema = afwDet.PeakTable.makeMinimalSchema()
489 if peakSchema is None:
490 # In this case, the peakSchemaMapper will transfer nothing, but
491 # we'll still have one
492 # to simplify downstream code
493 self.peakSchemaMapper = afwTable.SchemaMapper(peakMinimalSchema, schema)
494 else:
495 self.peakSchemaMapper = afwTable.SchemaMapper(peakSchema, schema)
496 for item in peakSchema:
497 if item.key not in peakMinimalSchema:
498 self.peakSchemaMapper.addMapping(item.key, item.field)
499 # Because SchemaMapper makes a copy of the output schema
500 # you give its ctor, it isn't updating this Schema in
501 # place. That's probably a design flaw, but in the
502 # meantime, we'll keep that schema in sync with the
503 # peakSchemaMapper.getOutputSchema() manually, by adding
504 # the same fields to both.
505 schema.addField(item.field)
506 assert schema == self.peakSchemaMapper.getOutputSchema(), "Logic bug mapping schemas"
507 self._addSchemaKeys(schema)
508 self.schema = schema
509 self.toCopyFromParent = [item.key for item in self.schema
510 if item.field.getName().startswith("merge_footprint")]
512 def _addSchemaKeys(self, schema):
513 """Add deblender specific keys to the schema
514 """
515 self.runtimeKey = schema.addField('deblend_runtime', type=np.float32, doc='runtime in ms')
517 self.iterKey = schema.addField('deblend_iterations', type=np.int32, doc='iterations to converge')
519 self.nChildKey = schema.addField('deblend_nChild', type=np.int32,
520 doc='Number of children this object has (defaults to 0)')
521 self.psfKey = schema.addField('deblend_deblendedAsPsf', type='Flag',
522 doc='Deblender thought this source looked like a PSF')
523 self.tooManyPeaksKey = schema.addField('deblend_tooManyPeaks', type='Flag',
524 doc='Source had too many peaks; '
525 'only the brightest were included')
526 self.tooBigKey = schema.addField('deblend_parentTooBig', type='Flag',
527 doc='Parent footprint covered too many pixels')
528 self.maskedKey = schema.addField('deblend_masked', type='Flag',
529 doc='Parent footprint was predominantly masked')
530 self.sedNotConvergedKey = schema.addField('deblend_sedConvergenceFailed', type='Flag',
531 doc='scarlet sed optimization did not converge before'
532 'config.maxIter')
533 self.morphNotConvergedKey = schema.addField('deblend_morphConvergenceFailed', type='Flag',
534 doc='scarlet morph optimization did not converge before'
535 'config.maxIter')
536 self.blendConvergenceFailedFlagKey = schema.addField('deblend_blendConvergenceFailedFlag',
537 type='Flag',
538 doc='at least one source in the blend'
539 'failed to converge')
540 self.edgePixelsKey = schema.addField('deblend_edgePixels', type='Flag',
541 doc='Source had flux on the edge of the parent footprint')
542 self.deblendFailedKey = schema.addField('deblend_failed', type='Flag',
543 doc="Deblending failed on source")
544 self.deblendErrorKey = schema.addField('deblend_error', type="String", size=25,
545 doc='Name of error if the blend failed')
546 self.deblendSkippedKey = schema.addField('deblend_skipped', type='Flag',
547 doc="Deblender skipped this source")
548 self.peakCenter = afwTable.Point2IKey.addFields(schema, name="deblend_peak_center",
549 doc="Center used to apply constraints in scarlet",
550 unit="pixel")
551 self.peakIdKey = schema.addField("deblend_peakId", type=np.int32,
552 doc="ID of the peak in the parent footprint. "
553 "This is not unique, but the combination of 'parent'"
554 "and 'peakId' should be for all child sources. "
555 "Top level blends with no parents have 'peakId=0'")
556 self.modelCenterFlux = schema.addField('deblend_peak_instFlux', type=float, units='count',
557 doc="The instFlux at the peak position of deblended mode")
558 self.modelTypeKey = schema.addField("deblend_modelType", type="String", size=25,
559 doc="The type of model used, for example "
560 "MultiExtendedSource, SingleExtendedSource, PointSource")
561 self.nPeaksKey = schema.addField("deblend_nPeaks", type=np.int32,
562 doc="Number of initial peaks in the blend. "
563 "This includes peaks that may have been culled "
564 "during deblending or failed to deblend")
565 self.parentNPeaksKey = schema.addField("deblend_parentNPeaks", type=np.int32,
566 doc="deblend_nPeaks from this records parent.")
567 self.parentNChildKey = schema.addField("deblend_parentNChild", type=np.int32,
568 doc="deblend_nChild from this records parent.")
569 self.scarletFluxKey = schema.addField("deblend_scarletFlux", type=np.float32,
570 doc="Flux measurement from scarlet")
571 self.scarletLogLKey = schema.addField("deblend_logL", type=np.float32,
572 doc="Final logL, used to identify regressions in scarlet.")
573 self.scarletSpectrumInitKey = schema.addField("deblend_spectrumInitFlag", type='Flag',
574 doc="True when scarlet initializes sources "
575 "in the blend with a more accurate spectrum. "
576 "The algorithm uses a lot of memory, "
577 "so large dense blends will use "
578 "a less accurate initialization.")
580 # self.log.trace('Added keys to schema: %s', ", ".join(str(x) for x in
581 # (self.nChildKey, self.tooManyPeaksKey, self.tooBigKey))
582 # )
584 @pipeBase.timeMethod
585 def run(self, mExposure, mergedSources):
586 """Get the psf from each exposure and then run deblend().
588 Parameters
589 ----------
590 mExposure : `MultibandExposure`
591 The exposures should be co-added images of the same
592 shape and region of the sky.
593 mergedSources : `SourceCatalog`
594 The merged `SourceCatalog` that contains parent footprints
595 to (potentially) deblend.
597 Returns
598 -------
599 templateCatalogs: dict
600 Keys are the names of the filters and the values are
601 `lsst.afw.table.source.source.SourceCatalog`'s.
602 These are catalogs with heavy footprints that are the templates
603 created by the multiband templates.
604 """
605 return self.deblend(mExposure, mergedSources)
607 @pipeBase.timeMethod
608 def deblend(self, mExposure, catalog):
609 """Deblend a data cube of multiband images
611 Parameters
612 ----------
613 mExposure : `MultibandExposure`
614 The exposures should be co-added images of the same
615 shape and region of the sky.
616 catalog : `SourceCatalog`
617 The merged `SourceCatalog` that contains parent footprints
618 to (potentially) deblend. The new deblended sources are
619 appended to this catalog in place.
621 Returns
622 -------
623 catalogs : `dict` or `None`
624 Keys are the names of the filters and the values are
625 `lsst.afw.table.source.source.SourceCatalog`'s.
626 These are catalogs with heavy footprints that are the templates
627 created by the multiband templates.
628 """
629 import time
631 filters = mExposure.filters
632 self.log.info(f"Deblending {len(catalog)} sources in {len(mExposure)} exposure bands")
634 # Add the NOT_DEBLENDED mask to the mask plane in each band
635 if self.config.notDeblendedMask:
636 for mask in mExposure.mask:
637 mask.addMaskPlane(self.config.notDeblendedMask)
639 nParents = len(catalog)
640 nDeblendedParents = 0
641 skippedParents = []
642 multibandColumns = {
643 "heavies": [],
644 "fluxes": [],
645 "centerFluxes": [],
646 }
647 for parentIndex in range(nParents):
648 parent = catalog[parentIndex]
649 foot = parent.getFootprint()
650 bbox = foot.getBBox()
651 peaks = foot.getPeaks()
653 # Since we use the first peak for the parent object, we should
654 # propagate its flags to the parent source.
655 parent.assign(peaks[0], self.peakSchemaMapper)
657 # Skip isolated sources unless processSingles is turned on.
658 # Note: this does not flag isolated sources as skipped or
659 # set the NOT_DEBLENDED mask in the exposure,
660 # since these aren't really a skipped blends.
661 # We also skip pseudo sources, like sky objects, which
662 # are intended to be skipped
663 if ((len(peaks) < 2 and not self.config.processSingles)
664 or isPseudoSource(parent, self.config.pseudoColumns)):
665 self._updateParentRecord(
666 parent=parent,
667 nPeaks=len(peaks),
668 nChild=0,
669 runtime=np.nan,
670 iterations=0,
671 logL=np.nan,
672 spectrumInit=False,
673 converged=False,
674 )
675 continue
677 # Block of conditions for skipping a parent with multiple children
678 skipKey = None
679 if self._isLargeFootprint(foot):
680 # The footprint is above the maximum footprint size limit
681 skipKey = self.tooBigKey
682 skipMessage = f"Parent {parent.getId()}: skipping large footprint"
683 elif self._isMasked(foot, mExposure):
684 # The footprint exceeds the maximum number of masked pixels
685 skipKey = self.maskedKey
686 skipMessage = f"Parent {parent.getId()}: skipping masked footprint"
687 elif self.config.maxNumberOfPeaks > 0 and len(peaks) > self.config.maxNumberOfPeaks:
688 # Unlike meas_deblender, in scarlet we skip the entire blend
689 # if the number of peaks exceeds max peaks, since neglecting
690 # to model any peaks often results in catastrophic failure
691 # of scarlet to generate models for the brighter sources.
692 skipKey = self.tooManyPeaksKey
693 skipMessage = f"Parent {parent.getId()}: Too many peaks, skipping blend"
694 if skipKey is not None:
695 self._skipParent(
696 parent=parent,
697 skipKey=skipKey,
698 logMessage=skipMessage,
699 )
700 skippedParents.append(parentIndex)
701 continue
703 nDeblendedParents += 1
704 self.log.trace(f"Parent {parent.getId()}: deblending {len(peaks)} peaks")
705 # Run the deblender
706 blendError = None
707 try:
708 t0 = time.time()
709 # Build the parameter lists with the same ordering
710 blend, skipped, spectrumInit = deblend(mExposure, foot, self.config)
711 tf = time.time()
712 runtime = (tf-t0)*1000
713 converged = _checkBlendConvergence(blend, self.config.relativeError)
714 scarletSources = [src for src in blend.sources]
715 nChild = len(scarletSources)
716 # Re-insert place holders for skipped sources
717 # to propagate them in the catalog so
718 # that the peaks stay consistent
719 for k in skipped:
720 scarletSources.insert(k, None)
721 # Catch all errors and filter out the ones that we know about
722 except Exception as e:
723 blendError = type(e).__name__
724 if isinstance(e, ScarletGradientError):
725 parent.set(self.iterKey, e.iterations)
726 elif not isinstance(e, IncompleteDataError):
727 blendError = "UnknownError"
728 if self.config.catchFailures:
729 # Make it easy to find UnknownErrors in the log file
730 self.log.warn("UnknownError")
731 import traceback
732 traceback.print_exc()
733 else:
734 raise
736 self._skipParent(
737 parent=parent,
738 skipKey=self.deblendFailedKey,
739 logMessage=f"Unable to deblend source {parent.getId}: {blendError}",
740 )
741 parent.set(self.deblendErrorKey, blendError)
742 skippedParents.append(parentIndex)
743 continue
745 # Update the parent record with the deblending results
746 logL = blend.loss[-1]-blend.observations[0].log_norm
747 self._updateParentRecord(
748 parent=parent,
749 nPeaks=len(peaks),
750 nChild=nChild,
751 runtime=runtime,
752 iterations=len(blend.loss),
753 logL=logL,
754 spectrumInit=spectrumInit,
755 converged=converged,
756 )
758 # Add each deblended source to the catalog
759 for k, scarletSource in enumerate(scarletSources):
760 # Skip any sources with no flux or that scarlet skipped because
761 # it could not initialize
762 if k in skipped:
763 # No need to propagate anything
764 continue
765 parent.set(self.deblendSkippedKey, False)
766 mHeavy = modelToHeavy(scarletSource, filters, xy0=bbox.getMin(),
767 observation=blend.observations[0])
768 multibandColumns["heavies"].append(mHeavy)
769 flux = scarlet.measure.flux(scarletSource)
770 multibandColumns["fluxes"].append({
771 filters[fidx]: _flux
772 for fidx, _flux in enumerate(flux)
773 })
774 centerFlux = self._getCenterFlux(mHeavy, scarletSource, xy0=bbox.getMin())
775 multibandColumns["centerFluxes"].append(centerFlux)
777 # Add all fields except the HeavyFootprint to the
778 # source record
779 self._addChild(
780 parent=parent,
781 mHeavy=mHeavy,
782 catalog=catalog,
783 scarletSource=scarletSource,
784 )
786 # Make sure that the number of new sources matches the number of
787 # entries in each of the band dependent columns.
788 # This should never trigger and is just a sanity check.
789 nChildren = len(catalog) - nParents
790 if np.any([len(meas) != nChildren for meas in multibandColumns.values()]):
791 msg = f"Added {len(catalog)-nParents} new sources, but have "
792 msg += ", ".join([
793 f"{len(value)} {key}"
794 for key, value in multibandColumns
795 ])
796 raise RuntimeError(msg)
797 # Make a copy of the catlog in each band and update the footprints
798 catalogs = {}
799 for f in filters:
800 _catalog = afwTable.SourceCatalog(catalog.table.clone())
801 _catalog.extend(catalog, deep=True)
802 # Update the footprints and columns that are different
803 # for each filter
804 for sourceIndex, source in enumerate(_catalog[nParents:]):
805 source.setFootprint(multibandColumns["heavies"][sourceIndex][f])
806 source.set(self.scarletFluxKey, multibandColumns["fluxes"][sourceIndex][f])
807 source.set(self.modelCenterFlux, multibandColumns["centerFluxes"][sourceIndex][f])
808 catalogs[f] = _catalog
810 # Update the mExposure mask with the footprint of skipped parents
811 if self.config.notDeblendedMask:
812 for mask in mExposure.mask:
813 for parentIndex in skippedParents:
814 fp = _catalog[parentIndex].getFootprint()
815 fp.spans.setMask(mask, mask.getPlaneBitMask(self.config.notDeblendedMask))
817 self.log.info(f"Deblender results: of {nParents} parent sources, {nDeblendedParents} "
818 f"were deblended, creating {nChildren} children, "
819 f"for a total of {len(catalog)} sources")
820 return catalogs
822 def _isLargeFootprint(self, footprint):
823 """Returns whether a Footprint is large
825 'Large' is defined by thresholds on the area, size and axis ratio.
826 These may be disabled independently by configuring them to be
827 non-positive.
829 This is principally intended to get rid of satellite streaks, which the
830 deblender or other downstream processing can have trouble dealing with
831 (e.g., multiple large HeavyFootprints can chew up memory).
832 """
833 if self.config.maxFootprintArea > 0 and footprint.getArea() > self.config.maxFootprintArea:
834 return True
835 if self.config.maxFootprintSize > 0:
836 bbox = footprint.getBBox()
837 if max(bbox.getWidth(), bbox.getHeight()) > self.config.maxFootprintSize:
838 return True
839 if self.config.minFootprintAxisRatio > 0:
840 axes = afwEll.Axes(footprint.getShape())
841 if axes.getB() < self.config.minFootprintAxisRatio*axes.getA():
842 return True
843 return False
845 def _isMasked(self, footprint, mExposure):
846 """Returns whether the footprint violates the mask limits"""
847 bbox = footprint.getBBox()
848 mask = np.bitwise_or.reduce(mExposure.mask[:, bbox].array, axis=0)
849 size = float(footprint.getArea())
850 for maskName, limit in self.config.maskLimits.items():
851 maskVal = mExposure.mask.getPlaneBitMask(maskName)
852 _mask = afwImage.MaskX(mask & maskVal, xy0=bbox.getMin())
853 unmaskedSpan = footprint.spans.intersectNot(_mask) # spanset of unmasked pixels
854 if (size - unmaskedSpan.getArea())/size > limit:
855 return True
856 return False
858 def _skipParent(self, parent, skipKey, logMessage):
859 """Update a parent record that is not being deblended.
861 This is a fairly trivial function but is implemented to ensure
862 that a skipped parent updates the appropriate columns
863 consistently, and always has a flag to mark the reason that
864 it is being skipped.
866 Parameters
867 ----------
868 parent : `lsst.afw.table.source.source.SourceRecord`
869 The parent record to flag as skipped.
870 skipKey : `bool`
871 The name of the flag to mark the reason for skipping.
872 logMessage : `str`
873 The message to display in a log.trace when a source
874 is skipped.
875 """
876 if logMessage is not None:
877 self.log.trace(logMessage)
878 self._updateParentRecord(
879 parent=parent,
880 nPeaks=len(parent.getFootprint().peaks),
881 nChild=0,
882 runtime=np.nan,
883 iterations=0,
884 logL=np.nan,
885 spectrumInit=False,
886 converged=False,
887 )
889 # Mark the source as skipped by the deblender and
890 # flag the reason why.
891 parent.set(self.deblendSkippedKey, True)
892 parent.set(skipKey, True)
894 def _updateParentRecord(self, parent, nPeaks, nChild,
895 runtime, iterations, logL, spectrumInit, converged):
896 """Update a parent record in all of the single band catalogs.
898 Ensure that all locations that update a parent record,
899 whether it is skipped or updated after deblending,
900 update all of the appropriate columns.
902 Parameters
903 ----------
904 parent : `lsst.afw.table.source.source.SourceRecord`
905 The parent record to update.
906 nPeaks : `int`
907 Number of peaks in the parent footprint.
908 nChild : `int`
909 Number of children deblended from the parent.
910 This may differ from `nPeaks` if some of the peaks
911 were culled and have no deblended model.
912 runtime : `float`
913 Total runtime for deblending.
914 iterations : `int`
915 Total number of iterations in scarlet before convergence.
916 logL : `float`
917 Final log likelihood of the blend.
918 spectrumInit : `bool`
919 True when scarlet used `set_spectra` to initialize all
920 sources with better initial intensities.
921 converged : `bool`
922 True when the optimizer reached convergence before
923 reaching the maximum number of iterations.
924 """
925 parent.set(self.nPeaksKey, nPeaks)
926 parent.set(self.nChildKey, nChild)
927 parent.set(self.runtimeKey, runtime)
928 parent.set(self.iterKey, iterations)
929 parent.set(self.scarletLogLKey, logL)
930 parent.set(self.scarletSpectrumInitKey, spectrumInit)
931 parent.set(self.blendConvergenceFailedFlagKey, converged)
933 def _addChild(self, parent, mHeavy, catalog, scarletSource):
934 """Add a child to a catalog.
936 This creates a new child in the source catalog,
937 assigning it a parent id, and adding all columns
938 that are independent across all filter bands.
940 Parameters
941 ----------
942 parent : `lsst.afw.table.source.source.SourceRecord`
943 The parent of the new child record.
944 mHeavy : `lsst.detection.MultibandFootprint`
945 The multi-band footprint containing the model and
946 peak catalog for the new child record.
947 catalog : `lsst.afw.table.source.source.SourceCatalog`
948 The merged `SourceCatalog` that contains parent footprints
949 to (potentially) deblend.
950 scarletSource : `scarlet.Component`
951 The scarlet model for the new source record.
952 """
953 src = catalog.addNew()
954 for key in self.toCopyFromParent:
955 src.set(key, parent.get(key))
956 # The peak catalog is the same for all bands,
957 # so we just use the first peak catalog
958 peaks = mHeavy[mHeavy.filters[0]].peaks
959 src.assign(peaks[0], self.peakSchemaMapper)
960 src.setParent(parent.getId())
961 # Currently all children only have a single peak,
962 # but it's possible in the future that there will be hierarchical
963 # deblending, so we use the footprint to set the number of peaks
964 # for each child.
965 src.set(self.nPeaksKey, len(peaks))
966 # Set the psf key based on whether or not the source was
967 # deblended using the PointSource model.
968 # This key is not that useful anymore since we now keep track of
969 # `modelType`, but we continue to propagate it in case code downstream
970 # is expecting it.
971 src.set(self.psfKey, scarletSource.__class__.__name__ == "PointSource")
972 src.set(self.modelTypeKey, scarletSource.__class__.__name__)
973 # We set the runtime to zero so that summing up the
974 # runtime column will give the total time spent
975 # running the deblender for the catalog.
976 src.set(self.runtimeKey, 0)
978 # Set the position of the peak from the parent footprint
979 # This will make it easier to match the same source across
980 # deblenders and across observations, where the peak
981 # position is unlikely to change unless enough time passes
982 # for a source to move on the sky.
983 peak = scarletSource.detectedPeak
984 src.set(self.peakCenter, Point2I(peak["i_x"], peak["i_y"]))
985 src.set(self.peakIdKey, peak["id"])
987 # Propagate columns from the parent to the child
988 for parentColumn, childColumn in self.config.columnInheritance.items():
989 src.set(childColumn, parent.get(parentColumn))
991 def _getCenterFlux(self, mHeavy, scarletSource, xy0):
992 """Get the flux at the center of a HeavyFootprint
994 Parameters
995 ----------
996 mHeavy : `lsst.detection.MultibandFootprint`
997 The multi-band footprint containing the model for the source.
998 scarletSource : `scarlet.Component`
999 The scarlet model for the heavy footprint
1000 """
1001 # Store the flux at the center of the model and the total
1002 # scarlet flux measurement.
1003 mImage = mHeavy.getImage(fill=0.0).image
1005 # Set the flux at the center of the model (for SNR)
1006 try:
1007 cy, cx = scarletSource.center
1008 cy += xy0.y
1009 cx += xy0.x
1010 return mImage[:, cx, cy]
1011 except AttributeError:
1012 msg = "Did not recognize coordinates for source type of `{0}`, "
1013 msg += "could not write coordinates or center flux. "
1014 msg += "Add `{0}` to meas_extensions_scarlet to properly persist this information."
1015 logger.warning(msg.format(type(scarletSource)))
1016 return {f: np.nan for f in mImage.filters}