lsst.ip.diffim g3169688e06+4f2cee96cd
Loading...
Searching...
No Matches
detectAndMeasure.py
Go to the documentation of this file.
1# This file is part of ip_diffim.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
21
22import numpy as np
23import requests
24import os
25
26import lsst.afw.detection as afwDetection
27import lsst.afw.image as afwImage
28import lsst.afw.math as afwMath
29import lsst.afw.table as afwTable
30import lsst.daf.base as dafBase
31import lsst.geom
32from lsst.ip.diffim.utils import (evaluateMaskFraction, computeDifferenceImageMetrics,
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 # noqa: F401
39import lsst.meas.extensions.shapeHSM
40import lsst.pex.config as pexConfig
41from lsst.pex.exceptions import InvalidParameterError
42import lsst.pipe.base as pipeBase
43import lsst.utils
44from lsst.utils.timer import timeMethod
45
46from . import DipoleFitTask
47
48__all__ = ["DetectAndMeasureConfig", "DetectAndMeasureTask",
49 "DetectAndMeasureScoreConfig", "DetectAndMeasureScoreTask"]
50
51
52class BadSubtractionError(pipeBase.AlgorithmError):
53 """Raised when the residuals in footprints of stars used to compute the
54 psf-matching kernel exceeds the configured maximum.
55 """
56 def __init__(self, *, ratio, threshold):
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}")
61 super().__init__(msg)
62 self.ratio = ratio
63 self.threshold = threshold
64
65 @property
66 def metadata(self):
67 return {"ratio": self.ratio,
68 "threshold": self.threshold
69 }
70
71
72class NoDiaSourcesError(pipeBase.AlgorithmError):
73 """Raised when there are no diaSources detected on an image difference.
74 """
75 def __init__(self):
76 msg = ("No diaSources detected!")
77 super().__init__(msg)
78
79 @property
80 def metadata(self):
81 return {}
82
83
84class DetectAndMeasureConnections(pipeBase.PipelineTaskConnections,
85 dimensions=("instrument", "visit", "detector"),
86 defaultTemplates={"coaddName": "deep",
87 "warpTypeSuffix": "",
88 "fakesType": ""}):
89 science = pipeBase.connectionTypes.Input(
90 doc="Input science exposure.",
91 dimensions=("instrument", "visit", "detector"),
92 storageClass="ExposureF",
93 name="{fakesType}calexp"
94 )
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",
100 )
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",
106 )
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"
112 )
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",
117 )
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",
123 )
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",
129 )
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",
135 )
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",
141 )
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",
147 )
148
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")
157
158
159class DetectAndMeasureConfig(pipeBase.PipelineTaskConfig,
160 pipelineConnections=DetectAndMeasureConnections):
161 """Config for DetectAndMeasureTask
162 """
163 doMerge = pexConfig.Field(
164 dtype=bool,
165 default=True,
166 doc="Merge positive and negative diaSources with grow radius "
167 "set by growFootprint"
168 )
169 doForcedMeasurement = pexConfig.Field(
170 dtype=bool,
171 default=True,
172 doc="Force photometer diaSource locations on PVI?"
173 )
174 doAddMetrics = pexConfig.Field(
175 dtype=bool,
176 default=False,
177 doc="Add columns to the source table to hold analysis metrics?"
178 )
179 doSubtractBackground = pexConfig.Field(
180 dtype=bool,
181 doc="Subtract a background model from the image before detection?",
182 default=True,
183 )
184 doWriteBackground = pexConfig.Field(
185 dtype=bool,
186 doc="Persist the fitted background model?",
187 default=False,
188 )
189 subtractInitialBackground = pexConfig.ConfigurableField(
190 target=lsst.meas.algorithms.SubtractBackgroundTask,
191 doc="Task to perform intial background subtraction, before first detection pass.",
192 )
193 subtractFinalBackground = pexConfig.ConfigurableField(
194 target=lsst.meas.algorithms.SubtractBackgroundTask,
195 doc="Task to perform final background subtraction, after first detection pass.",
196 )
197 detection = pexConfig.ConfigurableField(
198 target=SourceDetectionTask,
199 doc="Final source detection for diaSource measurement",
200 )
201 streakDetection = pexConfig.ConfigurableField(
202 target=SourceDetectionTask,
203 doc="Separate source detection used only for streak masking",
204 )
205 doDeblend = pexConfig.Field(
206 dtype=bool,
207 default=False,
208 doc="Deblend DIASources after detection?"
209 )
210 deblend = pexConfig.ConfigurableField(
211 target=lsst.meas.deblender.SourceDeblendTask,
212 doc="Task to split blended sources into their components."
213 )
214 measurement = pexConfig.ConfigurableField(
215 target=DipoleFitTask,
216 doc="Task to measure sources on the difference image.",
217 )
218 doApCorr = lsst.pex.config.Field(
219 dtype=bool,
220 default=True,
221 doc="Run subtask to apply aperture corrections"
222 )
223 applyApCorr = lsst.pex.config.ConfigurableField(
224 target=ApplyApCorrTask,
225 doc="Task to apply aperture corrections"
226 )
227 forcedMeasurement = pexConfig.ConfigurableField(
228 target=ForcedMeasurementTask,
229 doc="Task to force photometer science image at diaSource locations.",
230 )
231 growFootprint = pexConfig.Field(
232 dtype=int,
233 default=2,
234 doc="Grow positive and negative footprints by this many pixels before merging"
235 )
236 diaSourceMatchRadius = pexConfig.Field(
237 dtype=float,
238 default=0.5,
239 doc="Match radius (in arcseconds) for DiaSource to Source association"
240 )
241 doSkySources = pexConfig.Field(
242 dtype=bool,
243 default=False,
244 doc="Generate sky sources?",
245 )
246 skySources = pexConfig.ConfigurableField(
247 target=SkyObjectsTask,
248 doc="Generate sky sources",
249 )
250 doMaskStreaks = pexConfig.Field(
251 dtype=bool,
252 default=True,
253 doc="Turn on streak masking",
254 )
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.",
259 )
260 streakBinFactor = pexConfig.Field(
261 dtype=int,
262 default=4,
263 doc="Bin scale factor to use when rerunning detection for masking streaks. "
264 "Only used if doMaskStreaks is True.",
265 )
266 writeStreakInfo = pexConfig.Field(
267 dtype=bool,
268 default=False,
269 doc="Record the parameters of any detected streaks. For LSST, this should be turned off except for "
270 "development work."
271 )
272 findGlints = pexConfig.ConfigurableField(
273 target=FindGlintTrailsTask,
274 doc="Subtask for finding glint trails, usually caused by satellites or debris."
275 )
276 writeGlintInfo = pexConfig.Field(
277 dtype=bool,
278 default=True,
279 doc="Record the parameters of any detected glint trails."
280 )
281 setPrimaryFlags = pexConfig.ConfigurableField(
282 target=SetPrimaryFlagsTask,
283 doc="Task to add isPrimary and deblending-related flags to the catalog."
284 )
285 badSourceFlags = lsst.pex.config.ListField(
286 dtype=str,
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",
294 ),
295 )
296 clearMaskPlanes = lsst.pex.config.ListField(
297 dtype=str,
298 doc="Mask planes to clear before running detection.",
299 default=("DETECTED", "DETECTED_NEGATIVE", "NOT_DEBLENDED", "STREAK"),
300 )
301 raiseOnBadSubtractionRatio = pexConfig.Field(
302 dtype=bool,
303 default=True,
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``",
307 )
308 badSubtractionRatioThreshold = pexConfig.Field(
309 dtype=float,
310 default=0.2,
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",
314 )
315 badSubtractionVariationThreshold = pexConfig.Field(
316 dtype=float,
317 default=0.4,
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",
321 )
322 raiseOnNoDiaSources = pexConfig.Field(
323 dtype=bool,
324 default=True,
325 doc="Raise an algorithm error if no diaSources are detected.",
326 )
327 run_sattle = pexConfig.Field(
328 dtype=bool,
329 default=False,
330 doc="If true, dia source bounding boxes will be sent for verification"
331 "to the sattle service."
332 )
333 sattle_historical = pexConfig.Field(
334 dtype=bool,
335 default=False,
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."
339 )
340 idGenerator = DetectorVisitIdGeneratorConfig.make_field()
341
342 def setDefaults(self):
343 # Background subtraction
344 # Use a small binsize for the first pass to reduce detections on glints
345 # and extended structures. Should not affect the detectability of
346 # faint diaSources
347 self.subtractInitialBackground.binSize = 8
348 self.subtractInitialBackground.useApprox = False
349 self.subtractInitialBackground.statisticsProperty = "MEDIAN"
350 self.subtractInitialBackground.doFilterSuperPixels = True
351 # Use a larger binsize for the final background subtraction, to reduce
352 # over-subtraction of bright objects.
353 self.subtractFinalBackground.binSize = 40
354 self.subtractFinalBackground.useApprox = False
355 self.subtractFinalBackground.statisticsProperty = "MEDIAN"
356 self.subtractFinalBackground.doFilterSuperPixels = True
357 # DiaSource Detection
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",
363 "BAD",
364 ]
365
366 # Copy configs for binned streak detection from the base detection task
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
371 # Only detect positive streaks
372 self.streakDetection.thresholdPolarity = "positive"
373 # Do not grow detected mask for streaks
374 self.streakDetection.nSigmaToGrow = 0
375 # Set the streak mask along the entire fit line, not only where the
376 # detected mask is set.
377 self.maskStreaks.onlyMaskDetected = False
378 # Restrict streak masking from growing too large
379 self.maskStreaks.maxStreakWidth = 100
380 # Restrict the number of iterations allowed for fitting streaks
381 # When the fit is good it should solve quickly, and exit a bad fit quickly
382 self.maskStreaks.maxFitIter = 10
383 # Only mask to 2 sigma in width
384 self.maskStreaks.nSigmaMask = 2
385 # Threshold for including streaks after the Hough Transform.
386 # A lower value will detect more features that are less linear.
387 self.maskStreaks.absMinimumKernelHeight = 2
388
389 self.measurement.plugins.names |= ["ext_trailedSources_Naive",
390 "base_LocalPhotoCalib",
391 "base_LocalWcs",
392 "ext_shapeHSM_HsmSourceMoments",
393 "ext_shapeHSM_HsmPsfMoments",
394 "base_ClassificationSizeExtendedness",
395 ]
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
404
405 # Keep track of which footprints contain streaks
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"]
411
412 def validate(self):
413 super().validate()
414
415 if self.run_sattle:
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.")
420
421
422class DetectAndMeasureTask(lsst.pipe.base.PipelineTask):
423 """Detect and measure sources on a difference image.
424 """
425 ConfigClass = DetectAndMeasureConfig
426 _DefaultName = "detectAndMeasure"
427
428 def __init__(self, **kwargs):
429 super().__init__(**kwargs)
430 self.schema = afwTable.SourceTable.makeMinimalSchema()
431
432 self.algMetadata = dafBase.PropertyList()
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.",
448 units="count")
449 self.schema.addField(
450 "ip_diffim_forced_PsfFlux_instFluxErr", "D",
451 "Forced PSF flux error measured on the direct image.",
452 units="count")
453 self.schema.addField(
454 "ip_diffim_forced_PsfFlux_area", "F",
455 "Forced PSF flux effective area of PSF.",
456 units="pixel")
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)
467
468 self.schema.addField("refMatchId", "L", "unique id of reference catalog match")
469 self.schema.addField("srcMatchId", "L", "unique id of source match")
470 # Create the sky source task for use by metrics,
471 # even if sky sources are not added to the diaSource catalog
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.")
478
479 # To get the "merge_*" fields in the schema; have to re-initialize
480 # this later, once we have a peak schema post-detection.
481 lsst.afw.detection.FootprintMergeList(self.schema, ["positive", "negative"])
482
483 # Check that the schema and config are consistent
484 for flag in self.config.badSourceFlags:
485 if flag not in self.schema:
486 raise pipeBase.InvalidQuantumError("Field %s not in schema" % flag)
487
488 # initialize InitOutputs
489 self.outputSchema = afwTable.SourceCatalog(self.schema)
490 self.outputSchema.getTable().setMetadata(self.algMetadata)
491
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()
498 # Specify the fields that `annotate` needs below, to ensure they
499 # exist, even as None.
500 measurementResults = pipeBase.Struct(
501 subtractedMeasuredExposure=None,
502 diaSources=None,
503 maskedStreaks=None,
504 differenceBackground=None,
505 )
506 try:
507 self.run(**inputs, idFactory=idFactory, measurementResults=measurementResults)
508 except pipeBase.AlgorithmError as e:
509 error = pipeBase.AnnotatedPartialOutputsError.annotate(
510 e,
511 self,
512 measurementResults.subtractedMeasuredExposure,
513 measurementResults.diaSources,
514 measurementResults.maskedStreaks,
515 measurementResults.glintTrailInfo,
516 log=self.log
517 )
518 butlerQC.put(measurementResults, outputRefs)
519 raise error from e
520 butlerQC.put(measurementResults, outputRefs)
521
522 @timeMethod
523 def run(self, science, matchedTemplate, difference, kernelSources,
524 idFactory=None, measurementResults=None):
525 """Detect and measure sources on a difference image.
526
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
530 dipole diaSources.
531 Sky sources, or forced detections in background regions, will optionally
532 be added, and the configured measurement algorithm will be run on all
533 detections.
534
535 Parameters
536 ----------
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
541 difference image.
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.
554
555 Returns
556 -------
557 measurementResults : `lsst.pipe.base.Struct`
558
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.
565 """
566 if measurementResults is None:
567 measurementResults = pipeBase.Struct()
568 if idFactory is None:
569 idFactory = lsst.meas.base.IdGenerator().make_table_id_factory()
570
571 if self.config.doSubtractBackground:
572 # Run background subtraction before clearing the mask planes
573 detectionExposure = difference.clone()
574 background = self.subtractInitialBackground.run(detectionExposure).background
575 else:
576 detectionExposure = difference
577 background = afwMath.BackgroundList()
578
579 self._prepareInputs(detectionExposure)
580
581 # Don't use the idFactory until after deblend+merge, so that we aren't
582 # generating ids that just get thrown away (footprint merge doesn't
583 # know about past ids).
584 table = afwTable.SourceTable.make(self.schema)
585 results = self.detection.run(
586 table=table,
587 exposure=detectionExposure,
588 doSmooth=True,
589 background=background
590 )
591
592 if self.config.doSubtractBackground:
593 # Run background subtraction again after detecting peaks
594 # but before measurement
595 # First update the mask using the detection image
596 difference.setMask(detectionExposure.mask)
597 background = self.subtractFinalBackground.run(difference).background
598
599 # Re-run detection to get final footprints
600 table = afwTable.SourceTable.make(self.schema)
601 results = self.detection.run(
602 table=table,
603 exposure=difference,
604 doSmooth=True,
605 background=background
606 )
607 measurementResults.differenceBackground = background
608
609 if self.config.doDeblend:
610 sources, positives, negatives = self._deblend(difference,
611 results.positive,
612 results.negative)
613
614 else:
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
620
621 self.processResults(science, matchedTemplate, difference,
622 sources, idFactory, kernelSources,
623 positives=positives,
624 negatives=negatives,
625 measurementResults=measurementResults)
626 return measurementResults
627
628 def _prepareInputs(self, difference):
629 """Ensure that we start with an empty detection and deblended mask.
630
631 Parameters
632 ----------
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.
636
637 Raises
638 ------
639 lsst.pipe.base.UpstreamFailureNoWorkFound
640 If the PSF is not usable for measurement.
641 """
642 # Check that we have a valid PSF now before we do more work
643 sigma = difference.psf.computeShape(difference.psf.getAveragePosition()).getDeterminantRadius()
644 if np.isnan(sigma):
645 raise pipeBase.UpstreamFailureNoWorkFound("Invalid PSF detected! PSF width evaluates to NaN.")
646 # Ensure that we start with an empty detection and deblended mask.
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)
652
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.
656
657 Parameters
658 ----------
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
663 difference image.
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
670 difference image.
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.
681
682 Returns
683 -------
684 measurementResults : `lsst.pipe.base.Struct`
685
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.
690 """
691 if measurementResults is None:
692 measurementResults = pipeBase.Struct()
693 self.metadata["nUnmergedDiaSources"] = len(sources)
694 if self.config.doMerge:
695 # preserve peak schema, if there are any footprints
696 if len(positives) > 0:
697 peakSchema = positives[0].getFootprint().peaks.schema
698 elif len(negatives) > 0:
699 peakSchema = negatives[0].getFootprint().peaks.schema
700 else:
701 peakSchema = afwDetection.PeakTable.makeMinimalSchema()
702 mergeList = afwDetection.FootprintMergeList(self.schema,
703 ["positive", "negative"], peakSchema)
704 initialDiaSources = afwTable.SourceCatalog(self.schema)
705 # Start with positive, as FootprintMergeList will self-merge the
706 # subsequent added catalogs, and we want to try to preserve
707 # deblended positive sources.
708 mergeList.addCatalog(initialDiaSources.table, positives, "positive", minNewPeakDist=0)
709 mergeList.addCatalog(initialDiaSources.table, negatives, "negative", minNewPeakDist=0)
710 mergeList.getFinalSources(initialDiaSources)
711 # Flag as negative those sources that *only* came from the negative
712 # footprint set.
713 initialDiaSources["is_negative"] = initialDiaSources["merge_footprint_negative"] & \
714 ~initialDiaSources["merge_footprint_positive"]
715 self.log.info("Merging detections into %d sources", len(initialDiaSources))
716 else:
717 initialDiaSources = sources
718
719 # Assign source ids at the end: deblend/merge mean that we don't keep
720 # track of parents and children, we only care about the final ids.
721 for source in initialDiaSources:
722 source.setId(idFactory())
723 # Ensure sources added after this get correct ids.
724 initialDiaSources.getTable().setIdFactory(idFactory)
725 initialDiaSources.setMetadata(self.algMetadata)
726
727 self.metadata["nMergedDiaSources"] = len(initialDiaSources)
728
729 if self.config.doMaskStreaks:
730 streakInfo = self._runStreakMasking(difference)
731
732 if self.config.doSkySources:
733 self.addSkySources(initialDiaSources, difference.mask, difference.info.id)
734
735 if not initialDiaSources.isContiguous():
736 initialDiaSources = initialDiaSources.copy(deep=True)
737
738 self.measureDiaSources(initialDiaSources, science, difference, matchedTemplate)
739
740 # Add a column for glint trail diaSources, but do not remove them
741 initialDiaSources, trail_parameters = self._find_glint_trails(initialDiaSources)
742 if self.config.writeGlintInfo:
743 measurementResults.mergeItems(trail_parameters, 'glintTrailInfo')
744
745 # Remove unphysical diaSources per config.badSourceFlags
746 diaSources = self._removeBadSources(initialDiaSources)
747
748 if self.config.run_sattle:
749 diaSources = self.filterSatellites(diaSources, science)
750
751 if self.config.doForcedMeasurement:
752 self.measureForcedSources(diaSources, science, difference.getWcs())
753
754 measurementResults.subtractedMeasuredExposure = difference
755
756 if self.config.doMaskStreaks and self.config.writeStreakInfo:
757 measurementResults.mergeItems(streakInfo, 'maskedStreaks')
758
759 self.calculateMetrics(science, difference, diaSources, kernelSources)
760
761 if np.count_nonzero(~diaSources["sky_source"]) > 0:
762 measurementResults.diaSources = diaSources
763 elif self.config.raiseOnNoDiaSources:
764 raise NoDiaSourcesError()
765 elif len(diaSources) > 0:
766 # This option allows returning sky sources,
767 # even if there are no diaSources
768 measurementResults.diaSources = diaSources
769
770 return measurementResults
771
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.
775
776 Parameters
777 ----------
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.
783
784 Returns
785 -------
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``.
791 """
792
793 def deblend(footprints, negative=False):
794 """Deblend a positive or negative footprint set,
795 and return the deblended children.
796
797 Parameters
798 ----------
799 footprints : `lsst.afw.detection.FootprintSet`
800 negative : `bool`
801 Set True if the footprints contain negative fluxes
802
803 Returns
804 -------
805 sources : `lsst.afw.table.SourceCatalog`
806 """
807 sources = afwTable.SourceCatalog(self.schema)
808 footprints.makeSources(sources)
809 if negative:
810 # Invert the image so the deblender can run on positive peaks
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]
815 # Set the heavy footprint pixel values back to reality
816 for child in children:
817 footprint = child.getFootprint()
818 array = footprint.getImageArray()
819 array *= -1
820 else:
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)
825 # Clear parents, so that measurement plugins behave correctly.
826 sources['parent'] = 0
827 return sources.copy(deep=True)
828
829 positives = deblend(positiveFootprints)
830 negatives = deblend(negativeFootprints, negative=True)
831
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
839
840 def _removeBadSources(self, diaSources):
841 """Remove unphysical diaSources from the catalog.
842
843 Parameters
844 ----------
845 diaSources : `lsst.afw.table.SourceCatalog`
846 The catalog of detected sources.
847
848 Returns
849 -------
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.
853 """
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)
858 if nBad > 0:
859 self.log.debug("Found %d unphysical sources with flag %s.", nBad, flag)
860 selector &= ~flags
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)
865
866 def _find_glint_trails(self, diaSources):
867 """Define a new flag column for diaSources that are in a glint trail.
868
869 Parameters
870 ----------
871 diaSources : `lsst.afw.table.SourceCatalog`
872 The catalog of detected sources.
873
874 Returns
875 -------
876 diaSources : `lsst.afw.table.SourceCatalog`
877 The updated catalog of detected sources, with a new bool column
878 called 'glint_trail' added.
879
880 trail_parameters : `dict`
881 Parameters of all the trails that were found.
882 """
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)
886
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,
893 'angles': angles}
894
895 trail_parameters = pipeBase.Struct(glintTrailInfo=parameters)
896
897 return diaSources, trail_parameters
898
899 def addSkySources(self, diaSources, mask, seed,
900 subtask=None):
901 """Add sources in empty regions of the difference image
902 for measuring the background.
903
904 Parameters
905 ----------
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.
910 seed : `int`
911 Seed value to initialize the random number generator.
912 """
913 if subtask is None:
914 subtask = self.skySources
915 skySourceFootprints = subtask.run(mask=mask, seed=seed, catalog=diaSources)
916 self.metadata[f"n_{subtask.getName()}"] = len(skySourceFootprints)
917
918 def measureDiaSources(self, diaSources, science, difference, matchedTemplate):
919 """Use (matched) template and science image to constrain dipole fitting.
920
921 Parameters
922 ----------
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
931 difference image.
932 """
933 # Ensure that the required mask planes are present
934 for mp in self.config.measurement.plugins["base_PixelFlags"].masksFpAnywhere:
935 difference.mask.addMaskPlane(mp)
936 # Note that this may not be correct if we convolved the science image.
937 # In the future we may wish to persist the matchedScience image.
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.")
943 else:
944 self.applyApCorr.run(
945 catalog=diaSources,
946 apCorrMap=apCorrMap,
947 )
948
949 def measureForcedSources(self, diaSources, science, wcs):
950 """Perform forced measurement of the diaSources on the science image.
951
952 Parameters
953 ----------
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.
960 """
961 # Run forced psf photometry on the PVI at the diaSource locations.
962 # Copy the measured flux and error into the diaSource.
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)
980
981 def calculateMetrics(self, science, difference, diaSources, kernelSources):
982 """Add difference image QA metrics to the Task metadata.
983
984 This may be used to produce corresponding metrics (see
985 lsst.analysis.tools.tasks.diffimTaskDetectorVisitMetricAnalysis).
986
987 Parameters
988 ----------
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.
997 """
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)
1006 detPosPix &= badPix
1007 detNegPix &= badPix
1008 self.metadata["nBadPixelsDetectedPositive"] = np.sum(detPosPix)
1009 self.metadata["nBadPixelsDetectedNegative"] = np.sum(detNegPix)
1010
1011 metricsMaskPlanes = list(mask.getMaskPlaneDict().keys())
1012 for maskPlane in metricsMaskPlanes:
1013 try:
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)
1018
1019 if self.config.doSkySources:
1020 skySources = diaSources[diaSources["sky_source"]]
1021 else:
1022 skySources = None
1023 metrics = computeDifferenceImageMetrics(science, difference, kernelSources, sky_sources=skySources)
1024
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:
1035 raise BadSubtractionError(ratio=metrics.differenceFootprintRatioMean,
1036 threshold=self.config.badSubtractionRatioThreshold)
1037 if metrics.differenceFootprintRatioStdev > self.config.badSubtractionVariationThreshold:
1038 raise BadSubtractionError(ratio=metrics.differenceFootprintRatioStdev,
1039 threshold=self.config.badSubtractionVariationThreshold)
1040
1041 def getSattleDiaSourceAllowlist(self, diaSources, science):
1042 """Query the sattle service and determine which diaSources are allowed.
1043
1044 Parameters
1045 ----------
1046 diaSources : `lsst.afw.table.SourceCatalog`
1047 The catalog of detected sources.
1048 science : `lsst.afw.image.ExposureF`
1049 Science exposure that was subtracted.
1050
1051 Returns
1052 ----------
1053 allow_list : `list` of `int`
1054 diaSourceIds of diaSources that can be made public.
1055
1056 Raises
1057 ------
1058 requests.HTTPError
1059 Raised if sattle call does not return success.
1060 """
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')
1065
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})
1072
1073 payload = {"visit_id": visit_id, "detector_id": science.getDetector().getId(),
1074 "diasources": dia_sources_json, "historical": self.config.sattle_historical}
1075
1076 sattle_output = requests.put(f'{sattle_uri_base}/diasource_allow_list',
1077 json=payload)
1078
1079 # retry once if visit cache is not populated
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)
1084
1085 sattle_output.raise_for_status()
1086
1087 return sattle_output.json()['allow_list']
1088
1089 def filterSatellites(self, diaSources, science):
1090 """Remove diaSources overlapping predicted satellite positions.
1091
1092 Parameters
1093 ----------
1094 diaSources : `lsst.afw.table.SourceCatalog`
1095 The catalog of detected sources.
1096 science : `lsst.afw.image.ExposureF`
1097 Science exposure that was subtracted.
1098
1099 Returns
1100 ----------
1101 filterdDiaSources : `lsst.afw.table.SourceCatalog`
1102 Filtered catalog of diaSources
1103 """
1104
1105 allow_list = self.getSattleDiaSourceAllowlist(diaSources, science)
1106
1107 if allow_list:
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)
1111 else:
1112 self.log.warning('Sattle allowlist is empty, all diaSources removed')
1113 diaSources = diaSources[0:0].copy(deep=True)
1114 return diaSources
1115
1116 def _runStreakMasking(self, difference):
1117 """Do streak masking and optionally save the resulting streak
1118 fit parameters in a catalog.
1119
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.
1125
1126 Parameters
1127 ----------
1128 difference: `lsst.afw.image.Exposure`
1129 The exposure in which to search for streaks. Must have a detection
1130 mask.
1131
1132 Returns
1133 -------
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.
1145 """
1146 maskedImage = difference.maskedImage
1147 # Bin the diffim to enhance low surface brightness streaks
1148 binnedMaskedImage = afwMath.binImage(maskedImage,
1149 self.config.streakBinFactor,
1150 self.config.streakBinFactor)
1151 binnedExposure = afwImage.ExposureF(binnedMaskedImage.getBBox())
1152 binnedExposure.setMaskedImage(binnedMaskedImage)
1153 # Clear the DETECTED mask plane before streak detection
1154 binnedExposure.mask &= ~binnedExposure.mask.getPlaneBitMask('DETECTED')
1155 # Rerun detection to set the DETECTED mask plane on binnedExposure
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,
1163 axis=1)
1164 # Create new version of a diffim with DETECTED based on binnedExposure
1165 streakMaskedImage = maskedImage.clone()
1166 ysize, xsize = rescaledDetectedMaskPlane.shape
1167 streakMaskedImage.mask.array[:ysize, :xsize] |= rescaledDetectedMaskPlane
1168 # Detect streaks on this new version of the diffim
1169 streaks = self.maskStreaks.run(streakMaskedImage)
1170 streakMaskPlane = streakMaskedImage.mask.array & streakMaskedImage.mask.getPlaneBitMask('STREAK')
1171 # Apply the new STREAK mask to the original diffim
1172 maskedImage.mask.array |= streakMaskPlane
1173
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}
1182 else:
1183 streakInfo = {'rho': np.array([]), 'theta': np.array([]), 'sigma': np.array([]),
1184 'reducedChi2': np.array([]), 'modelMaximum': np.array([])}
1185 return pipeBase.Struct(maskedStreaks=streakInfo)
1186
1187
1188class DetectAndMeasureScoreConnections(DetectAndMeasureConnections):
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",
1194 )
1195
1196
1197class DetectAndMeasureScoreConfig(DetectAndMeasureConfig,
1198 pipelineConnections=DetectAndMeasureScoreConnections):
1199 pass
1200
1201
1202class DetectAndMeasureScoreTask(DetectAndMeasureTask):
1203 """Detect DIA sources using a score image,
1204 and measure the detections on the difference image.
1205
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
1209 dipole diaSources.
1210 Sky sources, or forced detections in background regions, will optionally
1211 be added, and the configured measurement algorithm will be run on all
1212 detections.
1213 """
1214 ConfigClass = DetectAndMeasureScoreConfig
1215 _DefaultName = "detectAndMeasureScore"
1216
1217 @timeMethod
1218 def run(self, science, matchedTemplate, difference, scoreExposure, kernelSources,
1219 idFactory=None):
1220 """Detect and measure sources on a score image.
1221
1222 Parameters
1223 ----------
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
1228 difference image.
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.
1239
1240 Returns
1241 -------
1242 measurementResults : `lsst.pipe.base.Struct`
1243
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.
1248 """
1249 if idFactory is None:
1250 idFactory = lsst.meas.base.IdGenerator().make_table_id_factory()
1251
1252 self._prepareInputs(scoreExposure)
1253
1254 # Don't use the idFactory until after deblend+merge, so that we aren't
1255 # generating ids that just get thrown away (footprint merge doesn't
1256 # know about past ids).
1257 table = afwTable.SourceTable.make(self.schema)
1258 results = self.detection.run(
1259 table=table,
1260 exposure=scoreExposure,
1261 doSmooth=False,
1262 )
1263 # Copy the detection mask from the Score image to the difference image
1264 difference.mask.assign(scoreExposure.mask, scoreExposure.getBBox())
1265
1266 if self.config.doDeblend:
1267 sources, positives, negatives = self._deblend(difference,
1268 results.positive,
1269 results.negative)
1270
1271 return self.processResults(science, matchedTemplate, difference,
1272 sources, idFactory, kernelSources,
1273 positives=positives,
1274 negatives=negatives)
1275
1276 else:
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)
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)