33import lsst.meas.extensions.trailedSources
34from lsst.meas.algorithms import (SourceDetectionTask, SingleGaussianPsf, ObjectSizeStarSelectorTask,
35 LoadIndexedReferenceObjectsTask, SkyObjectsTask,
40from lsst.ip.diffim import (DipoleAnalysis, SourceFlagChecker, KernelCandidateF, makeKernelBasisList,
41 KernelCandidateQa, DiaCatalogSourceSelectorTask, DiaCatalogSourceSelectorConfig,
42 GetCoaddAsTemplateTask, GetCalexpAsTemplateTask, DipoleFitTask,
43 DecorrelateALKernelSpatialTask, subtractAlgorithmRegistry)
48from lsst.obs.base
import ExposureIdInfo
49from lsst.utils.timer
import timeMethod
51from deprecated.sphinx
import deprecated
53__all__ = [
"ImageDifferenceConfig",
"ImageDifferenceTask"]
54FwhmPerSigma = 2*math.sqrt(2*math.log(2))
59 dimensions=(
"instrument",
"visit",
"detector",
"skymap"),
60 defaultTemplates={
"coaddName":
"deep",
65 exposure = pipeBase.connectionTypes.Input(
66 doc=
"Input science exposure to subtract from.",
67 dimensions=(
"instrument",
"visit",
"detector"),
68 storageClass=
"ExposureF",
69 name=
"{fakesType}calexp"
80 skyMap = pipeBase.connectionTypes.Input(
81 doc=
"Input definition of geometry/bbox and projection/wcs for template exposures",
82 name=BaseSkyMap.SKYMAP_DATASET_TYPE_NAME,
83 dimensions=(
"skymap", ),
84 storageClass=
"SkyMap",
86 coaddExposures = pipeBase.connectionTypes.Input(
87 doc=
"Input template to match and subtract from the exposure",
88 dimensions=(
"tract",
"patch",
"skymap",
"band"),
89 storageClass=
"ExposureF",
90 name=
"{fakesType}{coaddName}Coadd{warpTypeSuffix}",
94 dcrCoadds = pipeBase.connectionTypes.Input(
95 doc=
"Input DCR template to match and subtract from the exposure",
96 name=
"{fakesType}dcrCoadd{warpTypeSuffix}",
97 storageClass=
"ExposureF",
98 dimensions=(
"tract",
"patch",
"skymap",
"band",
"subfilter"),
102 finalizedPsfApCorrCatalog = pipeBase.connectionTypes.Input(
103 doc=(
"Per-visit finalized psf models and aperture correction maps. "
104 "These catalogs use the detector id for the catalog id, "
105 "sorted on id for fast lookup."),
106 name=
"finalized_psf_ap_corr_catalog",
107 storageClass=
"ExposureCatalog",
108 dimensions=(
"instrument",
"visit"),
110 outputSchema = pipeBase.connectionTypes.InitOutput(
111 doc=
"Schema (as an example catalog) for output DIASource catalog.",
112 storageClass=
"SourceCatalog",
113 name=
"{fakesType}{coaddName}Diff_diaSrc_schema",
115 subtractedExposure = pipeBase.connectionTypes.Output(
116 doc=
"Output AL difference or Zogy proper difference image",
117 dimensions=(
"instrument",
"visit",
"detector"),
118 storageClass=
"ExposureF",
119 name=
"{fakesType}{coaddName}Diff_differenceExp",
121 scoreExposure = pipeBase.connectionTypes.Output(
122 doc=
"Output AL likelihood or Zogy score image",
123 dimensions=(
"instrument",
"visit",
"detector"),
124 storageClass=
"ExposureF",
125 name=
"{fakesType}{coaddName}Diff_scoreExp",
127 warpedExposure = pipeBase.connectionTypes.Output(
128 doc=
"Warped template used to create `subtractedExposure`.",
129 dimensions=(
"instrument",
"visit",
"detector"),
130 storageClass=
"ExposureF",
131 name=
"{fakesType}{coaddName}Diff_warpedExp",
133 matchedExposure = pipeBase.connectionTypes.Output(
134 doc=
"Warped template used to create `subtractedExposure`.",
135 dimensions=(
"instrument",
"visit",
"detector"),
136 storageClass=
"ExposureF",
137 name=
"{fakesType}{coaddName}Diff_matchedExp",
139 diaSources = pipeBase.connectionTypes.Output(
140 doc=
"Output detected diaSources on the difference image",
141 dimensions=(
"instrument",
"visit",
"detector"),
142 storageClass=
"SourceCatalog",
143 name=
"{fakesType}{coaddName}Diff_diaSrc",
146 def __init__(self, *, config=None):
147 super().__init__(config=config)
148 if config.coaddName ==
'dcr':
149 self.inputs.remove(
"coaddExposures")
151 self.inputs.remove(
"dcrCoadds")
152 if not config.doWriteSubtractedExp:
153 self.outputs.remove(
"subtractedExposure")
154 if not config.doWriteScoreExp:
155 self.outputs.remove(
"scoreExposure")
156 if not config.doWriteWarpedExp:
157 self.outputs.remove(
"warpedExposure")
158 if not config.doWriteMatchedExp:
159 self.outputs.remove(
"matchedExposure")
160 if not config.doWriteSources:
161 self.outputs.remove(
"diaSources")
162 if not config.doApplyFinalizedPsf:
163 self.inputs.remove(
"finalizedPsfApCorrCatalog")
169class ImageDifferenceConfig(pipeBase.PipelineTaskConfig,
170 pipelineConnections=ImageDifferenceTaskConnections):
171 """Config for ImageDifferenceTask
173 doAddCalexpBackground = pexConfig.Field(dtype=bool, default=False,
174 doc=
"Add background to calexp before processing it. "
175 "Useful as ipDiffim does background matching.")
176 doUseRegister = pexConfig.Field(dtype=bool, default=
False,
177 doc=
"Re-compute astrometry on the template. "
178 "Use image-to-image registration to align template with "
179 "science image (AL only).")
180 doDebugRegister = pexConfig.Field(dtype=bool, default=
False,
181 doc=
"Writing debugging data for doUseRegister")
182 doSelectSources = pexConfig.Field(dtype=bool, default=
False,
183 doc=
"Select stars to use for kernel fitting (AL only)")
184 doSelectDcrCatalog = pexConfig.Field(dtype=bool, default=
False,
185 doc=
"Select stars of extreme color as part "
186 "of the control sample (AL only)")
187 doSelectVariableCatalog = pexConfig.Field(dtype=bool, default=
False,
188 doc=
"Select stars that are variable to be part "
189 "of the control sample (AL only)")
190 doSubtract = pexConfig.Field(dtype=bool, default=
True, doc=
"Compute subtracted exposure?")
191 doPreConvolve = pexConfig.Field(dtype=bool, default=
False,
192 doc=
"Not in use. Superseded by useScoreImageDetection.",
193 deprecated=
"This option superseded by useScoreImageDetection."
194 " Will be removed after v22.")
195 useScoreImageDetection = pexConfig.Field(
196 dtype=bool, default=
False, doc=
"Calculate the pre-convolved AL likelihood or "
197 "the Zogy score image. Use it for source detection (if doDetection=True).")
198 doWriteScoreExp = pexConfig.Field(
199 dtype=bool, default=
False, doc=
"Write AL likelihood or Zogy score exposure?")
200 doScaleTemplateVariance = pexConfig.Field(dtype=bool, default=
False,
201 doc=
"Scale variance of the template before PSF matching")
202 doScaleDiffimVariance = pexConfig.Field(dtype=bool, default=
True,
203 doc=
"Scale variance of the diffim before PSF matching. "
204 "You may do either this or template variance scaling, "
205 "or neither. (Doing both is a waste of CPU.)")
206 useGaussianForPreConvolution = pexConfig.Field(
207 dtype=bool, default=
False, doc=
"Use a simple gaussian PSF model for pre-convolution "
208 "(oherwise use exposure PSF)? (AL and if useScoreImageDetection=True only)")
209 doDetection = pexConfig.Field(dtype=bool, default=
True, doc=
"Detect sources?")
210 doDecorrelation = pexConfig.Field(dtype=bool, default=
True,
211 doc=
"Perform diffim decorrelation to undo pixel correlation due to A&L "
212 "kernel convolution (AL only)? If True, also update the diffim PSF.")
213 doMerge = pexConfig.Field(dtype=bool, default=
True,
214 doc=
"Merge positive and negative diaSources with grow radius "
215 "set by growFootprint")
216 doMatchSources = pexConfig.Field(dtype=bool, default=
False,
217 doc=
"Match diaSources with input calexp sources and ref catalog sources")
218 doMeasurement = pexConfig.Field(dtype=bool, default=
True, doc=
"Measure diaSources?")
219 doDipoleFitting = pexConfig.Field(dtype=bool, default=
True, doc=
"Measure dipoles using new algorithm?")
220 doForcedMeasurement = pexConfig.Field(
223 doc=
"Force photometer diaSource locations on PVI?")
224 doWriteSubtractedExp = pexConfig.Field(
225 dtype=bool, default=
True, doc=
"Write difference exposure (AL and Zogy) ?")
226 doWriteWarpedExp = pexConfig.Field(
227 dtype=bool, default=
False, doc=
"Write WCS, warped template coadd exposure?")
228 doWriteMatchedExp = pexConfig.Field(dtype=bool, default=
False,
229 doc=
"Write warped and PSF-matched template coadd exposure?")
230 doWriteSources = pexConfig.Field(dtype=bool, default=
True, doc=
"Write sources?")
231 doAddMetrics = pexConfig.Field(dtype=bool, default=
False,
232 doc=
"Add columns to the source table to hold analysis metrics?")
233 doApplyFinalizedPsf = pexConfig.Field(
234 doc=
"Whether to apply finalized psf models and aperture correction map.",
239 coaddName = pexConfig.Field(
240 doc=
"coadd name: typically one of deep, goodSeeing, or dcr",
244 convolveTemplate = pexConfig.Field(
245 doc=
"Which image gets convolved (default = template)",
249 refObjLoader = pexConfig.ConfigurableField(
250 target=LoadIndexedReferenceObjectsTask,
251 doc=
"reference object loader",
253 astrometer = pexConfig.ConfigurableField(
254 target=AstrometryTask,
255 doc=
"astrometry task; used to match sources to reference objects, but not to fit a WCS",
257 sourceSelector = pexConfig.ConfigurableField(
258 target=ObjectSizeStarSelectorTask,
259 doc=
"Source selection algorithm",
261 subtract = subtractAlgorithmRegistry.makeField(
"Subtraction Algorithm", default=
"al")
262 decorrelate = pexConfig.ConfigurableField(
263 target=DecorrelateALKernelSpatialTask,
264 doc=
"Decorrelate effects of A&L kernel convolution on image difference, only if doSubtract is True. "
265 "If this option is enabled, then detection.thresholdValue should be set to 5.0 (rather than the "
269 doSpatiallyVarying = pexConfig.Field(
272 doc=
"Perform A&L decorrelation on a grid across the "
273 "image in order to allow for spatial variations. Zogy does not use this option."
275 detection = pexConfig.ConfigurableField(
276 target=SourceDetectionTask,
277 doc=
"Low-threshold detection for final measurement",
279 measurement = pexConfig.ConfigurableField(
280 target=DipoleFitTask,
281 doc=
"Enable updated dipole fitting method",
283 doApCorr = lsst.pex.config.Field(
286 doc=
"Run subtask to apply aperture corrections"
288 applyApCorr = lsst.pex.config.ConfigurableField(
289 target=ApplyApCorrTask,
290 doc=
"Subtask to apply aperture corrections"
292 forcedMeasurement = pexConfig.ConfigurableField(
293 target=ForcedMeasurementTask,
294 doc=
"Subtask to force photometer PVI at diaSource location.",
296 getTemplate = pexConfig.ConfigurableField(
297 target=GetCoaddAsTemplateTask,
298 doc=
"Subtask to retrieve template exposure and sources",
300 scaleVariance = pexConfig.ConfigurableField(
301 target=ScaleVarianceTask,
302 doc=
"Subtask to rescale the variance of the template "
303 "to the statistically expected level"
305 controlStepSize = pexConfig.Field(
306 doc=
"What step size (every Nth one) to select a control sample from the kernelSources",
310 controlRandomSeed = pexConfig.Field(
311 doc=
"Random seed for shuffing the control sample",
315 register = pexConfig.ConfigurableField(
317 doc=
"Task to enable image-to-image image registration (warping)",
319 kernelSourcesFromRef = pexConfig.Field(
320 doc=
"Select sources to measure kernel from reference catalog if True, template if false",
324 templateSipOrder = pexConfig.Field(
325 dtype=int, default=2,
326 doc=
"Sip Order for fitting the Template Wcs (default is too high, overfitting)"
328 growFootprint = pexConfig.Field(
329 dtype=int, default=2,
330 doc=
"Grow positive and negative footprints by this amount before merging"
332 diaSourceMatchRadius = pexConfig.Field(
333 dtype=float, default=0.5,
334 doc=
"Match radius (in arcseconds) for DiaSource to Source association"
336 requiredTemplateFraction = pexConfig.Field(
337 dtype=float, default=0.1,
338 doc=
"Do not attempt to run task if template covers less than this fraction of pixels."
339 "Setting to 0 will always attempt image subtraction"
341 doSkySources = pexConfig.Field(
344 doc=
"Generate sky sources?",
346 skySources = pexConfig.ConfigurableField(
347 target=SkyObjectsTask,
348 doc=
"Generate sky sources",
351 def setDefaults(self):
354 self.subtract[
'al'].kernel.name =
"AL"
355 self.subtract[
'al'].kernel.active.fitForBackground =
True
356 self.subtract[
'al'].kernel.active.spatialKernelOrder = 1
357 self.subtract[
'al'].kernel.active.spatialBgOrder = 2
360 self.detection.thresholdPolarity =
"both"
361 self.detection.thresholdValue = 5.0
362 self.detection.reEstimateBackground =
False
363 self.detection.thresholdType =
"pixel_stdev"
369 self.measurement.algorithms.names.add(
'base_PeakLikelihoodFlux')
370 self.measurement.plugins.names |= [
'ext_trailedSources_Naive',
371 'base_LocalPhotoCalib',
374 self.forcedMeasurement.plugins = [
"base_TransformedCentroid",
"base_PsfFlux"]
375 self.forcedMeasurement.copyColumns = {
376 "id":
"objectId",
"parent":
"parentObjectId",
"coord_ra":
"coord_ra",
"coord_dec":
"coord_dec"}
377 self.forcedMeasurement.slots.centroid =
"base_TransformedCentroid"
378 self.forcedMeasurement.slots.shape =
None
381 random.seed(self.controlRandomSeed)
384 pexConfig.Config.validate(self)
385 if not self.doSubtract
and not self.doDetection:
386 raise ValueError(
"Either doSubtract or doDetection must be enabled.")
387 if self.doMeasurement
and not self.doDetection:
388 raise ValueError(
"Cannot run source measurement without source detection.")
389 if self.doMerge
and not self.doDetection:
390 raise ValueError(
"Cannot run source merging without source detection.")
391 if self.doSkySources
and not self.doDetection:
392 raise ValueError(
"Cannot run sky source creation without source detection.")
393 if self.doUseRegister
and not self.doSelectSources:
394 raise ValueError(
"doUseRegister=True and doSelectSources=False. "
395 "Cannot run RegisterTask without selecting sources.")
396 if self.doScaleDiffimVariance
and self.doScaleTemplateVariance:
397 raise ValueError(
"Scaling the diffim variance and scaling the template variance "
398 "are both set. Please choose one or the other.")
400 if self.subtract.name ==
'zogy':
401 if self.doWriteMatchedExp:
402 raise ValueError(
"doWriteMatchedExp=True Matched exposure is not "
403 "calculated in zogy subtraction.")
404 if self.doAddMetrics:
405 raise ValueError(
"doAddMetrics=True Kernel metrics does not exist in zogy subtraction.")
406 if self.doDecorrelation:
408 "doDecorrelation=True The decorrelation afterburner does not exist in zogy subtraction.")
409 if self.doSelectSources:
411 "doSelectSources=True Selecting sources for PSF matching is not a zogy option.")
412 if self.useGaussianForPreConvolution:
414 "useGaussianForPreConvolution=True This is an AL subtraction only option.")
417 if self.useScoreImageDetection
and not self.convolveTemplate:
419 "convolveTemplate=False and useScoreImageDetection=True "
420 "Pre-convolution and matching of the science image is not a supported operation.")
421 if self.doWriteSubtractedExp
and self.useScoreImageDetection:
423 "doWriteSubtractedExp=True and useScoreImageDetection=True "
424 "Regular difference image is not calculated. "
425 "AL subtraction calculates either the regular difference image or the score image.")
426 if self.doWriteScoreExp
and not self.useScoreImageDetection:
428 "doWriteScoreExp=True and useScoreImageDetection=False "
429 "Score image is not calculated. "
430 "AL subtraction calculates either the regular difference image or the score image.")
431 if self.doAddMetrics
and not self.doSubtract:
432 raise ValueError(
"Subtraction must be enabled for kernel metrics calculation.")
433 if self.useGaussianForPreConvolution
and not self.useScoreImageDetection:
435 "useGaussianForPreConvolution=True and useScoreImageDetection=False "
436 "Gaussian PSF approximation exists only for AL subtraction w/ pre-convolution.")
439class ImageDifferenceTaskRunner(pipeBase.ButlerInitializedTaskRunner):
442 def getTargetList(parsedCmd, **kwargs):
443 return pipeBase.TaskRunner.getTargetList(parsedCmd, templateIdList=parsedCmd.templateId.idList,
447@deprecated(reason=
"This Task has been replaced with lsst.ip.diffim.subtractImages"
448 " and lsst.ip.diffim.detectAndMeasure. Will be removed after v25.",
449 version=
"v24.0", category=FutureWarning)
450class ImageDifferenceTask(pipeBase.CmdLineTask, pipeBase.PipelineTask):
451 """Subtract an image from a template and measure the result
453 ConfigClass = ImageDifferenceConfig
454 RunnerClass = ImageDifferenceTaskRunner
455 _DefaultName = "imageDifference"
457 def __init__(self, butler=None, **kwargs):
458 """!Construct an ImageDifference Task
460 @param[
in] butler Butler object to use
in constructing reference object loaders
462 super().__init__(**kwargs)
463 self.makeSubtask("getTemplate")
465 self.makeSubtask(
"subtract")
467 if self.config.subtract.name ==
'al' and self.config.doDecorrelation:
468 self.makeSubtask(
"decorrelate")
470 if self.config.doScaleTemplateVariance
or self.config.doScaleDiffimVariance:
471 self.makeSubtask(
"scaleVariance")
473 if self.config.doUseRegister:
474 self.makeSubtask(
"register")
475 self.schema = afwTable.SourceTable.makeMinimalSchema()
477 if self.config.doSelectSources:
478 self.makeSubtask(
"sourceSelector")
479 if self.config.kernelSourcesFromRef:
480 self.makeSubtask(
'refObjLoader', butler=butler)
481 self.makeSubtask(
"astrometer", refObjLoader=self.refObjLoader)
483 self.algMetadata = dafBase.PropertyList()
484 if self.config.doDetection:
485 self.makeSubtask(
"detection", schema=self.schema)
486 if self.config.doMeasurement:
487 self.makeSubtask(
"measurement", schema=self.schema,
488 algMetadata=self.algMetadata)
489 if self.config.doApCorr:
490 self.makeSubtask(
"applyApCorr", schema=self.measurement.schema)
491 if self.config.doForcedMeasurement:
492 self.schema.addField(
493 "ip_diffim_forced_PsfFlux_instFlux",
"D",
494 "Forced PSF flux measured on the direct image.",
496 self.schema.addField(
497 "ip_diffim_forced_PsfFlux_instFluxErr",
"D",
498 "Forced PSF flux error measured on the direct image.",
500 self.schema.addField(
501 "ip_diffim_forced_PsfFlux_area",
"F",
502 "Forced PSF flux effective area of PSF.",
504 self.schema.addField(
505 "ip_diffim_forced_PsfFlux_flag",
"Flag",
506 "Forced PSF flux general failure flag.")
507 self.schema.addField(
508 "ip_diffim_forced_PsfFlux_flag_noGoodPixels",
"Flag",
509 "Forced PSF flux not enough non-rejected pixels in data to attempt the fit.")
510 self.schema.addField(
511 "ip_diffim_forced_PsfFlux_flag_edge",
"Flag",
512 "Forced PSF flux object was too close to the edge of the image to use the full PSF model.")
513 self.makeSubtask(
"forcedMeasurement", refSchema=self.schema)
514 if self.config.doMatchSources:
515 self.schema.addField(
"refMatchId",
"L",
"unique id of reference catalog match")
516 self.schema.addField(
"srcMatchId",
"L",
"unique id of source match")
517 if self.config.doSkySources:
518 self.makeSubtask(
"skySources")
519 self.skySourceKey = self.schema.addField(
"sky_source", type=
"Flag", doc=
"Sky objects.")
522 self.outputSchema = afwTable.SourceCatalog(self.schema)
523 self.outputSchema.getTable().setMetadata(self.algMetadata)
526 def makeIdFactory(expId, expBits):
527 """Create IdFactory instance for unique 64 bit diaSource id-s.
535 Number of used bits in ``expId``.
539 The diasource id-s consists of the ``expId`` stored fixed
in the highest value
540 ``expBits`` of the 64-bit integer plus (bitwise
or) a generated sequence number
in the
541 low value end of the integer.
547 return ExposureIdInfo(expId, expBits).makeSourceIdFactory()
549 @lsst.utils.inheritDoc(pipeBase.PipelineTask)
550 def runQuantum(self, butlerQC: pipeBase.ButlerQuantumContext,
551 inputRefs: pipeBase.InputQuantizedConnection,
552 outputRefs: pipeBase.OutputQuantizedConnection):
553 inputs = butlerQC.get(inputRefs)
554 self.log.info(
"Processing %s", butlerQC.quantum.dataId)
556 finalizedPsfApCorrCatalog = inputs.get(
"finalizedPsfApCorrCatalog",
None)
557 exposure = self.prepareCalibratedExposure(
559 finalizedPsfApCorrCatalog=finalizedPsfApCorrCatalog
562 expId, expBits = butlerQC.quantum.dataId.pack(
"visit_detector",
564 idFactory = self.makeIdFactory(expId=expId, expBits=expBits)
565 if self.config.coaddName ==
'dcr':
566 templateExposures = inputRefs.dcrCoadds
568 templateExposures = inputRefs.coaddExposures
569 templateStruct = self.getTemplate.runQuantum(
570 exposure, butlerQC, inputRefs.skyMap, templateExposures
573 self.checkTemplateIsSufficient(templateStruct.exposure)
575 outputs = self.run(exposure=exposure,
576 templateExposure=templateStruct.exposure,
579 if outputs.diaSources
is None:
580 del outputs.diaSources
581 butlerQC.put(outputs, outputRefs)
584 def runDataRef(self, sensorRef, templateIdList=None):
585 """Subtract an image from a template coadd and measure the result.
587 Data I/O wrapper around `run` using the butler in Gen2.
591 sensorRef : `lsst.daf.persistence.ButlerDataRef`
592 Sensor-level butler data reference, used
for the following data products:
599 - self.config.coaddName +
"Coadd_skyMap"
600 - self.config.coaddName +
"Coadd"
601 Input
or output, depending on config:
602 - self.config.coaddName +
"Diff_subtractedExp"
603 Output, depending on config:
604 - self.config.coaddName +
"Diff_matchedExp"
605 - self.config.coaddName +
"Diff_src"
609 results : `lsst.pipe.base.Struct`
610 Returns the Struct by `run`.
612 subtractedExposureName = self.config.coaddName + "Diff_differenceExp"
613 subtractedExposure =
None
615 calexpBackgroundExposure =
None
616 self.log.info(
"Processing %s", sensorRef.dataId)
621 idFactory = self.makeIdFactory(expId=int(sensorRef.get(
"ccdExposureId")),
622 expBits=sensorRef.get(
"ccdExposureId_bits"))
623 if self.config.doAddCalexpBackground:
624 calexpBackgroundExposure = sensorRef.get(
"calexpBackground")
627 exposure = sensorRef.get(
"calexp", immediate=
True)
630 template = self.getTemplate.runDataRef(exposure, sensorRef, templateIdList=templateIdList)
632 if sensorRef.datasetExists(
"src"):
633 self.log.info(
"Source selection via src product")
635 selectSources = sensorRef.get(
"src")
637 if not self.config.doSubtract
and self.config.doDetection:
639 subtractedExposure = sensorRef.get(subtractedExposureName)
642 results = self.run(exposure=exposure,
643 selectSources=selectSources,
644 templateExposure=template.exposure,
645 templateSources=template.sources,
647 calexpBackgroundExposure=calexpBackgroundExposure,
648 subtractedExposure=subtractedExposure)
650 if self.config.doWriteSources
and results.diaSources
is not None:
651 sensorRef.put(results.diaSources, self.config.coaddName +
"Diff_diaSrc")
652 if self.config.doWriteWarpedExp:
653 sensorRef.put(results.warpedExposure, self.config.coaddName +
"Diff_warpedExp")
654 if self.config.doWriteMatchedExp:
655 sensorRef.put(results.matchedExposure, self.config.coaddName +
"Diff_matchedExp")
656 if self.config.doAddMetrics
and self.config.doSelectSources:
657 sensorRef.put(results.selectSources, self.config.coaddName +
"Diff_kernelSrc")
658 if self.config.doWriteSubtractedExp:
659 sensorRef.put(results.subtractedExposure, subtractedExposureName)
660 if self.config.doWriteScoreExp:
661 sensorRef.put(results.scoreExposure, self.config.coaddName +
"Diff_scoreExp")
664 def prepareCalibratedExposure(self, exposure, finalizedPsfApCorrCatalog=None):
665 """Prepare a calibrated exposure and apply finalized psf if so configured.
669 exposure : `lsst.afw.image.exposure.Exposure`
670 Input exposure to adjust calibrations.
672 Exposure catalog with finalized psf models
and aperture correction
673 maps to be applied
if config.doApplyFinalizedPsf=
True. Catalog uses
674 the detector id
for the catalog id, sorted on id
for fast lookup.
678 exposure : `lsst.afw.image.exposure.Exposure`
679 Exposure
with adjusted calibrations.
681 detectorId = exposure.getInfo().getDetector().getId()
683 if finalizedPsfApCorrCatalog
is not None:
684 row = finalizedPsfApCorrCatalog.find(detectorId)
686 self.log.warning(
"Detector id %s not found in finalizedPsfApCorrCatalog; "
687 "Using original psf.", detectorId)
690 apCorrMap = row.getApCorrMap()
691 if psf
is None or apCorrMap
is None:
692 self.log.warning(
"Detector id %s has None for psf/apCorrMap in "
693 "finalizedPsfApCorrCatalog; Using original psf.", detectorId)
696 exposure.info.setApCorrMap(apCorrMap)
701 def run(self, exposure=None, selectSources=None, templateExposure=None, templateSources=None,
702 idFactory=None, calexpBackgroundExposure=None, subtractedExposure=None):
703 """PSF matches, subtract two images and perform detection on the difference image.
707 exposure : `lsst.afw.image.ExposureF`, optional
708 The science exposure, the minuend in the image subtraction.
709 Can be
None only
if ``config.doSubtract==
False``.
711 Identified sources on the science exposure. This catalog
is used to
712 select sources
in order to perform the AL PSF matching on stamp images
713 around them. The selection steps depend on config options
and whether
714 ``templateSources``
and ``matchingSources`` specified.
715 templateExposure : `lsst.afw.image.ExposureF`, optional
716 The template to be subtracted
from ``exposure``
in the image subtraction.
717 ``templateExposure``
is modified
in place
if ``config.doScaleTemplateVariance==
True``.
718 The template exposure should cover the same sky area
as the science exposure.
719 It
is either a stich of patches of a coadd skymap image
or a calexp
720 of the same pointing
as the science exposure. Can be
None only
721 if ``config.doSubtract==
False``
and ``subtractedExposure``
is not None.
723 Identified sources on the template exposure.
725 Generator object to assign ids to detected sources
in the difference image.
726 calexpBackgroundExposure : `lsst.afw.image.ExposureF`, optional
727 Background exposure to be added back to the science exposure
728 if ``config.doAddCalexpBackground==
True``
729 subtractedExposure : `lsst.afw.image.ExposureF`, optional
730 If ``config.doSubtract==
False``
and ``config.doDetection==
True``,
731 performs the post subtraction source detection only on this exposure.
732 Otherwise should be
None.
736 results : `lsst.pipe.base.Struct`
737 ``subtractedExposure`` : `lsst.afw.image.ExposureF`
739 ``scoreExposure`` : `lsst.afw.image.ExposureF`
or `
None`
740 The zogy score exposure,
if calculated.
741 ``matchedExposure`` : `lsst.afw.image.ExposureF`
742 The matched PSF exposure.
743 ``subtractRes`` : `lsst.pipe.base.Struct`
744 The returned result structure of the ImagePsfMatchTask subtask.
746 The catalog of detected sources.
748 The input source catalog
with optionally added Qa information.
752 The following major steps are included:
754 - warp template coadd to match WCS of image
755 - PSF match image to warped template
756 - subtract image
from PSF-matched, warped template
760 For details about the image subtraction configuration modes
764 controlSources =
None
765 subtractedExposure =
None
770 exposureOrig = exposure
772 if self.config.doAddCalexpBackground:
773 mi = exposure.getMaskedImage()
774 mi += calexpBackgroundExposure.getImage()
776 if not exposure.hasPsf():
777 raise pipeBase.TaskError(
"Exposure has no psf")
778 sciencePsf = exposure.getPsf()
780 if self.config.doSubtract:
781 if self.config.doScaleTemplateVariance:
782 self.log.info(
"Rescaling template variance")
783 templateVarFactor = self.scaleVariance.run(
784 templateExposure.getMaskedImage())
785 self.log.info(
"Template variance scaling factor: %.2f", templateVarFactor)
786 self.metadata.add(
"scaleTemplateVarianceFactor", templateVarFactor)
787 self.metadata.add(
"psfMatchingAlgorithm", self.config.subtract.name)
789 if self.config.subtract.name ==
'zogy':
790 subtractRes = self.subtract.run(exposure, templateExposure, doWarping=
True)
791 scoreExposure = subtractRes.scoreExp
792 subtractedExposure = subtractRes.diffExp
793 subtractRes.subtractedExposure = subtractedExposure
794 subtractRes.matchedExposure =
None
796 elif self.config.subtract.name ==
'al':
799 sciAvgPos = sciencePsf.getAveragePosition()
800 scienceSigmaOrig = sciencePsf.computeShape(sciAvgPos).getDeterminantRadius()
802 templatePsf = templateExposure.getPsf()
803 templateAvgPos = templatePsf.getAveragePosition()
804 templateSigma = templatePsf.computeShape(templateAvgPos).getDeterminantRadius()
812 if self.config.useScoreImageDetection:
813 self.log.warning(
"AL likelihood image: pre-convolution of PSF is not implemented.")
814 convControl = afwMath.ConvolutionControl()
816 srcMI = exposure.maskedImage
817 exposure = exposure.clone()
819 if self.config.useGaussianForPreConvolution:
821 "AL likelihood image: Using Gaussian (sigma=%.2f) PSF estimation "
822 "for science image pre-convolution", scienceSigmaOrig)
824 kWidth, kHeight = sciencePsf.getLocalKernel().getDimensions()
829 "AL likelihood image: Using the science image PSF for pre-convolution.")
831 afwMath.convolve(exposure.maskedImage, srcMI, preConvPsf.getLocalKernel(), convControl)
832 scienceSigmaPost = scienceSigmaOrig*math.sqrt(2)
834 scienceSigmaPost = scienceSigmaOrig
839 if self.config.doSelectSources:
840 if selectSources
is None:
841 self.log.warning(
"Src product does not exist; running detection, measurement,"
844 selectSources = self.subtract.getSelectSources(
846 sigma=scienceSigmaPost,
847 doSmooth=
not self.config.useScoreImageDetection,
851 if self.config.doAddMetrics:
854 nparam = len(makeKernelBasisList(self.subtract.config.kernel.active,
855 referenceFwhmPix=scienceSigmaPost*FwhmPerSigma,
856 targetFwhmPix=templateSigma*FwhmPerSigma))
863 kcQa = KernelCandidateQa(nparam)
864 selectSources = kcQa.addToSchema(selectSources)
865 if self.config.kernelSourcesFromRef:
867 astromRet = self.astrometer.loadAndMatch(exposure=exposure, sourceCat=selectSources)
868 matches = astromRet.matches
869 elif templateSources:
871 mc = afwTable.MatchControl()
872 mc.findOnlyClosest =
False
873 matches = afwTable.matchRaDec(templateSources, selectSources, 1.0*geom.arcseconds,
876 raise RuntimeError(
"doSelectSources=True and kernelSourcesFromRef=False,"
877 "but template sources not available. Cannot match science "
878 "sources with template sources. Run process* on data from "
879 "which templates are built.")
881 kernelSources = self.sourceSelector.run(selectSources, exposure=exposure,
882 matches=matches).sourceCat
883 random.shuffle(kernelSources, random.random)
884 controlSources = kernelSources[::self.config.controlStepSize]
885 kernelSources = [k
for i, k
in enumerate(kernelSources)
886 if i % self.config.controlStepSize]
888 if self.config.doSelectDcrCatalog:
889 redSelector = DiaCatalogSourceSelectorTask(
890 DiaCatalogSourceSelectorConfig(grMin=self.sourceSelector.config.grMax,
892 redSources = redSelector.selectStars(exposure, selectSources, matches=matches).starCat
893 controlSources.extend(redSources)
895 blueSelector = DiaCatalogSourceSelectorTask(
896 DiaCatalogSourceSelectorConfig(grMin=-99.999,
897 grMax=self.sourceSelector.config.grMin))
898 blueSources = blueSelector.selectStars(exposure, selectSources,
899 matches=matches).starCat
900 controlSources.extend(blueSources)
902 if self.config.doSelectVariableCatalog:
903 varSelector = DiaCatalogSourceSelectorTask(
904 DiaCatalogSourceSelectorConfig(includeVariable=
True))
905 varSources = varSelector.selectStars(exposure, selectSources, matches=matches).starCat
906 controlSources.extend(varSources)
908 self.log.info(
"Selected %d / %d sources for Psf matching (%d for control sample)",
909 len(kernelSources), len(selectSources), len(controlSources))
913 if self.config.doUseRegister:
914 self.log.info(
"Registering images")
916 if templateSources
is None:
920 templateSources = self.subtract.getSelectSources(
929 wcsResults = self.fitAstrometry(templateSources, templateExposure, selectSources)
930 warpedExp = self.register.warpExposure(templateExposure, wcsResults.wcs,
931 exposure.getWcs(), exposure.getBBox())
932 templateExposure = warpedExp
937 if self.config.doDebugRegister:
939 srcToMatch = {x.second.getId(): x.first
for x
in matches}
941 refCoordKey = wcsResults.matches[0].first.getTable().getCoordKey()
942 inCentroidKey = wcsResults.matches[0].second.getTable().getCentroidSlot().getMeasKey()
943 sids = [m.first.getId()
for m
in wcsResults.matches]
944 positions = [m.first.get(refCoordKey)
for m
in wcsResults.matches]
945 residuals = [m.first.get(refCoordKey).getOffsetFrom(wcsResults.wcs.pixelToSky(
946 m.second.get(inCentroidKey)))
for m
in wcsResults.matches]
947 allresids = dict(zip(sids, zip(positions, residuals)))
949 cresiduals = [m.first.get(refCoordKey).getTangentPlaneOffset(
950 wcsResults.wcs.pixelToSky(
951 m.second.get(inCentroidKey)))
for m
in wcsResults.matches]
952 colors = numpy.array([-2.5*numpy.log10(srcToMatch[x].get(
"g"))
953 + 2.5*numpy.log10(srcToMatch[x].get(
"r"))
954 for x
in sids
if x
in srcToMatch.keys()])
955 dlong = numpy.array([r[0].asArcseconds()
for s, r
in zip(sids, cresiduals)
956 if s
in srcToMatch.keys()])
957 dlat = numpy.array([r[1].asArcseconds()
for s, r
in zip(sids, cresiduals)
958 if s
in srcToMatch.keys()])
959 idx1 = numpy.where(colors < self.sourceSelector.config.grMin)
960 idx2 = numpy.where((colors >= self.sourceSelector.config.grMin)
961 & (colors <= self.sourceSelector.config.grMax))
962 idx3 = numpy.where(colors > self.sourceSelector.config.grMax)
963 rms1Long = IqrToSigma*(
964 (numpy.percentile(dlong[idx1], 75) - numpy.percentile(dlong[idx1], 25)))
965 rms1Lat = IqrToSigma*(numpy.percentile(dlat[idx1], 75)
966 - numpy.percentile(dlat[idx1], 25))
967 rms2Long = IqrToSigma*(
968 (numpy.percentile(dlong[idx2], 75) - numpy.percentile(dlong[idx2], 25)))
969 rms2Lat = IqrToSigma*(numpy.percentile(dlat[idx2], 75)
970 - numpy.percentile(dlat[idx2], 25))
971 rms3Long = IqrToSigma*(
972 (numpy.percentile(dlong[idx3], 75) - numpy.percentile(dlong[idx3], 25)))
973 rms3Lat = IqrToSigma*(numpy.percentile(dlat[idx3], 75)
974 - numpy.percentile(dlat[idx3], 25))
975 self.log.info(
"Blue star offsets'': %.3f %.3f, %.3f %.3f",
976 numpy.median(dlong[idx1]), rms1Long,
977 numpy.median(dlat[idx1]), rms1Lat)
978 self.log.info(
"Green star offsets'': %.3f %.3f, %.3f %.3f",
979 numpy.median(dlong[idx2]), rms2Long,
980 numpy.median(dlat[idx2]), rms2Lat)
981 self.log.info(
"Red star offsets'': %.3f %.3f, %.3f %.3f",
982 numpy.median(dlong[idx3]), rms3Long,
983 numpy.median(dlat[idx3]), rms3Lat)
985 self.metadata.add(
"RegisterBlueLongOffsetMedian", numpy.median(dlong[idx1]))
986 self.metadata.add(
"RegisterGreenLongOffsetMedian", numpy.median(dlong[idx2]))
987 self.metadata.add(
"RegisterRedLongOffsetMedian", numpy.median(dlong[idx3]))
988 self.metadata.add(
"RegisterBlueLongOffsetStd", rms1Long)
989 self.metadata.add(
"RegisterGreenLongOffsetStd", rms2Long)
990 self.metadata.add(
"RegisterRedLongOffsetStd", rms3Long)
992 self.metadata.add(
"RegisterBlueLatOffsetMedian", numpy.median(dlat[idx1]))
993 self.metadata.add(
"RegisterGreenLatOffsetMedian", numpy.median(dlat[idx2]))
994 self.metadata.add(
"RegisterRedLatOffsetMedian", numpy.median(dlat[idx3]))
995 self.metadata.add(
"RegisterBlueLatOffsetStd", rms1Lat)
996 self.metadata.add(
"RegisterGreenLatOffsetStd", rms2Lat)
997 self.metadata.add(
"RegisterRedLatOffsetStd", rms3Lat)
1004 self.log.info(
"Subtracting images")
1005 subtractRes = self.subtract.subtractExposures(
1006 templateExposure=templateExposure,
1007 scienceExposure=exposure,
1008 candidateList=kernelSources,
1009 convolveTemplate=self.config.convolveTemplate,
1010 doWarping=
not self.config.doUseRegister
1012 if self.config.useScoreImageDetection:
1013 scoreExposure = subtractRes.subtractedExposure
1015 subtractedExposure = subtractRes.subtractedExposure
1017 if self.config.doDetection:
1018 self.log.info(
"Computing diffim PSF")
1021 if subtractedExposure
is not None and not subtractedExposure.hasPsf():
1022 if self.config.convolveTemplate:
1023 subtractedExposure.setPsf(exposure.getPsf())
1025 subtractedExposure.setPsf(templateExposure.getPsf())
1032 if self.config.doDecorrelation
and self.config.doSubtract:
1033 preConvKernel =
None
1034 if self.config.useGaussianForPreConvolution:
1035 preConvKernel = preConvPsf.getLocalKernel()
1036 if self.config.useScoreImageDetection:
1037 scoreExposure = self.decorrelate.run(exposureOrig, subtractRes.warpedExposure,
1039 subtractRes.psfMatchingKernel,
1040 spatiallyVarying=self.config.doSpatiallyVarying,
1041 preConvKernel=preConvKernel,
1042 templateMatched=
True,
1043 preConvMode=
True).correctedExposure
1046 subtractedExposure = self.decorrelate.run(exposureOrig, subtractRes.warpedExposure,
1048 subtractRes.psfMatchingKernel,
1049 spatiallyVarying=self.config.doSpatiallyVarying,
1051 templateMatched=self.config.convolveTemplate,
1052 preConvMode=
False).correctedExposure
1055 if self.config.doDetection:
1056 self.log.info(
"Running diaSource detection")
1064 if self.config.useScoreImageDetection:
1066 self.log.info(
"Detection, diffim rescaling and measurements are "
1067 "on AL likelihood or Zogy score image.")
1068 detectionExposure = scoreExposure
1071 detectionExposure = subtractedExposure
1074 if self.config.doScaleDiffimVariance:
1075 self.log.info(
"Rescaling diffim variance")
1076 diffimVarFactor = self.scaleVariance.run(detectionExposure.getMaskedImage())
1077 self.log.info(
"Diffim variance scaling factor: %.2f", diffimVarFactor)
1078 self.metadata.add(
"scaleDiffimVarianceFactor", diffimVarFactor)
1081 mask = detectionExposure.getMaskedImage().getMask()
1082 mask &= ~(mask.getPlaneBitMask(
"DETECTED") | mask.getPlaneBitMask(
"DETECTED_NEGATIVE"))
1084 table = afwTable.SourceTable.make(self.schema, idFactory)
1085 table.setMetadata(self.algMetadata)
1086 results = self.detection.run(
1088 exposure=detectionExposure,
1089 doSmooth=
not self.config.useScoreImageDetection
1092 if self.config.doMerge:
1093 fpSet = results.fpSets.positive
1094 fpSet.merge(results.fpSets.negative, self.config.growFootprint,
1095 self.config.growFootprint,
False)
1096 diaSources = afwTable.SourceCatalog(table)
1097 fpSet.makeSources(diaSources)
1098 self.log.info(
"Merging detections into %d sources", len(diaSources))
1100 diaSources = results.sources
1102 if self.config.doSkySources:
1103 skySourceFootprints = self.skySources.run(
1104 mask=detectionExposure.mask,
1105 seed=detectionExposure.info.id)
1106 if skySourceFootprints:
1107 for foot
in skySourceFootprints:
1108 s = diaSources.addNew()
1109 s.setFootprint(foot)
1110 s.set(self.skySourceKey,
True)
1112 if self.config.doMeasurement:
1113 newDipoleFitting = self.config.doDipoleFitting
1114 self.log.info(
"Running diaSource measurement: newDipoleFitting=%r", newDipoleFitting)
1115 if not newDipoleFitting:
1117 self.measurement.run(diaSources, detectionExposure)
1120 if self.config.doSubtract
and 'matchedExposure' in subtractRes.getDict():
1121 self.measurement.run(diaSources, detectionExposure, exposure,
1122 subtractRes.matchedExposure)
1124 self.measurement.run(diaSources, detectionExposure, exposure)
1125 if self.config.doApCorr:
1126 self.applyApCorr.run(
1128 apCorrMap=detectionExposure.getInfo().getApCorrMap()
1131 if self.config.doForcedMeasurement:
1134 forcedSources = self.forcedMeasurement.generateMeasCat(
1135 exposure, diaSources, detectionExposure.getWcs())
1136 self.forcedMeasurement.run(forcedSources, exposure, diaSources, detectionExposure.getWcs())
1137 mapper = afwTable.SchemaMapper(forcedSources.schema, diaSources.schema)
1138 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_instFlux")[0],
1139 "ip_diffim_forced_PsfFlux_instFlux",
True)
1140 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_instFluxErr")[0],
1141 "ip_diffim_forced_PsfFlux_instFluxErr",
True)
1142 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_area")[0],
1143 "ip_diffim_forced_PsfFlux_area",
True)
1144 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag")[0],
1145 "ip_diffim_forced_PsfFlux_flag",
True)
1146 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag_noGoodPixels")[0],
1147 "ip_diffim_forced_PsfFlux_flag_noGoodPixels",
True)
1148 mapper.addMapping(forcedSources.schema.find(
"base_PsfFlux_flag_edge")[0],
1149 "ip_diffim_forced_PsfFlux_flag_edge",
True)
1150 for diaSource, forcedSource
in zip(diaSources, forcedSources):
1151 diaSource.assign(forcedSource, mapper)
1154 if self.config.doMatchSources:
1155 if selectSources
is not None:
1157 matchRadAsec = self.config.diaSourceMatchRadius
1158 matchRadPixel = matchRadAsec/exposure.getWcs().getPixelScale().asArcseconds()
1160 srcMatches = afwTable.matchXy(selectSources, diaSources, matchRadPixel)
1161 srcMatchDict = dict([(srcMatch.second.getId(), srcMatch.first.getId())
for
1162 srcMatch
in srcMatches])
1163 self.log.info(
"Matched %d / %d diaSources to sources",
1164 len(srcMatchDict), len(diaSources))
1166 self.log.warning(
"Src product does not exist; cannot match with diaSources")
1170 refAstromConfig = AstrometryConfig()
1171 refAstromConfig.matcher.maxMatchDistArcSec = matchRadAsec
1172 refAstrometer = AstrometryTask(self.refObjLoader, config=refAstromConfig)
1173 astromRet = refAstrometer.run(exposure=exposure, sourceCat=diaSources)
1174 refMatches = astromRet.matches
1175 if refMatches
is None:
1176 self.log.warning(
"No diaSource matches with reference catalog")
1179 self.log.info(
"Matched %d / %d diaSources to reference catalog",
1180 len(refMatches), len(diaSources))
1181 refMatchDict = dict([(refMatch.second.getId(), refMatch.first.getId())
for
1182 refMatch
in refMatches])
1185 for diaSource
in diaSources:
1186 sid = diaSource.getId()
1187 if sid
in srcMatchDict:
1188 diaSource.set(
"srcMatchId", srcMatchDict[sid])
1189 if sid
in refMatchDict:
1190 diaSource.set(
"refMatchId", refMatchDict[sid])
1192 if self.config.doAddMetrics
and self.config.doSelectSources:
1193 self.log.info(
"Evaluating metrics and control sample")
1196 for cell
in subtractRes.kernelCellSet.getCellList():
1197 for cand
in cell.begin(
False):
1198 kernelCandList.append(cand)
1201 basisList = kernelCandList[0].getKernel(KernelCandidateF.ORIG).getKernelList()
1202 nparam = len(kernelCandList[0].getKernel(KernelCandidateF.ORIG).getKernelParameters())
1205 diffimTools.sourceTableToCandidateList(controlSources,
1206 subtractRes.warpedExposure, exposure,
1207 self.config.subtract.kernel.active,
1208 self.config.subtract.kernel.active.detectionConfig,
1209 self.log, doBuild=
True, basisList=basisList))
1211 KernelCandidateQa.apply(kernelCandList, subtractRes.psfMatchingKernel,
1212 subtractRes.backgroundModel, dof=nparam)
1213 KernelCandidateQa.apply(controlCandList, subtractRes.psfMatchingKernel,
1214 subtractRes.backgroundModel)
1216 if self.config.doDetection:
1217 KernelCandidateQa.aggregate(selectSources, self.metadata, allresids, diaSources)
1219 KernelCandidateQa.aggregate(selectSources, self.metadata, allresids)
1221 self.runDebug(exposure, subtractRes, selectSources, kernelSources, diaSources)
1222 return pipeBase.Struct(
1223 subtractedExposure=subtractedExposure,
1224 scoreExposure=scoreExposure,
1225 warpedExposure=subtractRes.warpedExposure,
1226 matchedExposure=subtractRes.matchedExposure,
1227 subtractRes=subtractRes,
1228 diaSources=diaSources,
1229 selectSources=selectSources
1232 def fitAstrometry(self, templateSources, templateExposure, selectSources):
1233 """Fit the relative astrometry between templateSources and selectSources
1238 Remove this method. It originally fit a new WCS to the template before calling register.run
1239 because our TAN-SIP fitter behaved badly for points far
from CRPIX, but that
's been fixed.
1240 It remains because a subtask overrides it.
1242 results = self.register.run(templateSources, templateExposure.getWcs(),
1243 templateExposure.getBBox(), selectSources)
1246 def runDebug(self, exposure, subtractRes, selectSources, kernelSources, diaSources):
1247 """Make debug plots and displays.
1251 Test and update
for current debug display
and slot names
1261 disp = afwDisplay.getDisplay(frame=lsstDebug.frame)
1262 if not maskTransparency:
1263 maskTransparency = 0
1264 disp.setMaskTransparency(maskTransparency)
1266 if display
and showSubtracted:
1267 disp.mtv(subtractRes.subtractedExposure, title=
"Subtracted image")
1268 mi = subtractRes.subtractedExposure.getMaskedImage()
1269 x0, y0 = mi.getX0(), mi.getY0()
1270 with disp.Buffering():
1271 for s
in diaSources:
1272 x, y = s.getX() - x0, s.getY() - y0
1273 ctype =
"red" if s.get(
"flags_negative")
else "yellow"
1274 if (s.get(
"base_PixelFlags_flag_interpolatedCenter")
1275 or s.get(
"base_PixelFlags_flag_saturatedCenter")
1276 or s.get(
"base_PixelFlags_flag_crCenter")):
1278 elif (s.get(
"base_PixelFlags_flag_interpolated")
1279 or s.get(
"base_PixelFlags_flag_saturated")
1280 or s.get(
"base_PixelFlags_flag_cr")):
1284 disp.dot(ptype, x, y, size=4, ctype=ctype)
1285 lsstDebug.frame += 1
1287 if display
and showPixelResiduals
and selectSources:
1288 nonKernelSources = []
1289 for source
in selectSources:
1290 if source
not in kernelSources:
1291 nonKernelSources.append(source)
1293 diUtils.plotPixelResiduals(exposure,
1294 subtractRes.warpedExposure,
1295 subtractRes.subtractedExposure,
1296 subtractRes.kernelCellSet,
1297 subtractRes.psfMatchingKernel,
1298 subtractRes.backgroundModel,
1300 self.subtract.config.kernel.active.detectionConfig,
1302 diUtils.plotPixelResiduals(exposure,
1303 subtractRes.warpedExposure,
1304 subtractRes.subtractedExposure,
1305 subtractRes.kernelCellSet,
1306 subtractRes.psfMatchingKernel,
1307 subtractRes.backgroundModel,
1309 self.subtract.config.kernel.active.detectionConfig,
1311 if display
and showDiaSources:
1312 flagChecker = SourceFlagChecker(diaSources)
1313 isFlagged = [flagChecker(x)
for x
in diaSources]
1314 isDipole = [x.get(
"ip_diffim_ClassificationDipole_value")
for x
in diaSources]
1315 diUtils.showDiaSources(diaSources, subtractRes.subtractedExposure, isFlagged, isDipole,
1316 frame=lsstDebug.frame)
1317 lsstDebug.frame += 1
1319 if display
and showDipoles:
1320 DipoleAnalysis().displayDipoles(subtractRes.subtractedExposure, diaSources,
1321 frame=lsstDebug.frame)
1322 lsstDebug.frame += 1
1324 def checkTemplateIsSufficient(self, templateExposure):
1325 """Raise NoWorkFound if template coverage < requiredTemplateFraction
1329 templateExposure : `lsst.afw.image.ExposureF`
1330 The template exposure to check
1335 Raised if fraction of good pixels, defined
as not having NO_DATA
1336 set,
is less then the configured requiredTemplateFraction
1340 pixNoData = numpy.count_nonzero(templateExposure.mask.array
1341 & templateExposure.mask.getPlaneBitMask(
'NO_DATA'))
1342 pixGood = templateExposure.getBBox().getArea() - pixNoData
1343 self.log.info(
"template has %d good pixels (%.1f%%)", pixGood,
1344 100*pixGood/templateExposure.getBBox().getArea())
1346 if pixGood/templateExposure.getBBox().getArea() < self.config.requiredTemplateFraction:
1347 message = (
"Insufficient Template Coverage. (%.1f%% < %.1f%%) Not attempting subtraction. "
1348 "To force subtraction, set config requiredTemplateFraction=0." % (
1349 100*pixGood/templateExposure.getBBox().getArea(),
1350 100*self.config.requiredTemplateFraction))
1351 raise pipeBase.NoWorkFound(message)
1353 def _getConfigName(self):
1354 """Return the name of the config dataset
1356 return "%sDiff_config" % (self.config.coaddName,)
1358 def _getMetadataName(self):
1359 """Return the name of the metadata dataset
1361 return "%sDiff_metadata" % (self.config.coaddName,)
1363 def getSchemaCatalogs(self):
1364 """Return a dict of empty catalogs for each catalog dataset produced by this task."""
1365 return {self.config.coaddName +
"Diff_diaSrc": self.outputSchema}
1368 def _makeArgumentParser(cls):
1369 """Create an argument parser
1371 parser = pipeBase.ArgumentParser(name=cls._DefaultName)
1372 parser.add_id_argument("--id",
"calexp", help=
"data ID, e.g. --id visit=12345 ccd=1,2")
1373 parser.add_id_argument(
"--templateId",
"calexp", doMakeDataRefList=
True,
1374 help=
"Template data ID in case of calexp template,"
1375 " e.g. --templateId visit=6789")
1380 defaultTemplates={
"coaddName":
"goodSeeing"}
1382 inputTemplate = pipeBase.connectionTypes.Input(
1383 doc=(
"Warped template produced by GetMultiTractCoaddTemplate"),
1384 dimensions=(
"instrument",
"visit",
"detector"),
1385 storageClass=
"ExposureF",
1386 name=
"{fakesType}{coaddName}Diff_templateExp{warpTypeSuffix}",
1389 def __init__(self, *, config=None):
1390 super().__init__(config=config)
1393 if "coaddExposures" in self.inputs:
1394 self.inputs.remove(
"coaddExposures")
1395 if "dcrCoadds" in self.inputs:
1396 self.inputs.remove(
"dcrCoadds")
1400 pipelineConnections=ImageDifferenceFromTemplateConnections):
1405 ConfigClass = ImageDifferenceFromTemplateConfig
1406 _DefaultName =
"imageDifference"
1408 @lsst.utils.inheritDoc(pipeBase.PipelineTask)
1410 inputs = butlerQC.get(inputRefs)
1411 self.log.info(
"Processing %s", butlerQC.quantum.dataId)
1412 self.checkTemplateIsSufficient(inputs[
'inputTemplate'])
1413 expId, expBits = butlerQC.quantum.dataId.pack(
"visit_detector",
1415 idFactory = self.makeIdFactory(expId=expId, expBits=expBits)
1417 finalizedPsfApCorrCatalog = inputs.get(
"finalizedPsfApCorrCatalog",
None)
1418 exposure = self.prepareCalibratedExposure(
1420 finalizedPsfApCorrCatalog=finalizedPsfApCorrCatalog
1423 outputs = self.run(exposure=exposure,
1424 templateExposure=inputs[
'inputTemplate'],
1425 idFactory=idFactory)
1428 if outputs.diaSources
is None:
1429 del outputs.diaSources
1430 butlerQC.put(outputs, outputRefs)
1434 winter2013WcsShift = pexConfig.Field(dtype=float, default=0.0,
1435 doc=
"Shift stars going into RegisterTask by this amount")
1436 winter2013WcsRms = pexConfig.Field(dtype=float, default=0.0,
1437 doc=
"Perturb stars going into RegisterTask by this amount")
1440 ImageDifferenceConfig.setDefaults(self)
1441 self.getTemplate.retarget(GetCalexpAsTemplateTask)
1445 """!Image difference Task used in the Winter 2013 data challege.
1446 Enables testing the effects of registration shifts and scatter.
1448 For use
with winter 2013 simulated images:
1449 Use --templateId visit=88868666
for sparse data
1450 --templateId visit=22222200
for dense data (g)
1451 --templateId visit=11111100
for dense data (i)
1453 ConfigClass = Winter2013ImageDifferenceConfig
1454 _DefaultName = "winter2013ImageDifference"
1457 ImageDifferenceTask.__init__(self, **kwargs)
1460 """Fit the relative astrometry between templateSources and selectSources"""
1461 if self.config.winter2013WcsShift > 0.0:
1463 self.config.winter2013WcsShift)
1464 cKey = templateSources[0].getTable().getCentroidSlot().getMeasKey()
1465 for source
in templateSources:
1466 centroid = source.get(cKey)
1467 source.set(cKey, centroid + offset)
1468 elif self.config.winter2013WcsRms > 0.0:
1469 cKey = templateSources[0].getTable().getCentroidSlot().getMeasKey()
1470 for source
in templateSources:
1471 offset =
geom.Extent2D(self.config.winter2013WcsRms*numpy.random.normal(),
1472 self.config.winter2013WcsRms*numpy.random.normal())
1473 centroid = source.get(cKey)
1474 source.set(cKey, centroid + offset)
1476 results = self.register.run(templateSources, templateExposure.getWcs(),
1477 templateExposure.getBBox(), selectSources)
def runQuantum(self, butlerQC, inputRefs, outputRefs)
Image difference Task used in the Winter 2013 data challege.
def __init__(self, **kwargs)
def fitAstrometry(self, templateSources, templateExposure, selectSources)