33 populate_sattle_visit_cache)
34from lsst.meas.algorithms
import SkyObjectsTask, SourceDetectionTask, SetPrimaryFlagsTask, MaskStreaksTask
35from lsst.meas.algorithms
import FindGlintTrailsTask
36from lsst.meas.base import ForcedMeasurementTask, ApplyApCorrTask, DetectorVisitIdGeneratorConfig
37import lsst.meas.deblender
38import lsst.meas.extensions.trailedSources
39import lsst.meas.extensions.shapeHSM
44from lsst.utils.timer
import timeMethod
46from .
import DipoleFitTask
48__all__ = [
"DetectAndMeasureConfig",
"DetectAndMeasureTask",
49 "DetectAndMeasureScoreConfig",
"DetectAndMeasureScoreTask"]
53 """Raised when the residuals in footprints of stars used to compute the
54 psf-matching kernel exceeds the configured maximum.
57 msg = (
"The ratio of residual power in source footprints on the"
58 " difference image to the power in the footprints on the"
59 f
" science image was {ratio}, which exceeds the maximum"
60 f
" threshold of {threshold}")
67 return {
"ratio": self.
ratio,
73 """Raised when there are no diaSources detected on an image difference.
76 msg = (
"No diaSources detected!")
85 dimensions=(
"instrument",
"visit",
"detector"),
86 defaultTemplates={
"coaddName":
"deep",
89 science = pipeBase.connectionTypes.Input(
90 doc=
"Input science exposure.",
91 dimensions=(
"instrument",
"visit",
"detector"),
92 storageClass=
"ExposureF",
93 name=
"{fakesType}calexp"
95 matchedTemplate = pipeBase.connectionTypes.Input(
96 doc=
"Warped and PSF-matched template used to create the difference image.",
97 dimensions=(
"instrument",
"visit",
"detector"),
98 storageClass=
"ExposureF",
99 name=
"{fakesType}{coaddName}Diff_matchedExp",
101 difference = pipeBase.connectionTypes.Input(
102 doc=
"Result of subtracting template from science.",
103 dimensions=(
"instrument",
"visit",
"detector"),
104 storageClass=
"ExposureF",
105 name=
"{fakesType}{coaddName}Diff_differenceTempExp",
107 kernelSources = pipeBase.connectionTypes.Input(
108 doc=
"Final selection of sources used for psf matching.",
109 dimensions=(
"instrument",
"visit",
"detector"),
110 storageClass=
"SourceCatalog",
111 name=
"{fakesType}{coaddName}Diff_psfMatchSources"
113 outputSchema = pipeBase.connectionTypes.InitOutput(
114 doc=
"Schema (as an example catalog) for output DIASource catalog.",
115 storageClass=
"SourceCatalog",
116 name=
"{fakesType}{coaddName}Diff_diaSrc_schema",
118 diaSources = pipeBase.connectionTypes.Output(
119 doc=
"Detected diaSources on the difference image.",
120 dimensions=(
"instrument",
"visit",
"detector"),
121 storageClass=
"SourceCatalog",
122 name=
"{fakesType}{coaddName}Diff_diaSrc",
124 subtractedMeasuredExposure = pipeBase.connectionTypes.Output(
125 doc=
"Difference image with detection mask plane filled in.",
126 dimensions=(
"instrument",
"visit",
"detector"),
127 storageClass=
"ExposureF",
128 name=
"{fakesType}{coaddName}Diff_differenceExp",
130 differenceBackground = pipeBase.connectionTypes.Output(
131 doc=
"Background model that was subtracted from the difference image.",
132 dimensions=(
"instrument",
"visit",
"detector"),
133 storageClass=
"Background",
134 name=
"difference_background",
136 maskedStreaks = pipeBase.connectionTypes.Output(
137 doc=
'Catalog of streak fit parameters for the difference image.',
138 storageClass=
"ArrowNumpyDict",
139 dimensions=(
"instrument",
"visit",
"detector"),
140 name=
"{fakesType}{coaddName}Diff_streaks",
142 glintTrailInfo = pipeBase.connectionTypes.Output(
143 doc=
'Dict of fit parameters for glint trails in the catalog.',
144 storageClass=
"ArrowNumpyDict",
145 dimensions=(
"instrument",
"visit",
"detector"),
146 name=
"trailed_glints",
149 def __init__(self, *, config):
150 super().__init__(config=config)
151 if not (self.config.writeStreakInfo
and self.config.doMaskStreaks):
152 self.outputs.remove(
"maskedStreaks")
153 if not (self.config.doSubtractBackground
and self.config.doWriteBackground):
154 self.outputs.remove(
"differenceBackground")
155 if not (self.config.writeGlintInfo):
156 self.outputs.remove(
"glintTrailInfo")
159class DetectAndMeasureConfig(pipeBase.PipelineTaskConfig,
160 pipelineConnections=DetectAndMeasureConnections):
161 """Config for DetectAndMeasureTask
163 doMerge = pexConfig.Field(
166 doc=
"Merge positive and negative diaSources with grow radius "
167 "set by growFootprint"
169 doForcedMeasurement = pexConfig.Field(
172 doc=
"Force photometer diaSource locations on PVI?"
174 doAddMetrics = pexConfig.Field(
177 doc=
"Add columns to the source table to hold analysis metrics?"
179 doSubtractBackground = pexConfig.Field(
181 doc=
"Subtract a background model from the image before detection?",
184 doWriteBackground = pexConfig.Field(
186 doc=
"Persist the fitted background model?",
189 subtractInitialBackground = pexConfig.ConfigurableField(
190 target=lsst.meas.algorithms.SubtractBackgroundTask,
191 doc=
"Task to perform intial background subtraction, before first detection pass.",
193 subtractFinalBackground = pexConfig.ConfigurableField(
194 target=lsst.meas.algorithms.SubtractBackgroundTask,
195 doc=
"Task to perform final background subtraction, after first detection pass.",
197 detection = pexConfig.ConfigurableField(
198 target=SourceDetectionTask,
199 doc=
"Final source detection for diaSource measurement",
201 streakDetection = pexConfig.ConfigurableField(
202 target=SourceDetectionTask,
203 doc=
"Separate source detection used only for streak masking",
205 doDeblend = pexConfig.Field(
208 doc=
"Deblend DIASources after detection?"
210 deblend = pexConfig.ConfigurableField(
211 target=lsst.meas.deblender.SourceDeblendTask,
212 doc=
"Task to split blended sources into their components."
214 measurement = pexConfig.ConfigurableField(
215 target=DipoleFitTask,
216 doc=
"Task to measure sources on the difference image.",
218 doApCorr = lsst.pex.config.Field(
221 doc=
"Run subtask to apply aperture corrections"
223 applyApCorr = lsst.pex.config.ConfigurableField(
224 target=ApplyApCorrTask,
225 doc=
"Task to apply aperture corrections"
227 forcedMeasurement = pexConfig.ConfigurableField(
228 target=ForcedMeasurementTask,
229 doc=
"Task to force photometer science image at diaSource locations.",
231 growFootprint = pexConfig.Field(
234 doc=
"Grow positive and negative footprints by this many pixels before merging"
236 diaSourceMatchRadius = pexConfig.Field(
239 doc=
"Match radius (in arcseconds) for DiaSource to Source association"
241 doSkySources = pexConfig.Field(
244 doc=
"Generate sky sources?",
246 skySources = pexConfig.ConfigurableField(
247 target=SkyObjectsTask,
248 doc=
"Generate sky sources",
250 doMaskStreaks = pexConfig.Field(
253 doc=
"Turn on streak masking",
255 maskStreaks = pexConfig.ConfigurableField(
256 target=MaskStreaksTask,
257 doc=
"Subtask for masking streaks. Only used if doMaskStreaks is True. "
258 "Adds a mask plane to an exposure, with the mask plane name set by streakMaskName.",
260 streakBinFactor = pexConfig.Field(
263 doc=
"Bin scale factor to use when rerunning detection for masking streaks. "
264 "Only used if doMaskStreaks is True.",
266 writeStreakInfo = pexConfig.Field(
269 doc=
"Record the parameters of any detected streaks. For LSST, this should be turned off except for "
272 findGlints = pexConfig.ConfigurableField(
273 target=FindGlintTrailsTask,
274 doc=
"Subtask for finding glint trails, usually caused by satellites or debris."
276 writeGlintInfo = pexConfig.Field(
279 doc=
"Record the parameters of any detected glint trails."
281 setPrimaryFlags = pexConfig.ConfigurableField(
282 target=SetPrimaryFlagsTask,
283 doc=
"Task to add isPrimary and deblending-related flags to the catalog."
285 badSourceFlags = lsst.pex.config.ListField(
287 doc=
"Sources with any of these flags set are removed before writing the output catalog.",
288 default=(
"base_PixelFlags_flag_offimage",
289 "base_PixelFlags_flag_interpolatedCenterAll",
290 "base_PixelFlags_flag_badCenterAll",
291 "base_PixelFlags_flag_edgeCenterAll",
292 "base_PixelFlags_flag_nodataCenterAll",
293 "base_PixelFlags_flag_saturatedCenterAll",
296 clearMaskPlanes = lsst.pex.config.ListField(
298 doc=
"Mask planes to clear before running detection.",
299 default=(
"DETECTED",
"DETECTED_NEGATIVE",
"NOT_DEBLENDED",
"STREAK"),
301 raiseOnBadSubtractionRatio = pexConfig.Field(
304 doc=
"Raise an error if the ratio of power in detected footprints"
305 " on the difference image to the power in footprints on the science"
306 " image exceeds ``badSubtractionRatioThreshold``",
308 badSubtractionRatioThreshold = pexConfig.Field(
311 doc=
"Maximum ratio of power in footprints on the difference image to"
312 " the same footprints on the science image."
313 "Only used if ``raiseOnBadSubtractionRatio`` is set",
315 badSubtractionVariationThreshold = pexConfig.Field(
318 doc=
"Maximum standard deviation of the ratio of power in footprints on"
319 " the difference image to the same footprints on the science image."
320 "Only used if ``raiseOnBadSubtractionRatio`` is set",
322 raiseOnNoDiaSources = pexConfig.Field(
325 doc=
"Raise an algorithm error if no diaSources are detected.",
327 run_sattle = pexConfig.Field(
330 doc=
"If true, dia source bounding boxes will be sent for verification"
331 "to the sattle service."
333 sattle_historical = pexConfig.Field(
336 doc=
"If re-running a pipeline that requires sattle, this should be set "
337 "to True. This will populate sattle's cache with the historic data "
338 "closest in time to the exposure."
340 idGenerator = DetectorVisitIdGeneratorConfig.make_field()
342 def setDefaults(self):
347 self.subtractInitialBackground.binSize = 8
348 self.subtractInitialBackground.useApprox =
False
349 self.subtractInitialBackground.statisticsProperty =
"MEDIAN"
350 self.subtractInitialBackground.doFilterSuperPixels =
True
353 self.subtractFinalBackground.binSize = 40
354 self.subtractFinalBackground.useApprox =
False
355 self.subtractFinalBackground.statisticsProperty =
"MEDIAN"
356 self.subtractFinalBackground.doFilterSuperPixels =
True
358 self.detection.thresholdPolarity =
"both"
359 self.detection.thresholdValue = 5.0
360 self.detection.reEstimateBackground =
False
361 self.detection.thresholdType =
"pixel_stdev"
362 self.detection.excludeMaskPlanes = [
"EDGE",
367 self.streakDetection.thresholdType = self.detection.thresholdType
368 self.streakDetection.reEstimateBackground =
False
369 self.streakDetection.excludeMaskPlanes = self.detection.excludeMaskPlanes
370 self.streakDetection.thresholdValue = self.detection.thresholdValue
372 self.streakDetection.thresholdPolarity =
"positive"
374 self.streakDetection.nSigmaToGrow = 0
377 self.maskStreaks.onlyMaskDetected =
False
379 self.maskStreaks.maxStreakWidth = 100
382 self.maskStreaks.maxFitIter = 10
384 self.maskStreaks.nSigmaMask = 2
387 self.maskStreaks.absMinimumKernelHeight = 2
389 self.measurement.plugins.names |= [
"ext_trailedSources_Naive",
390 "base_LocalPhotoCalib",
392 "ext_shapeHSM_HsmSourceMoments",
393 "ext_shapeHSM_HsmPsfMoments",
394 "base_ClassificationSizeExtendedness",
396 self.measurement.slots.psfShape =
"ext_shapeHSM_HsmPsfMoments"
397 self.measurement.slots.shape =
"ext_shapeHSM_HsmSourceMoments"
398 self.measurement.plugins[
"base_SdssCentroid"].maxDistToPeak = 5.0
399 self.forcedMeasurement.plugins = [
"base_TransformedCentroid",
"base_PsfFlux"]
400 self.forcedMeasurement.copyColumns = {
401 "id":
"objectId",
"parent":
"parentObjectId",
"coord_ra":
"coord_ra",
"coord_dec":
"coord_dec"}
402 self.forcedMeasurement.slots.centroid =
"base_TransformedCentroid"
403 self.forcedMeasurement.slots.shape =
None
406 self.measurement.plugins[
"base_PixelFlags"].masksFpAnywhere = [
407 "STREAK",
"INJECTED",
"INJECTED_TEMPLATE"]
408 self.measurement.plugins[
"base_PixelFlags"].masksFpCenter = [
409 "STREAK",
"INJECTED",
"INJECTED_TEMPLATE"]
410 self.skySources.avoidMask = [
"DETECTED",
"DETECTED_NEGATIVE",
"BAD",
"NO_DATA",
"EDGE"]
416 if not os.getenv(
"SATTLE_URI_BASE"):
417 raise pexConfig.FieldValidationError(DetectAndMeasureConfig.run_sattle, self,
418 "Sattle requested but SATTLE_URI_BASE "
419 "environment variable not set.")
422class DetectAndMeasureTask(lsst.pipe.base.PipelineTask):
423 """Detect and measure sources on a difference image.
425 ConfigClass = DetectAndMeasureConfig
426 _DefaultName =
"detectAndMeasure"
428 def __init__(self, **kwargs):
429 super().__init__(**kwargs)
430 self.schema = afwTable.SourceTable.makeMinimalSchema()
433 if self.config.doSubtractBackground:
434 self.makeSubtask(
"subtractInitialBackground")
435 self.makeSubtask(
"subtractFinalBackground")
436 self.makeSubtask(
"detection", schema=self.schema)
437 if self.config.doDeblend:
438 self.makeSubtask(
"deblend", schema=self.schema)
439 self.makeSubtask(
"setPrimaryFlags", schema=self.schema, isSingleFrame=
True)
440 self.makeSubtask(
"measurement", schema=self.schema,
441 algMetadata=self.algMetadata)
442 if self.config.doApCorr:
443 self.makeSubtask(
"applyApCorr", schema=self.measurement.schema)
444 if self.config.doForcedMeasurement:
445 self.schema.addField(
446 "ip_diffim_forced_PsfFlux_instFlux",
"D",
447 "Forced PSF flux measured on the direct image.",
449 self.schema.addField(
450 "ip_diffim_forced_PsfFlux_instFluxErr",
"D",
451 "Forced PSF flux error measured on the direct image.",
453 self.schema.addField(
454 "ip_diffim_forced_PsfFlux_area",
"F",
455 "Forced PSF flux effective area of PSF.",
457 self.schema.addField(
458 "ip_diffim_forced_PsfFlux_flag",
"Flag",
459 "Forced PSF flux general failure flag.")
460 self.schema.addField(
461 "ip_diffim_forced_PsfFlux_flag_noGoodPixels",
"Flag",
462 "Forced PSF flux not enough non-rejected pixels in data to attempt the fit.")
463 self.schema.addField(
464 "ip_diffim_forced_PsfFlux_flag_edge",
"Flag",
465 "Forced PSF flux object was too close to the edge of the image to use the full PSF model.")
466 self.makeSubtask(
"forcedMeasurement", refSchema=self.schema)
468 self.schema.addField(
"refMatchId",
"L",
"unique id of reference catalog match")
469 self.schema.addField(
"srcMatchId",
"L",
"unique id of source match")
472 self.makeSubtask(
"skySources", schema=self.schema)
473 if self.config.doMaskStreaks:
474 self.makeSubtask(
"maskStreaks")
475 self.makeSubtask(
"streakDetection")
476 self.makeSubtask(
"findGlints")
477 self.schema.addField(
"glint_trail",
"Flag",
"DiaSource is part of a glint trail.")
484 for flag
in self.config.badSourceFlags:
485 if flag
not in self.schema:
486 raise pipeBase.InvalidQuantumError(
"Field %s not in schema" % flag)
489 self.outputSchema = afwTable.SourceCatalog(self.schema)
490 self.outputSchema.getTable().setMetadata(self.algMetadata)
492 def runQuantum(self, butlerQC: pipeBase.QuantumContext,
493 inputRefs: pipeBase.InputQuantizedConnection,
494 outputRefs: pipeBase.OutputQuantizedConnection):
495 inputs = butlerQC.get(inputRefs)
496 idGenerator = self.config.idGenerator.apply(butlerQC.quantum.dataId)
497 idFactory = idGenerator.make_table_id_factory()
500 measurementResults = pipeBase.Struct(
501 subtractedMeasuredExposure=
None,
504 differenceBackground=
None,
507 self.run(**inputs, idFactory=idFactory, measurementResults=measurementResults)
508 except pipeBase.AlgorithmError
as e:
509 error = pipeBase.AnnotatedPartialOutputsError.annotate(
512 measurementResults.subtractedMeasuredExposure,
513 measurementResults.diaSources,
514 measurementResults.maskedStreaks,
515 measurementResults.glintTrailInfo,
518 butlerQC.put(measurementResults, outputRefs)
520 butlerQC.put(measurementResults, outputRefs)
523 def run(self, science, matchedTemplate, difference, kernelSources,
524 idFactory=None, measurementResults=None):
525 """Detect and measure sources on a difference image.
527 The difference image will be convolved with a gaussian approximation of
528 the PSF to form a maximum likelihood image for detection.
529 Close positive and negative detections will optionally be merged into
531 Sky sources, or forced detections in background regions, will optionally
532 be added, and the configured measurement algorithm will be run on all
537 science : `lsst.afw.image.ExposureF`
538 Science exposure that the template was subtracted from.
539 matchedTemplate : `lsst.afw.image.ExposureF`
540 Warped and PSF-matched template that was used produce the
542 difference : `lsst.afw.image.ExposureF`
543 Result of subtracting template from the science image.
544 kernelSources : `lsst.afw.table.SourceCatalog`
545 Final selection of sources that was used for psf matching.
546 idFactory : `lsst.afw.table.IdFactory`, optional
547 Generator object used to assign ids to detected sources in the
548 difference image. Ids from this generator are not set until after
549 deblending and merging positive/negative peaks.
550 measurementResults : `lsst.pipe.base.Struct`, optional
551 Result struct that is modified to allow saving of partial outputs
552 for some failure conditions. If the task completes successfully,
553 this is also returned.
557 measurementResults : `lsst.pipe.base.Struct`
559 ``subtractedMeasuredExposure`` : `lsst.afw.image.ExposureF`
560 Subtracted exposure with detection mask applied.
561 ``diaSources`` : `lsst.afw.table.SourceCatalog`
562 The catalog of detected sources.
563 ``differenceBackground`` : `lsst.afw.math.BackgroundList`
564 Background that was subtracted from the difference image.
566 if measurementResults
is None:
567 measurementResults = pipeBase.Struct()
568 if idFactory
is None:
569 idFactory = lsst.meas.base.IdGenerator().make_table_id_factory()
571 if self.config.doSubtractBackground:
573 detectionExposure = difference.clone()
574 background = self.subtractInitialBackground.
run(detectionExposure).background
576 detectionExposure = difference
577 background = afwMath.BackgroundList()
579 self._prepareInputs(detectionExposure)
584 table = afwTable.SourceTable.make(self.schema)
585 results = self.detection.
run(
587 exposure=detectionExposure,
589 background=background
592 if self.config.doSubtractBackground:
596 difference.setMask(detectionExposure.mask)
597 background = self.subtractFinalBackground.
run(difference).background
600 table = afwTable.SourceTable.make(self.schema)
601 results = self.detection.
run(
605 background=background
607 measurementResults.differenceBackground = background
609 if self.config.doDeblend:
610 sources, positives, negatives = self._deblend(difference,
615 positives = afwTable.SourceCatalog(self.schema)
616 results.positive.makeSources(positives)
617 negatives = afwTable.SourceCatalog(self.schema)
618 results.negative.makeSources(negatives)
619 sources = results.sources
621 self.processResults(science, matchedTemplate, difference,
622 sources, idFactory, kernelSources,
625 measurementResults=measurementResults)
626 return measurementResults
628 def _prepareInputs(self, difference):
629 """Ensure that we start with an empty detection and deblended mask.
633 difference : `lsst.afw.image.ExposureF`
634 The difference image that will be used for detecting diaSources.
635 The mask plane will be modified in place.
639 lsst.pipe.base.UpstreamFailureNoWorkFound
640 If the PSF is not usable for measurement.
643 sigma = difference.psf.computeShape(difference.psf.getAveragePosition()).getDeterminantRadius()
645 raise pipeBase.UpstreamFailureNoWorkFound(
"Invalid PSF detected! PSF width evaluates to NaN.")
647 mask = difference.mask
648 for mp
in self.config.clearMaskPlanes:
649 if mp
not in mask.getMaskPlaneDict():
650 mask.addMaskPlane(mp)
651 mask &= ~mask.getPlaneBitMask(self.config.clearMaskPlanes)
653 def processResults(self, science, matchedTemplate, difference, sources, idFactory, kernelSources,
654 positives=None, negatives=None, measurementResults=None):
655 """Measure and process the results of source detection.
659 science : `lsst.afw.image.ExposureF`
660 Science exposure that the template was subtracted from.
661 matchedTemplate : `lsst.afw.image.ExposureF`
662 Warped and PSF-matched template that was used produce the
664 difference : `lsst.afw.image.ExposureF`
665 Result of subtracting template from the science image.
666 sources : `lsst.afw.table.SourceCatalog`
667 Detected sources on the difference exposure.
668 idFactory : `lsst.afw.table.IdFactory`
669 Generator object used to assign ids to detected sources in the
671 kernelSources : `lsst.afw.table.SourceCatalog`
672 Final selection of sources that was used for psf matching.
673 positives : `lsst.afw.table.SourceCatalog`, optional
674 Positive polarity footprints.
675 negatives : `lsst.afw.table.SourceCatalog`, optional
676 Negative polarity footprints.
677 measurementResults : `lsst.pipe.base.Struct`, optional
678 Result struct that is modified to allow saving of partial outputs
679 for some failure conditions. If the task completes successfully,
680 this is also returned.
684 measurementResults : `lsst.pipe.base.Struct`
686 ``subtractedMeasuredExposure`` : `lsst.afw.image.ExposureF`
687 Subtracted exposure with detection mask applied.
688 ``diaSources`` : `lsst.afw.table.SourceCatalog`
689 The catalog of detected sources.
691 if measurementResults
is None:
692 measurementResults = pipeBase.Struct()
693 self.metadata[
"nUnmergedDiaSources"] = len(sources)
694 if self.config.doMerge:
696 if len(positives) > 0:
697 peakSchema = positives[0].getFootprint().peaks.schema
698 elif len(negatives) > 0:
699 peakSchema = negatives[0].getFootprint().peaks.schema
701 peakSchema = afwDetection.PeakTable.makeMinimalSchema()
702 mergeList = afwDetection.FootprintMergeList(self.schema,
703 [
"positive",
"negative"], peakSchema)
704 initialDiaSources = afwTable.SourceCatalog(self.schema)
708 mergeList.addCatalog(initialDiaSources.table, positives,
"positive", minNewPeakDist=0)
709 mergeList.addCatalog(initialDiaSources.table, negatives,
"negative", minNewPeakDist=0)
710 mergeList.getFinalSources(initialDiaSources)
713 initialDiaSources[
"is_negative"] = initialDiaSources[
"merge_footprint_negative"] & \
714 ~initialDiaSources[
"merge_footprint_positive"]
715 self.log.info(
"Merging detections into %d sources", len(initialDiaSources))
717 initialDiaSources = sources
721 for source
in initialDiaSources:
724 initialDiaSources.getTable().setIdFactory(idFactory)
725 initialDiaSources.setMetadata(self.algMetadata)
727 self.metadata[
"nMergedDiaSources"] = len(initialDiaSources)
729 if self.config.doMaskStreaks:
730 streakInfo = self._runStreakMasking(difference)
732 if self.config.doSkySources:
733 self.addSkySources(initialDiaSources, difference.mask, difference.info.id)
735 if not initialDiaSources.isContiguous():
736 initialDiaSources = initialDiaSources.copy(deep=
True)
738 self.measureDiaSources(initialDiaSources, science, difference, matchedTemplate)
741 initialDiaSources, trail_parameters = self._find_glint_trails(initialDiaSources)
742 if self.config.writeGlintInfo:
743 measurementResults.mergeItems(trail_parameters,
'glintTrailInfo')
746 diaSources = self._removeBadSources(initialDiaSources)
748 if self.config.run_sattle:
749 diaSources = self.filterSatellites(diaSources, science)
751 if self.config.doForcedMeasurement:
752 self.measureForcedSources(diaSources, science, difference.getWcs())
754 measurementResults.subtractedMeasuredExposure = difference
756 if self.config.doMaskStreaks
and self.config.writeStreakInfo:
757 measurementResults.mergeItems(streakInfo,
'maskedStreaks')
759 self.calculateMetrics(science, difference, diaSources, kernelSources)
761 if np.count_nonzero(~diaSources[
"sky_source"]) > 0:
762 measurementResults.diaSources = diaSources
763 elif self.config.raiseOnNoDiaSources:
765 elif len(diaSources) > 0:
768 measurementResults.diaSources = diaSources
770 return measurementResults
772 def _deblend(self, difference, positiveFootprints, negativeFootprints):
773 """Deblend the positive and negative footprints and return a catalog
774 containing just the children, and the deblended footprints.
778 difference : `lsst.afw.image.Exposure`
779 Result of subtracting template from the science image.
780 positiveFootprints, negativeFootprints : `lsst.afw.detection.FootprintSet`
781 Positive and negative polarity footprints measured on
782 ``difference`` to be deblended separately.
786 sources : `lsst.afw.table.SourceCatalog`
787 Positive and negative deblended children.
788 positives, negatives : `lsst.afw.table.SourceCatalog`
789 Deblended positive and negative polarity sources with footprints
790 detected on ``difference``.
793 def deblend(footprints, negative=False):
794 """Deblend a positive or negative footprint set,
795 and return the deblended children.
799 footprints : `lsst.afw.detection.FootprintSet`
801 Set True if the footprints contain negative fluxes
805 sources : `lsst.afw.table.SourceCatalog`
807 sources = afwTable.SourceCatalog(self.schema)
808 footprints.makeSources(sources)
811 difference_inverted = difference.clone()
812 difference_inverted.image *= -1
813 self.deblend.
run(exposure=difference_inverted, sources=sources)
814 children = sources[sources[
"parent"] != 0]
816 for child
in children:
817 footprint = child.getFootprint()
818 array = footprint.getImageArray()
821 self.deblend.
run(exposure=difference, sources=sources)
822 self.setPrimaryFlags.
run(sources)
823 children = sources[
"detect_isDeblendedSource"] == 1
824 sources = sources[children].copy(deep=
True)
826 sources[
'parent'] = 0
827 return sources.copy(deep=
True)
829 positives = deblend(positiveFootprints)
830 negatives = deblend(negativeFootprints, negative=
True)
832 sources = afwTable.SourceCatalog(self.schema)
833 sources.reserve(len(positives) + len(negatives))
834 sources.extend(positives, deep=
True)
835 sources.extend(negatives, deep=
True)
836 if len(negatives) > 0:
837 sources[-len(negatives):][
"is_negative"] =
True
838 return sources, positives, negatives
840 def _removeBadSources(self, diaSources):
841 """Remove unphysical diaSources from the catalog.
845 diaSources : `lsst.afw.table.SourceCatalog`
846 The catalog of detected sources.
850 diaSources : `lsst.afw.table.SourceCatalog`
851 The updated catalog of detected sources, with any source that has a
852 flag in ``config.badSourceFlags`` set removed.
854 selector = np.ones(len(diaSources), dtype=bool)
855 for flag
in self.config.badSourceFlags:
856 flags = diaSources[flag]
857 nBad = np.count_nonzero(flags)
859 self.log.debug(
"Found %d unphysical sources with flag %s.", nBad, flag)
861 nBadTotal = np.count_nonzero(~selector)
862 self.metadata[
"nRemovedBadFlaggedSources"] = nBadTotal
863 self.log.info(
"Removed %d unphysical sources.", nBadTotal)
864 return diaSources[selector].copy(deep=
True)
866 def _find_glint_trails(self, diaSources):
867 """Define a new flag column for diaSources that are in a glint trail.
871 diaSources : `lsst.afw.table.SourceCatalog`
872 The catalog of detected sources.
876 diaSources : `lsst.afw.table.SourceCatalog`
877 The updated catalog of detected sources, with a new bool column
878 called 'glint_trail' added.
880 trail_parameters : `dict`
881 Parameters of all the trails that were found.
883 trailed_glints = self.findGlints.
run(diaSources)
884 glint_mask = [
True if id
in trailed_glints.trailed_ids
else False for id
in diaSources[
'id']]
885 diaSources[
'glint_trail'] = np.array(glint_mask)
887 slopes = np.array([trail.slope
for trail
in trailed_glints.parameters])
888 intercepts = np.array([trail.intercept
for trail
in trailed_glints.parameters])
889 stderrs = np.array([trail.stderr
for trail
in trailed_glints.parameters])
890 lengths = np.array([trail.length
for trail
in trailed_glints.parameters])
891 angles = np.array([trail.angle
for trail
in trailed_glints.parameters])
892 parameters = {
'slopes': slopes,
'intercepts': intercepts,
'stderrs': stderrs,
'lengths': lengths,
895 trail_parameters = pipeBase.Struct(glintTrailInfo=parameters)
897 return diaSources, trail_parameters
899 def addSkySources(self, diaSources, mask, seed,
901 """Add sources in empty regions of the difference image
902 for measuring the background.
906 diaSources : `lsst.afw.table.SourceCatalog`
907 The catalog of detected sources.
908 mask : `lsst.afw.image.Mask`
909 Mask plane for determining regions where Sky sources can be added.
911 Seed value to initialize the random number generator.
914 subtask = self.skySources
915 skySourceFootprints = subtask.run(mask=mask, seed=seed, catalog=diaSources)
916 self.metadata[f
"n_{subtask.getName()}"] = len(skySourceFootprints)
918 def measureDiaSources(self, diaSources, science, difference, matchedTemplate):
919 """Use (matched) template and science image to constrain dipole fitting.
923 diaSources : `lsst.afw.table.SourceCatalog`
924 The catalog of detected sources.
925 science : `lsst.afw.image.ExposureF`
926 Science exposure that the template was subtracted from.
927 difference : `lsst.afw.image.ExposureF`
928 Result of subtracting template from the science image.
929 matchedTemplate : `lsst.afw.image.ExposureF`
930 Warped and PSF-matched template that was used produce the
934 for mp
in self.config.measurement.plugins[
"base_PixelFlags"].masksFpAnywhere:
935 difference.mask.addMaskPlane(mp)
938 self.measurement.
run(diaSources, difference, science, matchedTemplate)
939 if self.config.doApCorr:
940 apCorrMap = difference.getInfo().getApCorrMap()
941 if apCorrMap
is None:
942 self.log.warning(
"Difference image does not have valid aperture correction; skipping.")
944 self.applyApCorr.
run(
949 def measureForcedSources(self, diaSources, science, wcs):
950 """Perform forced measurement of the diaSources on the science image.
954 diaSources : `lsst.afw.table.SourceCatalog`
955 The catalog of detected sources.
956 science : `lsst.afw.image.ExposureF`
957 Science exposure that the template was subtracted from.
958 wcs : `lsst.afw.geom.SkyWcs`
959 Coordinate system definition (wcs) for the exposure.
963 forcedSources = self.forcedMeasurement.generateMeasCat(science, diaSources, wcs)
964 self.forcedMeasurement.
run(forcedSources, science, diaSources, wcs)
965 mapper = afwTable.SchemaMapper(forcedSources.schema, diaSources.schema)
966 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_instFlux")[0],
967 "ip_diffim_forced_PsfFlux_instFlux",
True)
968 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_instFluxErr")[0],
969 "ip_diffim_forced_PsfFlux_instFluxErr",
True)
970 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_area")[0],
971 "ip_diffim_forced_PsfFlux_area",
True)
972 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag")[0],
973 "ip_diffim_forced_PsfFlux_flag",
True)
974 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag_noGoodPixels")[0],
975 "ip_diffim_forced_PsfFlux_flag_noGoodPixels",
True)
976 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag_edge")[0],
977 "ip_diffim_forced_PsfFlux_flag_edge",
True)
978 for diaSource, forcedSource
in zip(diaSources, forcedSources):
979 diaSource.assign(forcedSource, mapper)
981 def calculateMetrics(self, science, difference, diaSources, kernelSources):
982 """Add difference image QA metrics to the Task metadata.
984 This may be used to produce corresponding metrics (see
985 lsst.analysis.tools.tasks.diffimTaskDetectorVisitMetricAnalysis).
989 science : `lsst.afw.image.ExposureF`
990 Science exposure that was subtracted.
991 difference : `lsst.afw.image.Exposure`
992 The target difference image to calculate metrics for.
993 diaSources : `lsst.afw.table.SourceCatalog`
994 The catalog of detected sources.
995 kernelSources : `lsst.afw.table.SourceCatalog`
996 Final selection of sources that was used for psf matching.
998 mask = difference.mask
999 badPix = (mask.array & mask.getPlaneBitMask(self.config.detection.excludeMaskPlanes)) > 0
1000 self.metadata[
"nGoodPixels"] = np.sum(~badPix)
1001 self.metadata[
"nBadPixels"] = np.sum(badPix)
1002 detPosPix = (mask.array & mask.getPlaneBitMask(
"DETECTED")) > 0
1003 detNegPix = (mask.array & mask.getPlaneBitMask(
"DETECTED_NEGATIVE")) > 0
1004 self.metadata[
"nPixelsDetectedPositive"] = np.sum(detPosPix)
1005 self.metadata[
"nPixelsDetectedNegative"] = np.sum(detNegPix)
1008 self.metadata[
"nBadPixelsDetectedPositive"] = np.sum(detPosPix)
1009 self.metadata[
"nBadPixelsDetectedNegative"] = np.sum(detNegPix)
1011 metricsMaskPlanes = list(mask.getMaskPlaneDict().keys())
1012 for maskPlane
in metricsMaskPlanes:
1014 self.metadata[
"%s_mask_fraction"%maskPlane.lower()] = evaluateMaskFraction(mask, maskPlane)
1015 except InvalidParameterError:
1016 self.metadata[
"%s_mask_fraction"%maskPlane.lower()] = -1
1017 self.log.info(
"Unable to calculate metrics for mask plane %s: not in image"%maskPlane)
1019 if self.config.doSkySources:
1020 skySources = diaSources[diaSources[
"sky_source"]]
1023 metrics = computeDifferenceImageMetrics(science, difference, kernelSources, sky_sources=skySources)
1025 self.metadata[
"residualFootprintRatioMean"] = metrics.differenceFootprintRatioMean
1026 self.metadata[
"residualFootprintRatioStdev"] = metrics.differenceFootprintRatioStdev
1027 self.metadata[
"differenceFootprintSkyRatioMean"] = metrics.differenceFootprintSkyRatioMean
1028 self.metadata[
"differenceFootprintSkyRatioStdev"] = metrics.differenceFootprintSkyRatioStdev
1029 self.log.info(
"Mean, stdev of ratio of difference to science "
1030 "pixels in star footprints: %5.4f, %5.4f",
1031 self.metadata[
"residualFootprintRatioMean"],
1032 self.metadata[
"residualFootprintRatioStdev"])
1033 if self.config.raiseOnBadSubtractionRatio:
1034 if metrics.differenceFootprintRatioMean > self.config.badSubtractionRatioThreshold:
1036 threshold=self.config.badSubtractionRatioThreshold)
1037 if metrics.differenceFootprintRatioStdev > self.config.badSubtractionVariationThreshold:
1039 threshold=self.config.badSubtractionVariationThreshold)
1041 def getSattleDiaSourceAllowlist(self, diaSources, science):
1042 """Query the sattle service and determine which diaSources are allowed.
1046 diaSources : `lsst.afw.table.SourceCatalog`
1047 The catalog of detected sources.
1048 science : `lsst.afw.image.ExposureF`
1049 Science exposure that was subtracted.
1053 allow_list : `list` of `int`
1054 diaSourceIds of diaSources that can be made public.
1059 Raised if sattle call does not return success.
1061 wcs = science.getWcs()
1062 visit_info = science.getInfo().getVisitInfo()
1063 visit_id = visit_info.getId()
1064 sattle_uri_base = os.getenv(
'SATTLE_URI_BASE')
1066 dia_sources_json = []
1067 for source
in diaSources:
1068 source_bbox = source.getFootprint().getBBox()
1069 corners = wcs.pixelToSky([
lsst.geom.Point2D(c)
for c
in source_bbox.getCorners()])
1070 bbox_radec = [[pt.getRa().asDegrees(), pt.getDec().asDegrees()]
for pt
in corners]
1071 dia_sources_json.append({
"diasource_id": source[
"id"],
"bbox": bbox_radec})
1073 payload = {
"visit_id": visit_id,
"detector_id": science.getDetector().getId(),
1074 "diasources": dia_sources_json,
"historical": self.config.sattle_historical}
1076 sattle_output = requests.put(f
'{sattle_uri_base}/diasource_allow_list',
1080 if sattle_output.status_code == 404:
1081 self.log.warning(f
'Visit {visit_id} not found in sattle cache, re-sending')
1082 populate_sattle_visit_cache(visit_info, historical=self.config.sattle_historical)
1083 sattle_output = requests.put(f
'{sattle_uri_base}/diasource_allow_list', json=payload)
1085 sattle_output.raise_for_status()
1087 return sattle_output.json()[
'allow_list']
1089 def filterSatellites(self, diaSources, science):
1090 """Remove diaSources overlapping predicted satellite positions.
1094 diaSources : `lsst.afw.table.SourceCatalog`
1095 The catalog of detected sources.
1096 science : `lsst.afw.image.ExposureF`
1097 Science exposure that was subtracted.
1101 filterdDiaSources : `lsst.afw.table.SourceCatalog`
1102 Filtered catalog of diaSources
1105 allow_list = self.getSattleDiaSourceAllowlist(diaSources, science)
1108 allow_set = set(allow_list)
1109 allowed_ids = [source[
'id']
in allow_set
for source
in diaSources]
1110 diaSources = diaSources[np.array(allowed_ids)].copy(deep=
True)
1112 self.log.warning(
'Sattle allowlist is empty, all diaSources removed')
1113 diaSources = diaSources[0:0].copy(deep=
True)
1116 def _runStreakMasking(self, difference):
1117 """Do streak masking and optionally save the resulting streak
1118 fit parameters in a catalog.
1120 Only returns non-empty streakInfo if self.config.writeStreakInfo
1121 is set. The difference image is binned by self.config.streakBinFactor
1122 (and detection is run a second time) so that regions with lower
1123 surface brightness streaks are more likely to fall above the
1124 detection threshold.
1128 difference: `lsst.afw.image.Exposure`
1129 The exposure in which to search for streaks. Must have a detection
1134 streakInfo: `lsst.pipe.base.Struct`
1135 ``rho`` : `np.ndarray`
1136 Angle of detected streak.
1137 ``theta`` : `np.ndarray`
1138 Distance from center of detected streak.
1139 ``sigma`` : `np.ndarray`
1140 Width of streak profile.
1141 ``reducedChi2`` : `np.ndarray`
1142 Reduced chi2 of the best-fit streak profile.
1143 ``modelMaximum`` : `np.ndarray`
1144 Peak value of the fit line profile.
1146 maskedImage = difference.maskedImage
1149 self.config.streakBinFactor,
1150 self.config.streakBinFactor)
1151 binnedExposure = afwImage.ExposureF(binnedMaskedImage.getBBox())
1152 binnedExposure.setMaskedImage(binnedMaskedImage)
1154 binnedExposure.mask &= ~binnedExposure.mask.getPlaneBitMask(
'DETECTED')
1156 sigma = difference.psf.computeShape(difference.psf.getAveragePosition()).getDeterminantRadius()
1157 _table = afwTable.SourceTable.make(afwTable.SourceTable.makeMinimalSchema())
1158 self.streakDetection.
run(table=_table, exposure=binnedExposure, doSmooth=
True,
1159 sigma=sigma/self.config.streakBinFactor)
1160 binnedDetectedMaskPlane = binnedExposure.mask.array & binnedExposure.mask.getPlaneBitMask(
'DETECTED')
1161 rescaledDetectedMaskPlane = binnedDetectedMaskPlane.repeat(self.config.streakBinFactor,
1162 axis=0).repeat(self.config.streakBinFactor,
1165 streakMaskedImage = maskedImage.clone()
1166 ysize, xsize = rescaledDetectedMaskPlane.shape
1167 streakMaskedImage.mask.array[:ysize, :xsize] |= rescaledDetectedMaskPlane
1169 streaks = self.maskStreaks.
run(streakMaskedImage)
1170 streakMaskPlane = streakMaskedImage.mask.array & streakMaskedImage.mask.getPlaneBitMask(
'STREAK')
1172 maskedImage.mask.array |= streakMaskPlane
1174 if self.config.writeStreakInfo:
1175 rhos = np.array([line.rho
for line
in streaks.lines])
1176 thetas = np.array([line.theta
for line
in streaks.lines])
1177 sigmas = np.array([line.sigma
for line
in streaks.lines])
1178 chi2s = np.array([line.reducedChi2
for line
in streaks.lines])
1179 modelMaximums = np.array([line.modelMaximum
for line
in streaks.lines])
1180 streakInfo = {
'rho': rhos,
'theta': thetas,
'sigma': sigmas,
'reducedChi2': chi2s,
1181 'modelMaximum': modelMaximums}
1183 streakInfo = {
'rho': np.array([]),
'theta': np.array([]),
'sigma': np.array([]),
1184 'reducedChi2': np.array([]),
'modelMaximum': np.array([])}
1185 return pipeBase.Struct(maskedStreaks=streakInfo)
1189 scoreExposure = pipeBase.connectionTypes.Input(
1190 doc=
"Maximum likelihood image for detection.",
1191 dimensions=(
"instrument",
"visit",
"detector"),
1192 storageClass=
"ExposureF",
1193 name=
"{fakesType}{coaddName}Diff_scoreExp",
1197class DetectAndMeasureScoreConfig(DetectAndMeasureConfig,
1198 pipelineConnections=DetectAndMeasureScoreConnections):
1202class DetectAndMeasureScoreTask(DetectAndMeasureTask):
1203 """Detect DIA sources using a score image,
1204 and measure the detections on the difference image.
1206 Source detection is run on the supplied score, or maximum likelihood,
1207 image. Note that no additional convolution will be done in this case.
1208 Close positive and negative detections will optionally be merged into
1210 Sky sources, or forced detections in background regions, will optionally
1211 be added, and the configured measurement algorithm will be run on all
1214 ConfigClass = DetectAndMeasureScoreConfig
1215 _DefaultName =
"detectAndMeasureScore"
1218 def run(self, science, matchedTemplate, difference, scoreExposure, kernelSources,
1220 """Detect and measure sources on a score image.
1224 science : `lsst.afw.image.ExposureF`
1225 Science exposure that the template was subtracted from.
1226 matchedTemplate : `lsst.afw.image.ExposureF`
1227 Warped and PSF-matched template that was used produce the
1229 difference : `lsst.afw.image.ExposureF`
1230 Result of subtracting template from the science image.
1231 scoreExposure : `lsst.afw.image.ExposureF`
1232 Score or maximum likelihood difference image
1233 kernelSources : `lsst.afw.table.SourceCatalog`
1234 Final selection of sources that was used for psf matching.
1235 idFactory : `lsst.afw.table.IdFactory`, optional
1236 Generator object used to assign ids to detected sources in the
1237 difference image. Ids from this generator are not set until after
1238 deblending and merging positive/negative peaks.
1242 measurementResults : `lsst.pipe.base.Struct`
1244 ``subtractedMeasuredExposure`` : `lsst.afw.image.ExposureF`
1245 Subtracted exposure with detection mask applied.
1246 ``diaSources`` : `lsst.afw.table.SourceCatalog`
1247 The catalog of detected sources.
1249 if idFactory
is None:
1250 idFactory = lsst.meas.base.IdGenerator().make_table_id_factory()
1252 self._prepareInputs(scoreExposure)
1257 table = afwTable.SourceTable.make(self.schema)
1258 results = self.detection.
run(
1260 exposure=scoreExposure,
1264 difference.mask.assign(scoreExposure.mask, scoreExposure.getBBox())
1266 if self.config.doDeblend:
1267 sources, positives, negatives = self._deblend(difference,
1271 return self.processResults(science, matchedTemplate, difference,
1272 sources, idFactory, kernelSources,
1273 positives=positives,
1274 negatives=negatives)
1277 positives = afwTable.SourceCatalog(self.schema)
1278 results.positive.makeSources(positives)
1279 negatives = afwTable.SourceCatalog(self.schema)
1280 results.negative.makeSources(negatives)
1281 return self.processResults(science, matchedTemplate, difference,
1282 results.sources, idFactory, kernelSources,
1283 positives=positives,
1284 negatives=negatives)
__init__(self, *, ratio, threshold)
std::shared_ptr< ImageT > binImage(ImageT const &inImage, int const binX, int const binY, lsst::afw::math::Property const flags=lsst::afw::math::MEAN)
run(self, *, coaddExposureHandles, bbox, wcs, dataIds, physical_filter)