28from lsst.ip.diffim.utils
import evaluateMaskFraction
29from lsst.meas.algorithms import SkyObjectsTask, SourceDetectionTask, SetPrimaryFlagsTask, MaskStreaksTask
30from lsst.meas.base import ForcedMeasurementTask, ApplyApCorrTask, DetectorVisitIdGeneratorConfig
33import lsst.meas.extensions.shapeHSM
38from lsst.utils.timer
import timeMethod
40from .
import DipoleFitTask
42__all__ = [
"DetectAndMeasureConfig",
"DetectAndMeasureTask",
43 "DetectAndMeasureScoreConfig",
"DetectAndMeasureScoreTask"]
47 dimensions=(
"instrument",
"visit",
"detector"),
48 defaultTemplates={
"coaddName":
"deep",
51 science = pipeBase.connectionTypes.Input(
52 doc=
"Input science exposure.",
53 dimensions=(
"instrument",
"visit",
"detector"),
54 storageClass=
"ExposureF",
55 name=
"{fakesType}calexp"
57 matchedTemplate = pipeBase.connectionTypes.Input(
58 doc=
"Warped and PSF-matched template used to create the difference image.",
59 dimensions=(
"instrument",
"visit",
"detector"),
60 storageClass=
"ExposureF",
61 name=
"{fakesType}{coaddName}Diff_matchedExp",
63 difference = pipeBase.connectionTypes.Input(
64 doc=
"Result of subtracting template from science.",
65 dimensions=(
"instrument",
"visit",
"detector"),
66 storageClass=
"ExposureF",
67 name=
"{fakesType}{coaddName}Diff_differenceTempExp",
69 outputSchema = pipeBase.connectionTypes.InitOutput(
70 doc=
"Schema (as an example catalog) for output DIASource catalog.",
71 storageClass=
"SourceCatalog",
72 name=
"{fakesType}{coaddName}Diff_diaSrc_schema",
74 diaSources = pipeBase.connectionTypes.Output(
75 doc=
"Detected diaSources on the difference image.",
76 dimensions=(
"instrument",
"visit",
"detector"),
77 storageClass=
"SourceCatalog",
78 name=
"{fakesType}{coaddName}Diff_diaSrc",
80 subtractedMeasuredExposure = pipeBase.connectionTypes.Output(
81 doc=
"Difference image with detection mask plane filled in.",
82 dimensions=(
"instrument",
"visit",
"detector"),
83 storageClass=
"ExposureF",
84 name=
"{fakesType}{coaddName}Diff_differenceExp",
86 maskedStreaks = pipeBase.connectionTypes.Output(
87 doc=
'Catalog of streak fit parameters for the difference image.',
88 storageClass=
"ArrowNumpyDict",
89 dimensions=(
"instrument",
"visit",
"detector"),
90 name=
"{fakesType}{coaddName}Diff_streaks",
93 def __init__(self, *, config):
94 super().__init__(config=config)
95 if not (self.config.writeStreakInfo
and self.config.doMaskStreaks):
96 self.outputs.remove(
"maskedStreaks")
99class DetectAndMeasureConfig(pipeBase.PipelineTaskConfig,
100 pipelineConnections=DetectAndMeasureConnections):
101 """Config for DetectAndMeasureTask
103 doMerge = pexConfig.Field(
106 doc=
"Merge positive and negative diaSources with grow radius "
107 "set by growFootprint"
109 doForcedMeasurement = pexConfig.Field(
112 doc=
"Force photometer diaSource locations on PVI?")
113 doAddMetrics = pexConfig.Field(
116 doc=
"Add columns to the source table to hold analysis metrics?"
118 detection = pexConfig.ConfigurableField(
119 target=SourceDetectionTask,
120 doc=
"Final source detection for diaSource measurement",
122 deblend = pexConfig.ConfigurableField(
124 doc=
"Task to split blended sources into their components."
126 measurement = pexConfig.ConfigurableField(
127 target=DipoleFitTask,
128 doc=
"Task to measure sources on the difference image.",
133 doc=
"Run subtask to apply aperture corrections"
136 target=ApplyApCorrTask,
137 doc=
"Task to apply aperture corrections"
139 forcedMeasurement = pexConfig.ConfigurableField(
140 target=ForcedMeasurementTask,
141 doc=
"Task to force photometer science image at diaSource locations.",
143 growFootprint = pexConfig.Field(
146 doc=
"Grow positive and negative footprints by this many pixels before merging"
148 diaSourceMatchRadius = pexConfig.Field(
151 doc=
"Match radius (in arcseconds) for DiaSource to Source association"
153 doSkySources = pexConfig.Field(
156 doc=
"Generate sky sources?",
158 skySources = pexConfig.ConfigurableField(
159 target=SkyObjectsTask,
160 doc=
"Generate sky sources",
162 doMaskStreaks = pexConfig.Field(
165 doc=
"Turn on streak masking",
167 maskStreaks = pexConfig.ConfigurableField(
168 target=MaskStreaksTask,
169 doc=
"Subtask for masking streaks. Only used if doMaskStreaks is True. "
170 "Adds a mask plane to an exposure, with the mask plane name set by streakMaskName.",
172 writeStreakInfo = pexConfig.Field(
175 doc=
"Record the parameters of any detected streaks. For LSST, this should be turned off except for "
178 setPrimaryFlags = pexConfig.ConfigurableField(
179 target=SetPrimaryFlagsTask,
180 doc=
"Task to add isPrimary and deblending-related flags to the catalog."
184 doc=
"Sources with any of these flags set are removed before writing the output catalog.",
185 default=(
"base_PixelFlags_flag_offimage",
186 "base_PixelFlags_flag_interpolatedCenterAll",
187 "base_PixelFlags_flag_badCenterAll",
188 "base_PixelFlags_flag_edgeCenterAll",
189 "base_PixelFlags_flag_saturatedCenterAll",
192 idGenerator = DetectorVisitIdGeneratorConfig.make_field()
194 def setDefaults(self):
196 self.detection.thresholdPolarity =
"both"
197 self.detection.thresholdValue = 5.0
198 self.detection.reEstimateBackground =
False
199 self.detection.thresholdType =
"pixel_stdev"
200 self.detection.excludeMaskPlanes = [
"EDGE",
"SAT",
"BAD",
"INTRP"]
202 self.measurement.plugins.names |= [
"ext_trailedSources_Naive",
203 "base_LocalPhotoCalib",
205 "ext_shapeHSM_HsmSourceMoments",
206 "ext_shapeHSM_HsmPsfMoments",
208 self.measurement.slots.psfShape =
"ext_shapeHSM_HsmPsfMoments"
209 self.measurement.slots.shape =
"ext_shapeHSM_HsmSourceMoments"
210 self.measurement.plugins[
"base_SdssCentroid"].maxDistToPeak = 5.0
211 self.forcedMeasurement.plugins = [
"base_TransformedCentroid",
"base_PsfFlux"]
212 self.forcedMeasurement.copyColumns = {
213 "id":
"objectId",
"parent":
"parentObjectId",
"coord_ra":
"coord_ra",
"coord_dec":
"coord_dec"}
214 self.forcedMeasurement.slots.centroid =
"base_TransformedCentroid"
215 self.forcedMeasurement.slots.shape =
None
218 self.measurement.plugins[
"base_PixelFlags"].masksFpAnywhere = [
219 "STREAK",
"INJECTED",
"INJECTED_TEMPLATE"]
220 self.measurement.plugins[
"base_PixelFlags"].masksFpCenter = [
221 "STREAK",
"INJECTED",
"INJECTED_TEMPLATE"]
222 self.skySources.avoidMask = [
"DETECTED",
"DETECTED_NEGATIVE",
"BAD",
"NO_DATA",
"EDGE"]
226 self.maskStreaks.onlyMaskDetected =
False
229class DetectAndMeasureTask(lsst.pipe.base.PipelineTask):
230 """Detect and measure sources on a difference image.
232 ConfigClass = DetectAndMeasureConfig
233 _DefaultName =
"detectAndMeasure"
235 def __init__(self, **kwargs):
236 super().__init__(**kwargs)
237 self.schema = afwTable.SourceTable.makeMinimalSchema()
239 afwTable.CoordKey.addErrorFields(self.schema)
242 self.makeSubtask(
"detection", schema=self.schema)
243 self.makeSubtask(
"deblend", schema=self.schema)
244 self.makeSubtask(
"setPrimaryFlags", schema=self.schema, isSingleFrame=
True)
245 self.makeSubtask(
"measurement", schema=self.schema,
246 algMetadata=self.algMetadata)
247 if self.config.doApCorr:
248 self.makeSubtask(
"applyApCorr", schema=self.measurement.schema)
249 if self.config.doForcedMeasurement:
250 self.schema.addField(
251 "ip_diffim_forced_PsfFlux_instFlux",
"D",
252 "Forced PSF flux measured on the direct image.",
254 self.schema.addField(
255 "ip_diffim_forced_PsfFlux_instFluxErr",
"D",
256 "Forced PSF flux error measured on the direct image.",
258 self.schema.addField(
259 "ip_diffim_forced_PsfFlux_area",
"F",
260 "Forced PSF flux effective area of PSF.",
262 self.schema.addField(
263 "ip_diffim_forced_PsfFlux_flag",
"Flag",
264 "Forced PSF flux general failure flag.")
265 self.schema.addField(
266 "ip_diffim_forced_PsfFlux_flag_noGoodPixels",
"Flag",
267 "Forced PSF flux not enough non-rejected pixels in data to attempt the fit.")
268 self.schema.addField(
269 "ip_diffim_forced_PsfFlux_flag_edge",
"Flag",
270 "Forced PSF flux object was too close to the edge of the image to use the full PSF model.")
271 self.makeSubtask(
"forcedMeasurement", refSchema=self.schema)
273 self.schema.addField(
"refMatchId",
"L",
"unique id of reference catalog match")
274 self.schema.addField(
"srcMatchId",
"L",
"unique id of source match")
275 if self.config.doSkySources:
276 self.makeSubtask(
"skySources", schema=self.schema)
277 if self.config.doMaskStreaks:
278 self.makeSubtask(
"maskStreaks")
281 for flag
in self.config.badSourceFlags:
282 if flag
not in self.schema:
283 raise pipeBase.InvalidQuantumError(
"Field %s not in schema" % flag)
287 self.outputSchema.getTable().setMetadata(self.algMetadata)
289 def runQuantum(self, butlerQC: pipeBase.QuantumContext,
290 inputRefs: pipeBase.InputQuantizedConnection,
291 outputRefs: pipeBase.OutputQuantizedConnection):
292 inputs = butlerQC.get(inputRefs)
293 idGenerator = self.config.idGenerator.apply(butlerQC.quantum.dataId)
294 idFactory = idGenerator.make_table_id_factory()
295 outputs = self.run(**inputs, idFactory=idFactory)
296 butlerQC.put(outputs, outputRefs)
299 def run(self, science, matchedTemplate, difference,
301 """Detect and measure sources on a difference image.
303 The difference image will be convolved with a gaussian approximation of
304 the PSF to form a maximum likelihood image for detection.
305 Close positive and negative detections will optionally be merged into
307 Sky sources, or forced detections in background regions, will optionally
308 be added, and the configured measurement algorithm will be run on all
313 science : `lsst.afw.image.ExposureF`
314 Science exposure that the template was subtracted from.
315 matchedTemplate : `lsst.afw.image.ExposureF`
316 Warped and PSF-matched template that was used produce the
318 difference : `lsst.afw.image.ExposureF`
319 Result of subtracting template from the science image.
320 idFactory : `lsst.afw.table.IdFactory`, optional
321 Generator object used to assign ids to detected sources in the
322 difference image. Ids from this generator are not set until after
323 deblending and merging positive/negative peaks.
327 measurementResults : `lsst.pipe.base.Struct`
329 ``subtractedMeasuredExposure`` : `lsst.afw.image.ExposureF`
330 Subtracted exposure with detection mask applied.
331 ``diaSources`` : `lsst.afw.table.SourceCatalog`
332 The catalog of detected sources.
334 if idFactory
is None:
338 mask = difference.mask
339 clearMaskPlanes = [
"DETECTED",
"DETECTED_NEGATIVE",
"NOT_DEBLENDED",
"STREAK"]
340 for mp
in clearMaskPlanes:
341 if mp
not in mask.getMaskPlaneDict():
342 mask.addMaskPlane(mp)
343 mask &= ~mask.getPlaneBitMask(clearMaskPlanes)
348 table = afwTable.SourceTable.make(self.schema)
349 results = self.detection.run(
355 sources, positives, negatives = self._deblend(difference,
359 return self.processResults(science, matchedTemplate, difference, sources, idFactory,
360 positiveFootprints=positives,
361 negativeFootprints=negatives)
363 def processResults(self, science, matchedTemplate, difference, sources, idFactory,
364 positiveFootprints=None, negativeFootprints=None,):
365 """Measure and process the results of source detection.
369 science : `lsst.afw.image.ExposureF`
370 Science exposure that the template was subtracted from.
371 matchedTemplate : `lsst.afw.image.ExposureF`
372 Warped and PSF-matched template that was used produce the
374 difference : `lsst.afw.image.ExposureF`
375 Result of subtracting template from the science image.
376 sources : `lsst.afw.table.SourceCatalog`
377 Detected sources on the difference exposure.
378 idFactory : `lsst.afw.table.IdFactory`
379 Generator object used to assign ids to detected sources in the
381 positiveFootprints : `lsst.afw.detection.FootprintSet`, optional
382 Positive polarity footprints.
383 negativeFootprints : `lsst.afw.detection.FootprintSet`, optional
384 Negative polarity footprints.
388 measurementResults : `lsst.pipe.base.Struct`
390 ``subtractedMeasuredExposure`` : `lsst.afw.image.ExposureF`
391 Subtracted exposure with detection mask applied.
392 ``diaSources`` : `lsst.afw.table.SourceCatalog`
393 The catalog of detected sources.
395 self.metadata.add(
"nUnmergedDiaSources", len(sources))
396 if self.config.doMerge:
397 fpSet = positiveFootprints
398 fpSet.merge(negativeFootprints, self.config.growFootprint,
399 self.config.growFootprint,
False)
401 fpSet.makeSources(initialDiaSources)
402 self.log.info(
"Merging detections into %d sources", len(initialDiaSources))
404 initialDiaSources = sources
408 for source
in initialDiaSources:
411 initialDiaSources.getTable().setIdFactory(idFactory)
412 initialDiaSources.setMetadata(self.algMetadata)
414 self.metadata.add(
"nMergedDiaSources", len(initialDiaSources))
416 if self.config.doMaskStreaks:
417 streakInfo = self._runStreakMasking(difference.maskedImage)
419 if self.config.doSkySources:
420 self.addSkySources(initialDiaSources, difference.mask, difference.info.id)
422 if not initialDiaSources.isContiguous():
423 initialDiaSources = initialDiaSources.copy(deep=
True)
425 self.measureDiaSources(initialDiaSources, science, difference, matchedTemplate)
426 diaSources = self._removeBadSources(initialDiaSources)
428 if self.config.doForcedMeasurement:
429 self.measureForcedSources(diaSources, science, difference.getWcs())
431 self.calculateMetrics(difference)
433 measurementResults = pipeBase.Struct(
434 subtractedMeasuredExposure=difference,
435 diaSources=diaSources,
437 if self.config.doMaskStreaks
and self.config.writeStreakInfo:
438 measurementResults.mergeItems(streakInfo,
'maskedStreaks')
440 return measurementResults
442 def _deblend(self, difference, positiveFootprints, negativeFootprints):
443 """Deblend the positive and negative footprints and return a catalog
444 containing just the children, and the deblended footprints.
448 difference : `lsst.afw.image.Exposure`
449 Result of subtracting template from the science image.
450 positiveFootprints, negativeFootprints : `lsst.afw.detection.FootprintSet`
451 Positive and negative polarity footprints measured on
452 ``difference`` to be deblended separately.
456 sources : `lsst.afw.table.SourceCatalog`
457 Positive and negative deblended children.
458 positives, negatives : `lsst.afw.detection.FootprintSet`
459 Deblended positive and negative polarity footprints measured on
462 def makeFootprints(sources):
463 footprints = afwDetection.FootprintSet(difference.getBBox())
464 footprints.setFootprints([src.getFootprint()
for src
in sources])
468 """Deblend a positive or negative footprint set,
469 and return the deblended children.
472 footprints.makeSources(sources)
473 self.deblend.run(exposure=difference, sources=sources)
474 self.setPrimaryFlags.run(sources)
475 children = sources[
"detect_isDeblendedSource"] == 1
476 sources = sources[children].copy(deep=
True)
478 sources[
'parent'] = 0
479 return sources.copy(deep=
True)
481 positives =
deblend(positiveFootprints)
482 negatives =
deblend(negativeFootprints)
485 sources.reserve(len(positives) + len(negatives))
486 sources.extend(positives, deep=
True)
487 sources.extend(negatives, deep=
True)
488 return sources, makeFootprints(positives), makeFootprints(negatives)
490 def _removeBadSources(self, diaSources):
491 """Remove unphysical diaSources from the catalog.
495 diaSources : `lsst.afw.table.SourceCatalog`
496 The catalog of detected sources.
500 diaSources : `lsst.afw.table.SourceCatalog`
501 The updated catalog of detected sources, with any source that has a
502 flag in ``config.badSourceFlags`` set removed.
504 selector = np.ones(len(diaSources), dtype=bool)
505 for flag
in self.config.badSourceFlags:
506 flags = diaSources[flag]
507 nBad = np.count_nonzero(flags)
509 self.log.debug(
"Found %d unphysical sources with flag %s.", nBad, flag)
511 nBadTotal = np.count_nonzero(~selector)
512 self.metadata.add(
"nRemovedBadFlaggedSources", nBadTotal)
513 self.log.info(
"Removed %d unphysical sources.", nBadTotal)
514 return diaSources[selector].copy(deep=
True)
516 def addSkySources(self, diaSources, mask, seed,
518 """Add sources in empty regions of the difference image
519 for measuring the background.
523 diaSources : `lsst.afw.table.SourceCatalog`
524 The catalog of detected sources.
525 mask : `lsst.afw.image.Mask`
526 Mask plane for determining regions where Sky sources can be added.
528 Seed value to initialize the random number generator.
531 subtask = self.skySources
532 skySourceFootprints = subtask.run(mask=mask, seed=seed, catalog=diaSources)
533 self.metadata.add(f
"n_{subtask.getName()}", len(skySourceFootprints))
535 def measureDiaSources(self, diaSources, science, difference, matchedTemplate):
536 """Use (matched) template and science image to constrain dipole fitting.
540 diaSources : `lsst.afw.table.SourceCatalog`
541 The catalog of detected sources.
542 science : `lsst.afw.image.ExposureF`
543 Science exposure that the template was subtracted from.
544 difference : `lsst.afw.image.ExposureF`
545 Result of subtracting template from the science image.
546 matchedTemplate : `lsst.afw.image.ExposureF`
547 Warped and PSF-matched template that was used produce the
551 for mp
in self.config.measurement.plugins[
"base_PixelFlags"].masksFpAnywhere:
552 difference.mask.addMaskPlane(mp)
555 self.measurement.run(diaSources, difference, science, matchedTemplate)
556 if self.config.doApCorr:
557 apCorrMap = difference.getInfo().getApCorrMap()
558 if apCorrMap
is None:
559 self.log.warning(
"Difference image does not have valid aperture correction; skipping.")
561 self.applyApCorr.run(
566 def measureForcedSources(self, diaSources, science, wcs):
567 """Perform forced measurement of the diaSources on the science image.
571 diaSources : `lsst.afw.table.SourceCatalog`
572 The catalog of detected sources.
573 science : `lsst.afw.image.ExposureF`
574 Science exposure that the template was subtracted from.
575 wcs : `lsst.afw.geom.SkyWcs`
576 Coordinate system definition (wcs) for the exposure.
580 forcedSources = self.forcedMeasurement.generateMeasCat(science, diaSources, wcs)
581 self.forcedMeasurement.run(forcedSources, science, diaSources, wcs)
583 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_instFlux")[0],
584 "ip_diffim_forced_PsfFlux_instFlux",
True)
585 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_instFluxErr")[0],
586 "ip_diffim_forced_PsfFlux_instFluxErr",
True)
587 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_area")[0],
588 "ip_diffim_forced_PsfFlux_area",
True)
589 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag")[0],
590 "ip_diffim_forced_PsfFlux_flag",
True)
591 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag_noGoodPixels")[0],
592 "ip_diffim_forced_PsfFlux_flag_noGoodPixels",
True)
593 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag_edge")[0],
594 "ip_diffim_forced_PsfFlux_flag_edge",
True)
595 for diaSource, forcedSource
in zip(diaSources, forcedSources):
596 diaSource.assign(forcedSource, mapper)
598 def calculateMetrics(self, difference):
599 """Add difference image QA metrics to the Task metadata.
601 This may be used to produce corresponding metrics (see
602 lsst.analysis.tools.tasks.diffimTaskDetectorVisitMetricAnalysis).
606 difference : `lsst.afw.image.Exposure`
607 The target difference image to calculate metrics for.
609 mask = difference.mask
610 badPix = (mask.array & mask.getPlaneBitMask(self.config.detection.excludeMaskPlanes)) > 0
611 self.metadata.add(
"nGoodPixels", np.sum(~badPix))
612 self.metadata.add(
"nBadPixels", np.sum(badPix))
613 detPosPix = (mask.array & mask.getPlaneBitMask(
"DETECTED")) > 0
614 detNegPix = (mask.array & mask.getPlaneBitMask(
"DETECTED_NEGATIVE")) > 0
615 self.metadata.add(
"nPixelsDetectedPositive", np.sum(detPosPix))
616 self.metadata.add(
"nPixelsDetectedNegative", np.sum(detNegPix))
619 self.metadata.add(
"nBadPixelsDetectedPositive", np.sum(detPosPix))
620 self.metadata.add(
"nBadPixelsDetectedNegative", np.sum(detNegPix))
622 metricsMaskPlanes = list(mask.getMaskPlaneDict().keys())
623 for maskPlane
in metricsMaskPlanes:
625 self.metadata.add(
"%s_mask_fraction"%maskPlane.lower(), evaluateMaskFraction(mask, maskPlane))
626 except InvalidParameterError:
627 self.metadata.add(
"%s_mask_fraction"%maskPlane.lower(), -1)
628 self.log.info(
"Unable to calculate metrics for mask plane %s: not in image"%maskPlane)
630 def _runStreakMasking(self, maskedImage):
631 """Do streak masking and optionally save the resulting streak
632 fit parameters in a catalog.
636 maskedImage: `lsst.afw.image.maskedImage`
637 The image in which to search for streaks. Must have a detection
642 streakInfo: `lsst.pipe.base.Struct`
643 ``rho`` : `np.ndarray`
644 Angle of detected streak.
645 ``theta`` : `np.ndarray`
646 Distance from center of detected streak.
647 ``sigma`` : `np.ndarray`
648 Width of streak profile.
649 ``reducedChi2`` : `np.ndarray`
650 Reduced chi2 of the best-fit streak profile.
651 ``modelMaximum`` : `np.ndarray`
652 Peak value of the fit line profile.
654 streaks = self.maskStreaks.run(maskedImage)
655 if self.config.writeStreakInfo:
656 rhos = np.array([line.rho
for line
in streaks.lines])
657 thetas = np.array([line.theta
for line
in streaks.lines])
658 sigmas = np.array([line.sigma
for line
in streaks.lines])
659 chi2s = np.array([line.reducedChi2
for line
in streaks.lines])
660 modelMaximums = np.array([line.modelMaximum
for line
in streaks.lines])
661 streakInfo = {
'rho': rhos,
'theta': thetas,
'sigma': sigmas,
'reducedChi2': chi2s,
662 'modelMaximum': modelMaximums}
664 streakInfo = {
'rho': np.array([]),
'theta': np.array([]),
'sigma': np.array([]),
665 'reducedChi2': np.array([]),
'modelMaximum': np.array([])}
666 return pipeBase.Struct(maskedStreaks=streakInfo)
670 scoreExposure = pipeBase.connectionTypes.Input(
671 doc=
"Maximum likelihood image for detection.",
672 dimensions=(
"instrument",
"visit",
"detector"),
673 storageClass=
"ExposureF",
674 name=
"{fakesType}{coaddName}Diff_scoreExp",
678class DetectAndMeasureScoreConfig(DetectAndMeasureConfig,
679 pipelineConnections=DetectAndMeasureScoreConnections):
683class DetectAndMeasureScoreTask(DetectAndMeasureTask):
684 """Detect DIA sources using a score image,
685 and measure the detections on the difference image.
687 Source detection is run on the supplied score, or maximum likelihood,
688 image. Note that no additional convolution will be done in this case.
689 Close positive and negative detections will optionally be merged into
691 Sky sources, or forced detections in background regions, will optionally
692 be added, and the configured measurement algorithm will be run on all
695 ConfigClass = DetectAndMeasureScoreConfig
696 _DefaultName =
"detectAndMeasureScore"
699 def run(self, science, matchedTemplate, difference, scoreExposure,
701 """Detect and measure sources on a score image.
705 science : `lsst.afw.image.ExposureF`
706 Science exposure that the template was subtracted from.
707 matchedTemplate : `lsst.afw.image.ExposureF`
708 Warped and PSF-matched template that was used produce the
710 difference : `lsst.afw.image.ExposureF`
711 Result of subtracting template from the science image.
712 scoreExposure : `lsst.afw.image.ExposureF`
713 Score or maximum likelihood difference image
714 idFactory : `lsst.afw.table.IdFactory`, optional
715 Generator object used to assign ids to detected sources in the
716 difference image. Ids from this generator are not set until after
717 deblending and merging positive/negative peaks.
721 measurementResults : `lsst.pipe.base.Struct`
723 ``subtractedMeasuredExposure`` : `lsst.afw.image.ExposureF`
724 Subtracted exposure with detection mask applied.
725 ``diaSources`` : `lsst.afw.table.SourceCatalog`
726 The catalog of detected sources.
728 if idFactory
is None:
732 mask = scoreExposure.mask
733 mask &= ~(mask.getPlaneBitMask(
"DETECTED") | mask.getPlaneBitMask(
"DETECTED_NEGATIVE"))
738 table = afwTable.SourceTable.make(self.schema)
739 results = self.detection.run(
741 exposure=scoreExposure,
745 difference.mask.assign(scoreExposure.mask, scoreExposure.getBBox())
747 sources, positives, negatives = self._deblend(difference,
751 return self.processResults(science, matchedTemplate, difference, sources, idFactory,
752 positiveFootprints=positives, negativeFootprints=negatives)
A mapping between the keys of two Schemas, used to copy data between them.
Class for storing ordered metadata with comments.
run(self, coaddExposures, bbox, wcs, dataIds, physical_filter)