lsst.pipe.tasks  21.0.0-121-gecf9ee78+b64c36337a
imageDifference.py
Go to the documentation of this file.
1 # This file is part of pipe_tasks.
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 
22 import math
23 import random
24 import numpy
25 
26 import lsst.utils
27 import lsst.pex.config as pexConfig
28 import lsst.pipe.base as pipeBase
29 import lsst.daf.base as dafBase
30 import lsst.geom as geom
31 import lsst.afw.math as afwMath
32 import lsst.afw.table as afwTable
33 from lsst.meas.astrom import AstrometryConfig, AstrometryTask
34 from lsst.meas.base import ForcedMeasurementTask, ApplyApCorrTask
35 from lsst.meas.algorithms import LoadIndexedReferenceObjectsTask, SkyObjectsTask
36 from lsst.pipe.tasks.registerImage import RegisterTask
37 from lsst.pipe.tasks.scaleVariance import ScaleVarianceTask
38 from lsst.meas.algorithms import SourceDetectionTask, SingleGaussianPsf, ObjectSizeStarSelectorTask
39 from lsst.ip.diffim import (DipoleAnalysis, SourceFlagChecker, KernelCandidateF, makeKernelBasisList,
40  KernelCandidateQa, DiaCatalogSourceSelectorTask, DiaCatalogSourceSelectorConfig,
41  GetCoaddAsTemplateTask, GetCalexpAsTemplateTask, DipoleFitTask,
42  DecorrelateALKernelSpatialTask, subtractAlgorithmRegistry)
43 import lsst.ip.diffim.diffimTools as diffimTools
44 import lsst.ip.diffim.utils as diUtils
45 import lsst.afw.display as afwDisplay
46 from lsst.skymap import BaseSkyMap
47 from lsst.obs.base import ExposureIdInfo
48 
49 __all__ = ["ImageDifferenceConfig", "ImageDifferenceTask"]
50 FwhmPerSigma = 2*math.sqrt(2*math.log(2))
51 IqrToSigma = 0.741
52 
53 
54 class ImageDifferenceTaskConnections(pipeBase.PipelineTaskConnections,
55  dimensions=("instrument", "visit", "detector", "skymap"),
56  defaultTemplates={"coaddName": "deep",
57  "skyMapName": "deep",
58  "warpTypeSuffix": "",
59  "fakesType": ""}):
60 
61  exposure = pipeBase.connectionTypes.Input(
62  doc="Input science exposure to subtract from.",
63  dimensions=("instrument", "visit", "detector"),
64  storageClass="ExposureF",
65  name="{fakesType}calexp"
66  )
67 
68  # TODO DM-22953
69  # kernelSources = pipeBase.connectionTypes.Input(
70  # doc="Source catalog produced in calibrate task for kernel candidate sources",
71  # name="src",
72  # storageClass="SourceCatalog",
73  # dimensions=("instrument", "visit", "detector"),
74  # )
75 
76  skyMap = pipeBase.connectionTypes.Input(
77  doc="Input definition of geometry/bbox and projection/wcs for template exposures",
78  name=BaseSkyMap.SKYMAP_DATASET_TYPE_NAME,
79  dimensions=("skymap", ),
80  storageClass="SkyMap",
81  )
82  coaddExposures = pipeBase.connectionTypes.Input(
83  doc="Input template to match and subtract from the exposure",
84  dimensions=("tract", "patch", "skymap", "band"),
85  storageClass="ExposureF",
86  name="{fakesType}{coaddName}Coadd{warpTypeSuffix}",
87  multiple=True,
88  deferLoad=True
89  )
90  dcrCoadds = pipeBase.connectionTypes.Input(
91  doc="Input DCR template to match and subtract from the exposure",
92  name="{fakesType}dcrCoadd{warpTypeSuffix}",
93  storageClass="ExposureF",
94  dimensions=("tract", "patch", "skymap", "band", "subfilter"),
95  multiple=True,
96  deferLoad=True
97  )
98  outputSchema = pipeBase.connectionTypes.InitOutput(
99  doc="Schema (as an example catalog) for output DIASource catalog.",
100  storageClass="SourceCatalog",
101  name="{fakesType}{coaddName}Diff_diaSrc_schema",
102  )
103  # TODO DM-29965: Currently the AL likelihood image is not a separate data product
104  subtractedExposure = pipeBase.connectionTypes.Output(
105  doc="Output AL difference or Zogy proper difference image",
106  dimensions=("instrument", "visit", "detector"),
107  storageClass="ExposureF",
108  name="{fakesType}{coaddName}Diff_differenceExp",
109  )
110  scoreExposure = pipeBase.connectionTypes.Output(
111  doc="Output Zogy score (likelihood) image",
112  dimensions=("instrument", "visit", "detector"),
113  storageClass="ExposureF",
114  name="{fakesType}{coaddName}Diff_scoreExp",
115  )
116  warpedExposure = pipeBase.connectionTypes.Output(
117  doc="Warped template used to create `subtractedExposure`.",
118  dimensions=("instrument", "visit", "detector"),
119  storageClass="ExposureF",
120  name="{fakesType}{coaddName}Diff_warpedExp",
121  )
122  matchedExposure = pipeBase.connectionTypes.Output(
123  doc="Warped template used to create `subtractedExposure`.",
124  dimensions=("instrument", "visit", "detector"),
125  storageClass="ExposureF",
126  name="{fakesType}{coaddName}Diff_matchedExp",
127  )
128  diaSources = pipeBase.connectionTypes.Output(
129  doc="Output detected diaSources on the difference image",
130  dimensions=("instrument", "visit", "detector"),
131  storageClass="SourceCatalog",
132  name="{fakesType}{coaddName}Diff_diaSrc",
133  )
134 
135  def __init__(self, *, config=None):
136  super().__init__(config=config)
137  if config.coaddName == 'dcr':
138  self.inputs.remove("coaddExposures")
139  else:
140  self.inputs.remove("dcrCoadds")
141  if not config.doWriteSubtractedExp:
142  self.outputs.remove("subtractedExposure")
143  if not config.doWriteScoreExp:
144  self.outputs.remove("scoreExposure")
145  if not config.doWriteWarpedExp:
146  self.outputs.remove("warpedExposure")
147  if not config.doWriteMatchedExp:
148  self.outputs.remove("matchedExposure")
149  if not config.doWriteSources:
150  self.outputs.remove("diaSources")
151 
152  # TODO DM-22953: Add support for refObjLoader (kernelSourcesFromRef)
153  # Make kernelSources optional
154 
155 
156 class ImageDifferenceConfig(pipeBase.PipelineTaskConfig,
157  pipelineConnections=ImageDifferenceTaskConnections):
158  """Config for ImageDifferenceTask
159  """
160  doAddCalexpBackground = pexConfig.Field(dtype=bool, default=False,
161  doc="Add background to calexp before processing it. "
162  "Useful as ipDiffim does background matching.")
163  doUseRegister = pexConfig.Field(dtype=bool, default=False,
164  doc="Re-compute astrometry on the template. "
165  "Use image-to-image registration to align template with "
166  "science image (AL only).")
167  doDebugRegister = pexConfig.Field(dtype=bool, default=False,
168  doc="Writing debugging data for doUseRegister")
169  doSelectSources = pexConfig.Field(dtype=bool, default=False,
170  doc="Select stars to use for kernel fitting (AL only)")
171  doSelectDcrCatalog = pexConfig.Field(dtype=bool, default=False,
172  doc="Select stars of extreme color as part "
173  "of the control sample (AL only)")
174  doSelectVariableCatalog = pexConfig.Field(dtype=bool, default=False,
175  doc="Select stars that are variable to be part "
176  "of the control sample (AL only)")
177  doSubtract = pexConfig.Field(dtype=bool, default=True, doc="Compute subtracted exposure?")
178  doPreConvolve = pexConfig.Field(dtype=bool, default=False,
179  doc="Convolve science image by its PSF before PSF-matching (AL only)."
180  " The difference image becomes a likelihood image.")
181  useScoreImageDetection = pexConfig.Field(
182  dtype=bool, default=False, doc="Calculate and detect sources on the Zogy score image (Zogy only).")
183  doWriteScoreExp = pexConfig.Field(
184  dtype=bool, default=False, doc="Write score exposure (Zogy only) ?")
185  doScaleTemplateVariance = pexConfig.Field(dtype=bool, default=False,
186  doc="Scale variance of the template before PSF matching")
187  doScaleDiffimVariance = pexConfig.Field(dtype=bool, default=True,
188  doc="Scale variance of the diffim before PSF matching. "
189  "You may do either this or template variance scaling, "
190  "or neither. (Doing both is a waste of CPU.)")
191  useGaussianForPreConvolution = pexConfig.Field(dtype=bool, default=True,
192  doc="Use a simple gaussian PSF model for pre-convolution "
193  "(else use fit PSF)? Ignored if doPreConvolve false.")
194  doDetection = pexConfig.Field(dtype=bool, default=True, doc="Detect sources?")
195  doDecorrelation = pexConfig.Field(dtype=bool, default=True,
196  doc="Perform diffim decorrelation to undo pixel correlation due to A&L "
197  "kernel convolution (AL only)? If True, also update the diffim PSF.")
198  doMerge = pexConfig.Field(dtype=bool, default=True,
199  doc="Merge positive and negative diaSources with grow radius "
200  "set by growFootprint")
201  doMatchSources = pexConfig.Field(dtype=bool, default=False,
202  doc="Match diaSources with input calexp sources and ref catalog sources")
203  doMeasurement = pexConfig.Field(dtype=bool, default=True, doc="Measure diaSources?")
204  doDipoleFitting = pexConfig.Field(dtype=bool, default=True, doc="Measure dipoles using new algorithm?")
205  doForcedMeasurement = pexConfig.Field(
206  dtype=bool,
207  default=True,
208  doc="Force photometer diaSource locations on PVI?")
209  doWriteSubtractedExp = pexConfig.Field(
210  dtype=bool, default=True, doc="Write difference exposure (AL and Zogy) ?")
211  doWriteWarpedExp = pexConfig.Field(
212  dtype=bool, default=False, doc="Write WCS, warped template coadd exposure?")
213  doWriteMatchedExp = pexConfig.Field(dtype=bool, default=False,
214  doc="Write warped and PSF-matched template coadd exposure?")
215  doWriteSources = pexConfig.Field(dtype=bool, default=True, doc="Write sources?")
216  doAddMetrics = pexConfig.Field(dtype=bool, default=False,
217  doc="Add columns to the source table to hold analysis metrics?")
218 
219  coaddName = pexConfig.Field(
220  doc="coadd name: typically one of deep, goodSeeing, or dcr",
221  dtype=str,
222  default="deep",
223  )
224  convolveTemplate = pexConfig.Field(
225  doc="Which image gets convolved (default = template)",
226  dtype=bool,
227  default=True
228  )
229  refObjLoader = pexConfig.ConfigurableField(
230  target=LoadIndexedReferenceObjectsTask,
231  doc="reference object loader",
232  )
233  astrometer = pexConfig.ConfigurableField(
234  target=AstrometryTask,
235  doc="astrometry task; used to match sources to reference objects, but not to fit a WCS",
236  )
237  sourceSelector = pexConfig.ConfigurableField(
238  target=ObjectSizeStarSelectorTask,
239  doc="Source selection algorithm",
240  )
241  subtract = subtractAlgorithmRegistry.makeField("Subtraction Algorithm", default="al")
242  decorrelate = pexConfig.ConfigurableField(
243  target=DecorrelateALKernelSpatialTask,
244  doc="Decorrelate effects of A&L kernel convolution on image difference, only if doSubtract is True. "
245  "If this option is enabled, then detection.thresholdValue should be set to 5.0 (rather than the "
246  "default of 5.5).",
247  )
248  # Old style ImageMapper grid. ZogyTask has its own grid option
249  doSpatiallyVarying = pexConfig.Field(
250  dtype=bool,
251  default=False,
252  doc="Perform A&L decorrelation on a grid across the "
253  "image in order to allow for spatial variations. Zogy does not use this option."
254  )
255  detection = pexConfig.ConfigurableField(
256  target=SourceDetectionTask,
257  doc="Low-threshold detection for final measurement",
258  )
259  measurement = pexConfig.ConfigurableField(
260  target=DipoleFitTask,
261  doc="Enable updated dipole fitting method",
262  )
263  doApCorr = lsst.pex.config.Field(
264  dtype=bool,
265  default=True,
266  doc="Run subtask to apply aperture corrections"
267  )
268  applyApCorr = lsst.pex.config.ConfigurableField(
269  target=ApplyApCorrTask,
270  doc="Subtask to apply aperture corrections"
271  )
272  forcedMeasurement = pexConfig.ConfigurableField(
273  target=ForcedMeasurementTask,
274  doc="Subtask to force photometer PVI at diaSource location.",
275  )
276  getTemplate = pexConfig.ConfigurableField(
277  target=GetCoaddAsTemplateTask,
278  doc="Subtask to retrieve template exposure and sources",
279  )
280  scaleVariance = pexConfig.ConfigurableField(
281  target=ScaleVarianceTask,
282  doc="Subtask to rescale the variance of the template "
283  "to the statistically expected level"
284  )
285  controlStepSize = pexConfig.Field(
286  doc="What step size (every Nth one) to select a control sample from the kernelSources",
287  dtype=int,
288  default=5
289  )
290  controlRandomSeed = pexConfig.Field(
291  doc="Random seed for shuffing the control sample",
292  dtype=int,
293  default=10
294  )
295  register = pexConfig.ConfigurableField(
296  target=RegisterTask,
297  doc="Task to enable image-to-image image registration (warping)",
298  )
299  kernelSourcesFromRef = pexConfig.Field(
300  doc="Select sources to measure kernel from reference catalog if True, template if false",
301  dtype=bool,
302  default=False
303  )
304  templateSipOrder = pexConfig.Field(
305  dtype=int, default=2,
306  doc="Sip Order for fitting the Template Wcs (default is too high, overfitting)"
307  )
308  growFootprint = pexConfig.Field(
309  dtype=int, default=2,
310  doc="Grow positive and negative footprints by this amount before merging"
311  )
312  diaSourceMatchRadius = pexConfig.Field(
313  dtype=float, default=0.5,
314  doc="Match radius (in arcseconds) for DiaSource to Source association"
315  )
316  requiredTemplateFraction = pexConfig.Field(
317  dtype=float, default=0.1,
318  doc="Do not attempt to run task if template covers less than this fraction of pixels."
319  "Setting to 0 will always attempt image subtraction"
320  )
321  doSkySources = pexConfig.Field(
322  dtype=bool,
323  default=False,
324  doc="Generate sky sources?",
325  )
326  skySources = pexConfig.ConfigurableField(
327  target=SkyObjectsTask,
328  doc="Generate sky sources",
329  )
330 
331  def setDefaults(self):
332  # defaults are OK for catalog and diacatalog
333 
334  self.subtract['al'].kernel.name = "AL"
335  self.subtract['al'].kernel.active.fitForBackground = True
336  self.subtract['al'].kernel.active.spatialKernelOrder = 1
337  self.subtract['al'].kernel.active.spatialBgOrder = 2
338 
339  # DiaSource Detection
340  self.detection.thresholdPolarity = "both"
341  self.detection.thresholdValue = 5.0
342  self.detection.reEstimateBackground = False
343  self.detection.thresholdType = "pixel_stdev"
344 
345  # Add filtered flux measurement, the correct measurement for pre-convolved images.
346  # Enable all measurements, regardless of doPreConvolve, as it makes data harvesting easier.
347  # To change that you must modify algorithms.names in the task's applyOverrides method,
348  # after the user has set doPreConvolve.
349  self.measurement.algorithms.names.add('base_PeakLikelihoodFlux')
350  self.measurement.plugins.names |= ['base_LocalPhotoCalib',
351  'base_LocalWcs']
352 
353  self.forcedMeasurement.plugins = ["base_TransformedCentroid", "base_PsfFlux"]
354  self.forcedMeasurement.copyColumns = {
355  "id": "objectId", "parent": "parentObjectId", "coord_ra": "coord_ra", "coord_dec": "coord_dec"}
356  self.forcedMeasurement.slots.centroid = "base_TransformedCentroid"
357  self.forcedMeasurement.slots.shape = None
358 
359  # For shuffling the control sample
360  random.seed(self.controlRandomSeed)
361 
362  def validate(self):
363  pexConfig.Config.validate(self)
364  if not self.doSubtract and not self.doDetection:
365  raise ValueError("Either doSubtract or doDetection must be enabled.")
366  if self.doMeasurement and not self.doDetection:
367  raise ValueError("Cannot run source measurement without source detection.")
368  if self.doMerge and not self.doDetection:
369  raise ValueError("Cannot run source merging without source detection.")
370  if self.doSkySources and not self.doDetection:
371  raise ValueError("Cannot run sky source creation without source detection.")
372  if self.doUseRegister and not self.doSelectSources:
373  raise ValueError("doUseRegister=True and doSelectSources=False. "
374  "Cannot run RegisterTask without selecting sources.")
375  if hasattr(self.getTemplate, "coaddName"):
376  if self.getTemplate.coaddName != self.coaddName:
377  raise ValueError("Mis-matched coaddName and getTemplate.coaddName in the config.")
378  if self.doScaleDiffimVariance and self.doScaleTemplateVariance:
379  raise ValueError("Scaling the diffim variance and scaling the template variance "
380  "are both set. Please choose one or the other.")
381  # We cannot allow inconsistencies that would lead to None or not available output products
382  if self.subtract.name == 'zogy':
383  if self.doWriteScoreExp and not self.useScoreImageDetection:
384  raise ValueError("doWriteScoreExp=True and useScoreImageDetection=False "
385  "is not supported. Score image is not calculated.")
386  if self.doWriteMatchedExp:
387  raise ValueError("doWriteMatchedExp=True Matched exposure is not "
388  "calculated in zogy subtraction.")
389  if self.doAddMetrics:
390  raise ValueError("doAddMetrics=True Kernel metrics does not exist in zogy subtraction.")
391  if self.doDecorrelation:
392  raise ValueError(
393  "doDecorrelation=True The decorrelation afterburner does not exist in zogy subtraction.")
394  if self.doPreConvolve:
395  raise ValueError(
396  "doPreConvolve=True Pre-convolution is not a zogy option.")
397  if self.doSelectSources:
398  raise ValueError(
399  "doSelectSources=True Selecting sources for PSF matching is not a zogy option.")
400  else:
401  if self.useScoreImageDetection:
402  raise ValueError("useScoreImageDetection=True Score exposure does not "
403  "exist in AL subtraction.")
404  if self.doWriteScoreExp: # Ensure output is not None
405  raise ValueError("doWriteScoreExp=True Score exposure does not exist in AL subtraction.")
406  if self.doAddMetrics and not self.doSubtract:
407  raise ValueError("Subtraction must be enabled for kernel metrics calculation.")
408  if self.doPreConvolve and self.doDecorrelation:
409  raise NotImplementedError(
410  "doPreConvolve=True and doDecorrelation=True "
411  "The decorrelation afterburner cannot handle pre-convolved exposures.")
412 
413 
414 class ImageDifferenceTaskRunner(pipeBase.ButlerInitializedTaskRunner):
415 
416  @staticmethod
417  def getTargetList(parsedCmd, **kwargs):
418  return pipeBase.TaskRunner.getTargetList(parsedCmd, templateIdList=parsedCmd.templateId.idList,
419  **kwargs)
420 
421 
422 class ImageDifferenceTask(pipeBase.CmdLineTask, pipeBase.PipelineTask):
423  """Subtract an image from a template and measure the result
424  """
425  ConfigClass = ImageDifferenceConfig
426  RunnerClass = ImageDifferenceTaskRunner
427  _DefaultName = "imageDifference"
428 
429  def __init__(self, butler=None, **kwargs):
430  """!Construct an ImageDifference Task
431 
432  @param[in] butler Butler object to use in constructing reference object loaders
433  """
434  super().__init__(**kwargs)
435  self.makeSubtask("getTemplate")
436 
437  self.makeSubtask("subtract")
438 
439  if self.config.subtract.name == 'al' and self.config.doDecorrelation:
440  self.makeSubtask("decorrelate")
441 
442  if self.config.doScaleTemplateVariance or self.config.doScaleDiffimVariance:
443  self.makeSubtask("scaleVariance")
444 
445  if self.config.doUseRegister:
446  self.makeSubtask("register")
447  self.schema = afwTable.SourceTable.makeMinimalSchema()
448 
449  if self.config.doSelectSources:
450  self.makeSubtask("sourceSelector")
451  if self.config.kernelSourcesFromRef:
452  self.makeSubtask('refObjLoader', butler=butler)
453  self.makeSubtask("astrometer", refObjLoader=self.refObjLoader)
454 
455  self.algMetadata = dafBase.PropertyList()
456  if self.config.doDetection:
457  self.makeSubtask("detection", schema=self.schema)
458  if self.config.doMeasurement:
459  self.makeSubtask("measurement", schema=self.schema,
460  algMetadata=self.algMetadata)
461  if self.config.doApCorr:
462  self.makeSubtask("applyApCorr", schema=self.measurement.schema)
463  if self.config.doForcedMeasurement:
464  self.schema.addField(
465  "ip_diffim_forced_PsfFlux_instFlux", "D",
466  "Forced PSF flux measured on the direct image.",
467  units="count")
468  self.schema.addField(
469  "ip_diffim_forced_PsfFlux_instFluxErr", "D",
470  "Forced PSF flux error measured on the direct image.",
471  units="count")
472  self.schema.addField(
473  "ip_diffim_forced_PsfFlux_area", "F",
474  "Forced PSF flux effective area of PSF.",
475  units="pixel")
476  self.schema.addField(
477  "ip_diffim_forced_PsfFlux_flag", "Flag",
478  "Forced PSF flux general failure flag.")
479  self.schema.addField(
480  "ip_diffim_forced_PsfFlux_flag_noGoodPixels", "Flag",
481  "Forced PSF flux not enough non-rejected pixels in data to attempt the fit.")
482  self.schema.addField(
483  "ip_diffim_forced_PsfFlux_flag_edge", "Flag",
484  "Forced PSF flux object was too close to the edge of the image to use the full PSF model.")
485  self.makeSubtask("forcedMeasurement", refSchema=self.schema)
486  if self.config.doMatchSources:
487  self.schema.addField("refMatchId", "L", "unique id of reference catalog match")
488  self.schema.addField("srcMatchId", "L", "unique id of source match")
489  if self.config.doSkySources:
490  self.makeSubtask("skySources")
491  self.skySourceKey = self.schema.addField("sky_source", type="Flag", doc="Sky objects.")
492 
493  # initialize InitOutputs
494  self.outputSchema = afwTable.SourceCatalog(self.schema)
495  self.outputSchema.getTable().setMetadata(self.algMetadata)
496 
497  @staticmethod
498  def makeIdFactory(expId, expBits):
499  """Create IdFactory instance for unique 64 bit diaSource id-s.
500 
501  Parameters
502  ----------
503  expId : `int`
504  Exposure id.
505 
506  expBits: `int`
507  Number of used bits in ``expId``.
508 
509  Note
510  ----
511  The diasource id-s consists of the ``expId`` stored fixed in the highest value
512  ``expBits`` of the 64-bit integer plus (bitwise or) a generated sequence number in the
513  low value end of the integer.
514 
515  Returns
516  -------
517  idFactory: `lsst.afw.table.IdFactory`
518  """
519  return ExposureIdInfo(expId, expBits).makeSourceIdFactory()
520 
521  @lsst.utils.inheritDoc(pipeBase.PipelineTask)
522  def runQuantum(self, butlerQC: pipeBase.ButlerQuantumContext,
523  inputRefs: pipeBase.InputQuantizedConnection,
524  outputRefs: pipeBase.OutputQuantizedConnection):
525  inputs = butlerQC.get(inputRefs)
526  self.log.info("Processing %s", butlerQC.quantum.dataId)
527  expId, expBits = butlerQC.quantum.dataId.pack("visit_detector",
528  returnMaxBits=True)
529  idFactory = self.makeIdFactory(expId=expId, expBits=expBits)
530  if self.config.coaddName == 'dcr':
531  templateExposures = inputRefs.dcrCoadds
532  else:
533  templateExposures = inputRefs.coaddExposures
534  templateStruct = self.getTemplate.runQuantum(
535  inputs['exposure'], butlerQC, inputRefs.skyMap, templateExposures
536  )
537 
538  if templateStruct.area/inputs['exposure'].getBBox().getArea() < self.config.requiredTemplateFraction:
539  message = ("Insufficient Template Coverage. (%.1f%% < %.1f%%) Not attempting subtraction. "
540  "To force subtraction, set config requiredTemplateFraction=0." % (
541  100*templateStruct.area/inputs['exposure'].getBBox().getArea(),
542  100*self.config.requiredTemplateFraction))
543  raise pipeBase.NoWorkFound(message)
544  else:
545  outputs = self.run(exposure=inputs['exposure'],
546  templateExposure=templateStruct.exposure,
547  idFactory=idFactory)
548  # Consistency with runDataref gen2 handling
549  if outputs.diaSources is None:
550  del outputs.diaSources
551  butlerQC.put(outputs, outputRefs)
552 
553  @pipeBase.timeMethod
554  def runDataRef(self, sensorRef, templateIdList=None):
555  """Subtract an image from a template coadd and measure the result.
556 
557  Data I/O wrapper around `run` using the butler in Gen2.
558 
559  Parameters
560  ----------
561  sensorRef : `lsst.daf.persistence.ButlerDataRef`
562  Sensor-level butler data reference, used for the following data products:
563 
564  Input only:
565  - calexp
566  - psf
567  - ccdExposureId
568  - ccdExposureId_bits
569  - self.config.coaddName + "Coadd_skyMap"
570  - self.config.coaddName + "Coadd"
571  Input or output, depending on config:
572  - self.config.coaddName + "Diff_subtractedExp"
573  Output, depending on config:
574  - self.config.coaddName + "Diff_matchedExp"
575  - self.config.coaddName + "Diff_src"
576 
577  Returns
578  -------
579  results : `lsst.pipe.base.Struct`
580  Returns the Struct by `run`.
581  """
582  subtractedExposureName = self.config.coaddName + "Diff_differenceExp"
583  subtractedExposure = None
584  selectSources = None
585  calexpBackgroundExposure = None
586  self.log.info("Processing %s", sensorRef.dataId)
587 
588  # We make one IdFactory that will be used by both icSrc and src datasets;
589  # I don't know if this is the way we ultimately want to do things, but at least
590  # this ensures the source IDs are fully unique.
591  idFactory = self.makeIdFactory(expId=int(sensorRef.get("ccdExposureId")),
592  expBits=sensorRef.get("ccdExposureId_bits"))
593  if self.config.doAddCalexpBackground:
594  calexpBackgroundExposure = sensorRef.get("calexpBackground")
595 
596  # Retrieve the science image we wish to analyze
597  exposure = sensorRef.get("calexp", immediate=True)
598 
599  # Retrieve the template image
600  template = self.getTemplate.runDataRef(exposure, sensorRef, templateIdList=templateIdList)
601 
602  if sensorRef.datasetExists("src"):
603  self.log.info("Source selection via src product")
604  # Sources already exist; for data release processing
605  selectSources = sensorRef.get("src")
606 
607  if not self.config.doSubtract and self.config.doDetection:
608  # If we don't do subtraction, we need the subtracted exposure from the repo
609  subtractedExposure = sensorRef.get(subtractedExposureName)
610  # Both doSubtract and doDetection cannot be False
611 
612  results = self.run(exposure=exposure,
613  selectSources=selectSources,
614  templateExposure=template.exposure,
615  templateSources=template.sources,
616  idFactory=idFactory,
617  calexpBackgroundExposure=calexpBackgroundExposure,
618  subtractedExposure=subtractedExposure)
619 
620  if self.config.doWriteSources and results.diaSources is not None:
621  sensorRef.put(results.diaSources, self.config.coaddName + "Diff_diaSrc")
622  if self.config.doWriteWarpedExp:
623  sensorRef.put(results.warpedExposure, self.config.coaddName + "Diff_warpedExp")
624  if self.config.doWriteMatchedExp:
625  sensorRef.put(results.matchedExposure, self.config.coaddName + "Diff_matchedExp")
626  if self.config.doAddMetrics and self.config.doSelectSources:
627  sensorRef.put(results.selectSources, self.config.coaddName + "Diff_kernelSrc")
628  if self.config.doWriteSubtractedExp:
629  sensorRef.put(results.subtractedExposure, subtractedExposureName)
630  if self.config.doWriteScoreExp:
631  sensorRef.put(results.scoreExposure, self.config.coaddName + "Diff_scoreExp")
632  return results
633 
634  @pipeBase.timeMethod
635  def run(self, exposure=None, selectSources=None, templateExposure=None, templateSources=None,
636  idFactory=None, calexpBackgroundExposure=None, subtractedExposure=None):
637  """PSF matches, subtract two images and perform detection on the difference image.
638 
639  Parameters
640  ----------
641  exposure : `lsst.afw.image.ExposureF`, optional
642  The science exposure, the minuend in the image subtraction.
643  Can be None only if ``config.doSubtract==False``.
644  selectSources : `lsst.afw.table.SourceCatalog`, optional
645  Identified sources on the science exposure. This catalog is used to
646  select sources in order to perform the AL PSF matching on stamp images
647  around them. The selection steps depend on config options and whether
648  ``templateSources`` and ``matchingSources`` specified.
649  templateExposure : `lsst.afw.image.ExposureF`, optional
650  The template to be subtracted from ``exposure`` in the image subtraction.
651  ``templateExposure`` is modified in place if ``config.doScaleTemplateVariance==True``.
652  The template exposure should cover the same sky area as the science exposure.
653  It is either a stich of patches of a coadd skymap image or a calexp
654  of the same pointing as the science exposure. Can be None only
655  if ``config.doSubtract==False`` and ``subtractedExposure`` is not None.
656  templateSources : `lsst.afw.table.SourceCatalog`, optional
657  Identified sources on the template exposure.
658  idFactory : `lsst.afw.table.IdFactory`
659  Generator object to assign ids to detected sources in the difference image.
660  calexpBackgroundExposure : `lsst.afw.image.ExposureF`, optional
661  Background exposure to be added back to the science exposure
662  if ``config.doAddCalexpBackground==True``
663  subtractedExposure : `lsst.afw.image.ExposureF`, optional
664  If ``config.doSubtract==False`` and ``config.doDetection==True``,
665  performs the post subtraction source detection only on this exposure.
666  Otherwise should be None.
667 
668  Returns
669  -------
670  results : `lsst.pipe.base.Struct`
671  ``subtractedExposure`` : `lsst.afw.image.ExposureF`
672  Difference image.
673  ``scoreExposure`` : `lsst.afw.image.ExposureF` or `None`
674  The zogy score exposure, if calculated.
675  ``matchedExposure`` : `lsst.afw.image.ExposureF`
676  The matched PSF exposure.
677  ``subtractRes`` : `lsst.pipe.base.Struct`
678  The returned result structure of the ImagePsfMatchTask subtask.
679  ``diaSources`` : `lsst.afw.table.SourceCatalog`
680  The catalog of detected sources.
681  ``selectSources`` : `lsst.afw.table.SourceCatalog`
682  The input source catalog with optionally added Qa information.
683 
684  Notes
685  -----
686  The following major steps are included:
687 
688  - warp template coadd to match WCS of image
689  - PSF match image to warped template
690  - subtract image from PSF-matched, warped template
691  - detect sources
692  - measure sources
693 
694  For details about the image subtraction configuration modes
695  see `lsst.ip.diffim`.
696  """
697  subtractRes = None
698  controlSources = None
699  scoreExposure = None
700  diaSources = None
701  kernelSources = None
702  # We'll clone exposure if modified but will still need the original
703  exposureOrig = exposure
704 
705  if self.config.doAddCalexpBackground:
706  mi = exposure.getMaskedImage()
707  mi += calexpBackgroundExposure.getImage()
708 
709  if not exposure.hasPsf():
710  raise pipeBase.TaskError("Exposure has no psf")
711  sciencePsf = exposure.getPsf()
712 
713  if self.config.doSubtract:
714  if self.config.doScaleTemplateVariance:
715  self.log.info("Rescaling template variance")
716  templateVarFactor = self.scaleVariance.run(
717  templateExposure.getMaskedImage())
718  self.log.info("Template variance scaling factor: %.2f", templateVarFactor)
719  self.metadata.add("scaleTemplateVarianceFactor", templateVarFactor)
720 
721  if self.config.subtract.name == 'zogy':
722  subtractRes = self.subtract.run(exposure, templateExposure, doWarping=True)
723  scoreExposure = subtractRes.scoreExp
724  subtractedExposure = subtractRes.diffExp
725  subtractRes.subtractedExposure = subtractedExposure
726  subtractRes.matchedExposure = None
727 
728  elif self.config.subtract.name == 'al':
729  # compute scienceSigmaOrig: sigma of PSF of science image before pre-convolution
730  scienceSigmaOrig = sciencePsf.computeShape().getDeterminantRadius()
731  templateSigma = templateExposure.getPsf().computeShape().getDeterminantRadius()
732 
733  # if requested, convolve the science exposure with its PSF
734  # (properly, this should be a cross-correlation, but our code does not yet support that)
735  # compute scienceSigmaPost: sigma of science exposure with pre-convolution, if done,
736  # else sigma of original science exposure
737  # TODO: DM-22762 This functional block should be moved into its own method
738  preConvPsf = None
739  if self.config.doPreConvolve:
740  convControl = afwMath.ConvolutionControl()
741  # cannot convolve in place, so need a new image anyway
742  srcMI = exposure.maskedImage
743  exposure = exposure.clone() # New deep copy
744  srcPsf = sciencePsf
745  if self.config.useGaussianForPreConvolution:
746  # convolve with a simplified PSF model: a double Gaussian
747  kWidth, kHeight = sciencePsf.getLocalKernel().getDimensions()
748  preConvPsf = SingleGaussianPsf(kWidth, kHeight, scienceSigmaOrig)
749  else:
750  # convolve with science exposure's PSF model
751  preConvPsf = srcPsf
752  afwMath.convolve(exposure.maskedImage, srcMI, preConvPsf.getLocalKernel(), convControl)
753  scienceSigmaPost = scienceSigmaOrig*math.sqrt(2)
754  else:
755  scienceSigmaPost = scienceSigmaOrig
756 
757  # If requested, find and select sources from the image
758  # else, AL subtraction will do its own source detection
759  # TODO: DM-22762 This functional block should be moved into its own method
760  if self.config.doSelectSources:
761  if selectSources is None:
762  self.log.warning("Src product does not exist; running detection, measurement,"
763  " selection")
764  # Run own detection and measurement; necessary in nightly processing
765  selectSources = self.subtract.getSelectSources(
766  exposure,
767  sigma=scienceSigmaPost,
768  doSmooth=not self.config.doPreConvolve,
769  idFactory=idFactory,
770  )
771 
772  if self.config.doAddMetrics:
773  # Number of basis functions
774 
775  nparam = len(makeKernelBasisList(self.subtract.config.kernel.active,
776  referenceFwhmPix=scienceSigmaPost*FwhmPerSigma,
777  targetFwhmPix=templateSigma*FwhmPerSigma))
778  # Modify the schema of all Sources
779  # DEPRECATED: This is a data dependent (nparam) output product schema
780  # outside the task constructor.
781  # NOTE: The pre-determination of nparam at this point
782  # may be incorrect as the template psf is warped later in
783  # ImagePsfMatchTask.matchExposures()
784  kcQa = KernelCandidateQa(nparam)
785  selectSources = kcQa.addToSchema(selectSources)
786  if self.config.kernelSourcesFromRef:
787  # match exposure sources to reference catalog
788  astromRet = self.astrometer.loadAndMatch(exposure=exposure, sourceCat=selectSources)
789  matches = astromRet.matches
790  elif templateSources:
791  # match exposure sources to template sources
792  mc = afwTable.MatchControl()
793  mc.findOnlyClosest = False
794  matches = afwTable.matchRaDec(templateSources, selectSources, 1.0*geom.arcseconds,
795  mc)
796  else:
797  raise RuntimeError("doSelectSources=True and kernelSourcesFromRef=False,"
798  "but template sources not available. Cannot match science "
799  "sources with template sources. Run process* on data from "
800  "which templates are built.")
801 
802  kernelSources = self.sourceSelector.run(selectSources, exposure=exposure,
803  matches=matches).sourceCat
804  random.shuffle(kernelSources, random.random)
805  controlSources = kernelSources[::self.config.controlStepSize]
806  kernelSources = [k for i, k in enumerate(kernelSources)
807  if i % self.config.controlStepSize]
808 
809  if self.config.doSelectDcrCatalog:
810  redSelector = DiaCatalogSourceSelectorTask(
811  DiaCatalogSourceSelectorConfig(grMin=self.sourceSelector.config.grMax,
812  grMax=99.999))
813  redSources = redSelector.selectStars(exposure, selectSources, matches=matches).starCat
814  controlSources.extend(redSources)
815 
816  blueSelector = DiaCatalogSourceSelectorTask(
817  DiaCatalogSourceSelectorConfig(grMin=-99.999,
818  grMax=self.sourceSelector.config.grMin))
819  blueSources = blueSelector.selectStars(exposure, selectSources,
820  matches=matches).starCat
821  controlSources.extend(blueSources)
822 
823  if self.config.doSelectVariableCatalog:
824  varSelector = DiaCatalogSourceSelectorTask(
825  DiaCatalogSourceSelectorConfig(includeVariable=True))
826  varSources = varSelector.selectStars(exposure, selectSources, matches=matches).starCat
827  controlSources.extend(varSources)
828 
829  self.log.info("Selected %d / %d sources for Psf matching (%d for control sample)",
830  len(kernelSources), len(selectSources), len(controlSources))
831 
832  allresids = {}
833  # TODO: DM-22762 This functional block should be moved into its own method
834  if self.config.doUseRegister:
835  self.log.info("Registering images")
836 
837  if templateSources is None:
838  # Run detection on the template, which is
839  # temporarily background-subtracted
840  # sigma of PSF of template image before warping
841  templateSigma = templateExposure.getPsf().computeShape().getDeterminantRadius()
842  templateSources = self.subtract.getSelectSources(
843  templateExposure,
844  sigma=templateSigma,
845  doSmooth=True,
846  idFactory=idFactory
847  )
848 
849  # Third step: we need to fit the relative astrometry.
850  #
851  wcsResults = self.fitAstrometry(templateSources, templateExposure, selectSources)
852  warpedExp = self.register.warpExposure(templateExposure, wcsResults.wcs,
853  exposure.getWcs(), exposure.getBBox())
854  templateExposure = warpedExp
855 
856  # Create debugging outputs on the astrometric
857  # residuals as a function of position. Persistence
858  # not yet implemented; expected on (I believe) #2636.
859  if self.config.doDebugRegister:
860  # Grab matches to reference catalog
861  srcToMatch = {x.second.getId(): x.first for x in matches}
862 
863  refCoordKey = wcsResults.matches[0].first.getTable().getCoordKey()
864  inCentroidKey = wcsResults.matches[0].second.getTable().getCentroidSlot().getMeasKey()
865  sids = [m.first.getId() for m in wcsResults.matches]
866  positions = [m.first.get(refCoordKey) for m in wcsResults.matches]
867  residuals = [m.first.get(refCoordKey).getOffsetFrom(wcsResults.wcs.pixelToSky(
868  m.second.get(inCentroidKey))) for m in wcsResults.matches]
869  allresids = dict(zip(sids, zip(positions, residuals)))
870 
871  cresiduals = [m.first.get(refCoordKey).getTangentPlaneOffset(
872  wcsResults.wcs.pixelToSky(
873  m.second.get(inCentroidKey))) for m in wcsResults.matches]
874  colors = numpy.array([-2.5*numpy.log10(srcToMatch[x].get("g"))
875  + 2.5*numpy.log10(srcToMatch[x].get("r"))
876  for x in sids if x in srcToMatch.keys()])
877  dlong = numpy.array([r[0].asArcseconds() for s, r in zip(sids, cresiduals)
878  if s in srcToMatch.keys()])
879  dlat = numpy.array([r[1].asArcseconds() for s, r in zip(sids, cresiduals)
880  if s in srcToMatch.keys()])
881  idx1 = numpy.where(colors < self.sourceSelector.config.grMin)
882  idx2 = numpy.where((colors >= self.sourceSelector.config.grMin)
883  & (colors <= self.sourceSelector.config.grMax))
884  idx3 = numpy.where(colors > self.sourceSelector.config.grMax)
885  rms1Long = IqrToSigma*(
886  (numpy.percentile(dlong[idx1], 75) - numpy.percentile(dlong[idx1], 25)))
887  rms1Lat = IqrToSigma*(numpy.percentile(dlat[idx1], 75)
888  - numpy.percentile(dlat[idx1], 25))
889  rms2Long = IqrToSigma*(
890  (numpy.percentile(dlong[idx2], 75) - numpy.percentile(dlong[idx2], 25)))
891  rms2Lat = IqrToSigma*(numpy.percentile(dlat[idx2], 75)
892  - numpy.percentile(dlat[idx2], 25))
893  rms3Long = IqrToSigma*(
894  (numpy.percentile(dlong[idx3], 75) - numpy.percentile(dlong[idx3], 25)))
895  rms3Lat = IqrToSigma*(numpy.percentile(dlat[idx3], 75)
896  - numpy.percentile(dlat[idx3], 25))
897  self.log.info("Blue star offsets'': %.3f %.3f, %.3f %.3f",
898  numpy.median(dlong[idx1]), rms1Long,
899  numpy.median(dlat[idx1]), rms1Lat)
900  self.log.info("Green star offsets'': %.3f %.3f, %.3f %.3f",
901  numpy.median(dlong[idx2]), rms2Long,
902  numpy.median(dlat[idx2]), rms2Lat)
903  self.log.info("Red star offsets'': %.3f %.3f, %.3f %.3f",
904  numpy.median(dlong[idx3]), rms3Long,
905  numpy.median(dlat[idx3]), rms3Lat)
906 
907  self.metadata.add("RegisterBlueLongOffsetMedian", numpy.median(dlong[idx1]))
908  self.metadata.add("RegisterGreenLongOffsetMedian", numpy.median(dlong[idx2]))
909  self.metadata.add("RegisterRedLongOffsetMedian", numpy.median(dlong[idx3]))
910  self.metadata.add("RegisterBlueLongOffsetStd", rms1Long)
911  self.metadata.add("RegisterGreenLongOffsetStd", rms2Long)
912  self.metadata.add("RegisterRedLongOffsetStd", rms3Long)
913 
914  self.metadata.add("RegisterBlueLatOffsetMedian", numpy.median(dlat[idx1]))
915  self.metadata.add("RegisterGreenLatOffsetMedian", numpy.median(dlat[idx2]))
916  self.metadata.add("RegisterRedLatOffsetMedian", numpy.median(dlat[idx3]))
917  self.metadata.add("RegisterBlueLatOffsetStd", rms1Lat)
918  self.metadata.add("RegisterGreenLatOffsetStd", rms2Lat)
919  self.metadata.add("RegisterRedLatOffsetStd", rms3Lat)
920 
921  # warp template exposure to match exposure,
922  # PSF match template exposure to exposure,
923  # then return the difference
924 
925  # Return warped template... Construct sourceKernelCand list after subtract
926  self.log.info("Subtracting images")
927  subtractRes = self.subtract.subtractExposures(
928  templateExposure=templateExposure,
929  scienceExposure=exposure,
930  candidateList=kernelSources,
931  convolveTemplate=self.config.convolveTemplate,
932  doWarping=not self.config.doUseRegister
933  )
934  subtractedExposure = subtractRes.subtractedExposure
935 
936  if self.config.doDetection:
937  self.log.info("Computing diffim PSF")
938 
939  # Get Psf from the appropriate input image if it doesn't exist
940  if not subtractedExposure.hasPsf():
941  if self.config.convolveTemplate:
942  subtractedExposure.setPsf(exposure.getPsf())
943  else:
944  subtractedExposure.setPsf(templateExposure.getPsf())
945 
946  # If doSubtract is False, then subtractedExposure was fetched from disk (above),
947  # thus it may have already been decorrelated. Thus, we do not decorrelate if
948  # doSubtract is False.
949 
950  # NOTE: At this point doSubtract == True
951  if self.config.doDecorrelation and self.config.doSubtract:
952  preConvKernel = None
953  if preConvPsf is not None:
954  preConvKernel = preConvPsf.getLocalKernel()
955  decorrResult = self.decorrelate.run(exposureOrig, subtractRes.warpedExposure,
956  subtractedExposure,
957  subtractRes.psfMatchingKernel,
958  spatiallyVarying=self.config.doSpatiallyVarying,
959  preConvKernel=preConvKernel,
960  templateMatched=self.config.convolveTemplate)
961  subtractedExposure = decorrResult.correctedExposure
962 
963  # END (if subtractAlgorithm == 'AL')
964  # END (if self.config.doSubtract)
965  if self.config.doDetection:
966  self.log.info("Running diaSource detection")
967 
968  # subtractedExposure - reserved for task return value
969  # in zogy, it is always the proper difference image
970  # in AL, it may be (yet) pre-convolved and/or decorrelated
971  #
972  # detectionExposure - controls which exposure to use for detection
973  # in-place modifications will appear in task return
974  if self.config.useScoreImageDetection:
975  # zogy with score image detection enabled
976  self.log.info("Detection, diffim rescaling and measurements are on Zogy score image.")
977  detectionExposure = scoreExposure
978  detectOnLikelihood = True
979  else:
980  # AL or zogy with no score image detection
981  detectionExposure = subtractedExposure
982  detectOnLikelihood = False
983  if self.config.doPreConvolve:
984  # In AL, the likelihood image is not a separate product, yet
985  self.log.info("Detection, diffim rescaling and measurements are on AL pre-convolved "
986  "difference (likelihood) image.")
987  detectOnLikelihood = True
988  else:
989  self.log.info("Detection, diffim rescaling and measurements are on "
990  "(proper) difference image.")
991 
992  # Rescale difference image variance plane
993  if self.config.doScaleDiffimVariance:
994  self.log.info("Rescaling diffim variance")
995  diffimVarFactor = self.scaleVariance.run(detectionExposure.getMaskedImage())
996  self.log.info("Diffim variance scaling factor: %.2f", diffimVarFactor)
997  self.metadata.add("scaleDiffimVarianceFactor", diffimVarFactor)
998 
999  # Erase existing detection mask planes
1000  mask = detectionExposure.getMaskedImage().getMask()
1001  mask &= ~(mask.getPlaneBitMask("DETECTED") | mask.getPlaneBitMask("DETECTED_NEGATIVE"))
1002 
1003  table = afwTable.SourceTable.make(self.schema, idFactory)
1004  table.setMetadata(self.algMetadata)
1005  results = self.detection.run(
1006  table=table,
1007  exposure=detectionExposure,
1008  doSmooth=not detectOnLikelihood
1009  )
1010 
1011  if self.config.doMerge:
1012  fpSet = results.fpSets.positive
1013  fpSet.merge(results.fpSets.negative, self.config.growFootprint,
1014  self.config.growFootprint, False)
1015  diaSources = afwTable.SourceCatalog(table)
1016  fpSet.makeSources(diaSources)
1017  self.log.info("Merging detections into %d sources", len(diaSources))
1018  else:
1019  diaSources = results.sources
1020  # Inject skySources before measurement.
1021  if self.config.doSkySources:
1022  skySourceFootprints = self.skySources.run(
1023  mask=detectionExposure.mask,
1024  seed=detectionExposure.getInfo().getVisitInfo().getExposureId())
1025  if skySourceFootprints:
1026  for foot in skySourceFootprints:
1027  s = diaSources.addNew()
1028  s.setFootprint(foot)
1029  s.set(self.skySourceKey, True)
1030 
1031  if self.config.doMeasurement:
1032  newDipoleFitting = self.config.doDipoleFitting
1033  self.log.info("Running diaSource measurement: newDipoleFitting=%r", newDipoleFitting)
1034  if not newDipoleFitting:
1035  # Just fit dipole in diffim
1036  self.measurement.run(diaSources, detectionExposure)
1037  else:
1038  # Use (matched) template and science image (if avail.) to constrain dipole fitting
1039  if self.config.doSubtract and 'matchedExposure' in subtractRes.getDict():
1040  self.measurement.run(diaSources, detectionExposure, exposure,
1041  subtractRes.matchedExposure)
1042  else:
1043  self.measurement.run(diaSources, detectionExposure, exposure)
1044  if self.config.doApCorr:
1045  self.applyApCorr.run(
1046  catalog=diaSources,
1047  apCorrMap=detectionExposure.getInfo().getApCorrMap()
1048  )
1049 
1050  if self.config.doForcedMeasurement:
1051  # Run forced psf photometry on the PVI at the diaSource locations.
1052  # Copy the measured flux and error into the diaSource.
1053  forcedSources = self.forcedMeasurement.generateMeasCat(
1054  exposure, diaSources, detectionExposure.getWcs())
1055  self.forcedMeasurement.run(forcedSources, exposure, diaSources, detectionExposure.getWcs())
1056  mapper = afwTable.SchemaMapper(forcedSources.schema, diaSources.schema)
1057  mapper.addMapping(forcedSources.schema.find("base_PsfFlux_instFlux")[0],
1058  "ip_diffim_forced_PsfFlux_instFlux", True)
1059  mapper.addMapping(forcedSources.schema.find("base_PsfFlux_instFluxErr")[0],
1060  "ip_diffim_forced_PsfFlux_instFluxErr", True)
1061  mapper.addMapping(forcedSources.schema.find("base_PsfFlux_area")[0],
1062  "ip_diffim_forced_PsfFlux_area", True)
1063  mapper.addMapping(forcedSources.schema.find("base_PsfFlux_flag")[0],
1064  "ip_diffim_forced_PsfFlux_flag", True)
1065  mapper.addMapping(forcedSources.schema.find("base_PsfFlux_flag_noGoodPixels")[0],
1066  "ip_diffim_forced_PsfFlux_flag_noGoodPixels", True)
1067  mapper.addMapping(forcedSources.schema.find("base_PsfFlux_flag_edge")[0],
1068  "ip_diffim_forced_PsfFlux_flag_edge", True)
1069  for diaSource, forcedSource in zip(diaSources, forcedSources):
1070  diaSource.assign(forcedSource, mapper)
1071 
1072  # Match with the calexp sources if possible
1073  if self.config.doMatchSources:
1074  if selectSources is not None:
1075  # Create key,val pair where key=diaSourceId and val=sourceId
1076  matchRadAsec = self.config.diaSourceMatchRadius
1077  matchRadPixel = matchRadAsec/exposure.getWcs().getPixelScale().asArcseconds()
1078 
1079  srcMatches = afwTable.matchXy(selectSources, diaSources, matchRadPixel)
1080  srcMatchDict = dict([(srcMatch.second.getId(), srcMatch.first.getId()) for
1081  srcMatch in srcMatches])
1082  self.log.info("Matched %d / %d diaSources to sources",
1083  len(srcMatchDict), len(diaSources))
1084  else:
1085  self.log.warning("Src product does not exist; cannot match with diaSources")
1086  srcMatchDict = {}
1087 
1088  # Create key,val pair where key=diaSourceId and val=refId
1089  refAstromConfig = AstrometryConfig()
1090  refAstromConfig.matcher.maxMatchDistArcSec = matchRadAsec
1091  refAstrometer = AstrometryTask(refAstromConfig)
1092  astromRet = refAstrometer.run(exposure=exposure, sourceCat=diaSources)
1093  refMatches = astromRet.matches
1094  if refMatches is None:
1095  self.log.warning("No diaSource matches with reference catalog")
1096  refMatchDict = {}
1097  else:
1098  self.log.info("Matched %d / %d diaSources to reference catalog",
1099  len(refMatches), len(diaSources))
1100  refMatchDict = dict([(refMatch.second.getId(), refMatch.first.getId()) for
1101  refMatch in refMatches])
1102 
1103  # Assign source Ids
1104  for diaSource in diaSources:
1105  sid = diaSource.getId()
1106  if sid in srcMatchDict:
1107  diaSource.set("srcMatchId", srcMatchDict[sid])
1108  if sid in refMatchDict:
1109  diaSource.set("refMatchId", refMatchDict[sid])
1110 
1111  if self.config.doAddMetrics and self.config.doSelectSources:
1112  self.log.info("Evaluating metrics and control sample")
1113 
1114  kernelCandList = []
1115  for cell in subtractRes.kernelCellSet.getCellList():
1116  for cand in cell.begin(False): # include bad candidates
1117  kernelCandList.append(cand)
1118 
1119  # Get basis list to build control sample kernels
1120  basisList = kernelCandList[0].getKernel(KernelCandidateF.ORIG).getKernelList()
1121  nparam = len(kernelCandList[0].getKernel(KernelCandidateF.ORIG).getKernelParameters())
1122 
1123  controlCandList = (
1124  diffimTools.sourceTableToCandidateList(controlSources,
1125  subtractRes.warpedExposure, exposure,
1126  self.config.subtract.kernel.active,
1127  self.config.subtract.kernel.active.detectionConfig,
1128  self.log, doBuild=True, basisList=basisList))
1129 
1130  KernelCandidateQa.apply(kernelCandList, subtractRes.psfMatchingKernel,
1131  subtractRes.backgroundModel, dof=nparam)
1132  KernelCandidateQa.apply(controlCandList, subtractRes.psfMatchingKernel,
1133  subtractRes.backgroundModel)
1134 
1135  if self.config.doDetection:
1136  KernelCandidateQa.aggregate(selectSources, self.metadata, allresids, diaSources)
1137  else:
1138  KernelCandidateQa.aggregate(selectSources, self.metadata, allresids)
1139 
1140  self.runDebug(exposure, subtractRes, selectSources, kernelSources, diaSources)
1141  return pipeBase.Struct(
1142  subtractedExposure=subtractedExposure,
1143  scoreExposure=scoreExposure,
1144  warpedExposure=subtractRes.warpedExposure,
1145  matchedExposure=subtractRes.matchedExposure,
1146  subtractRes=subtractRes,
1147  diaSources=diaSources,
1148  selectSources=selectSources
1149  )
1150 
1151  def fitAstrometry(self, templateSources, templateExposure, selectSources):
1152  """Fit the relative astrometry between templateSources and selectSources
1153 
1154  Todo
1155  ----
1156 
1157  Remove this method. It originally fit a new WCS to the template before calling register.run
1158  because our TAN-SIP fitter behaved badly for points far from CRPIX, but that's been fixed.
1159  It remains because a subtask overrides it.
1160  """
1161  results = self.register.run(templateSources, templateExposure.getWcs(),
1162  templateExposure.getBBox(), selectSources)
1163  return results
1164 
1165  def runDebug(self, exposure, subtractRes, selectSources, kernelSources, diaSources):
1166  """Make debug plots and displays.
1167 
1168  Todo
1169  ----
1170  Test and update for current debug display and slot names
1171  """
1172  import lsstDebug
1173  display = lsstDebug.Info(__name__).display
1174  showSubtracted = lsstDebug.Info(__name__).showSubtracted
1175  showPixelResiduals = lsstDebug.Info(__name__).showPixelResiduals
1176  showDiaSources = lsstDebug.Info(__name__).showDiaSources
1177  showDipoles = lsstDebug.Info(__name__).showDipoles
1178  maskTransparency = lsstDebug.Info(__name__).maskTransparency
1179  if display:
1180  disp = afwDisplay.getDisplay(frame=lsstDebug.frame)
1181  if not maskTransparency:
1182  maskTransparency = 0
1183  disp.setMaskTransparency(maskTransparency)
1184 
1185  if display and showSubtracted:
1186  disp.mtv(subtractRes.subtractedExposure, title="Subtracted image")
1187  mi = subtractRes.subtractedExposure.getMaskedImage()
1188  x0, y0 = mi.getX0(), mi.getY0()
1189  with disp.Buffering():
1190  for s in diaSources:
1191  x, y = s.getX() - x0, s.getY() - y0
1192  ctype = "red" if s.get("flags_negative") else "yellow"
1193  if (s.get("base_PixelFlags_flag_interpolatedCenter")
1194  or s.get("base_PixelFlags_flag_saturatedCenter")
1195  or s.get("base_PixelFlags_flag_crCenter")):
1196  ptype = "x"
1197  elif (s.get("base_PixelFlags_flag_interpolated")
1198  or s.get("base_PixelFlags_flag_saturated")
1199  or s.get("base_PixelFlags_flag_cr")):
1200  ptype = "+"
1201  else:
1202  ptype = "o"
1203  disp.dot(ptype, x, y, size=4, ctype=ctype)
1204  lsstDebug.frame += 1
1205 
1206  if display and showPixelResiduals and selectSources:
1207  nonKernelSources = []
1208  for source in selectSources:
1209  if source not in kernelSources:
1210  nonKernelSources.append(source)
1211 
1212  diUtils.plotPixelResiduals(exposure,
1213  subtractRes.warpedExposure,
1214  subtractRes.subtractedExposure,
1215  subtractRes.kernelCellSet,
1216  subtractRes.psfMatchingKernel,
1217  subtractRes.backgroundModel,
1218  nonKernelSources,
1219  self.subtract.config.kernel.active.detectionConfig,
1220  origVariance=False)
1221  diUtils.plotPixelResiduals(exposure,
1222  subtractRes.warpedExposure,
1223  subtractRes.subtractedExposure,
1224  subtractRes.kernelCellSet,
1225  subtractRes.psfMatchingKernel,
1226  subtractRes.backgroundModel,
1227  nonKernelSources,
1228  self.subtract.config.kernel.active.detectionConfig,
1229  origVariance=True)
1230  if display and showDiaSources:
1231  flagChecker = SourceFlagChecker(diaSources)
1232  isFlagged = [flagChecker(x) for x in diaSources]
1233  isDipole = [x.get("ip_diffim_ClassificationDipole_value") for x in diaSources]
1234  diUtils.showDiaSources(diaSources, subtractRes.subtractedExposure, isFlagged, isDipole,
1235  frame=lsstDebug.frame)
1236  lsstDebug.frame += 1
1237 
1238  if display and showDipoles:
1239  DipoleAnalysis().displayDipoles(subtractRes.subtractedExposure, diaSources,
1240  frame=lsstDebug.frame)
1241  lsstDebug.frame += 1
1242 
1243  def _getConfigName(self):
1244  """Return the name of the config dataset
1245  """
1246  return "%sDiff_config" % (self.config.coaddName,)
1247 
1248  def _getMetadataName(self):
1249  """Return the name of the metadata dataset
1250  """
1251  return "%sDiff_metadata" % (self.config.coaddName,)
1252 
1253  def getSchemaCatalogs(self):
1254  """Return a dict of empty catalogs for each catalog dataset produced by this task."""
1255  return {self.config.coaddName + "Diff_diaSrc": self.outputSchema}
1256 
1257  @classmethod
1258  def _makeArgumentParser(cls):
1259  """Create an argument parser
1260  """
1261  parser = pipeBase.ArgumentParser(name=cls._DefaultName)
1262  parser.add_id_argument("--id", "calexp", help="data ID, e.g. --id visit=12345 ccd=1,2")
1263  parser.add_id_argument("--templateId", "calexp", doMakeDataRefList=True,
1264  help="Template data ID in case of calexp template,"
1265  " e.g. --templateId visit=6789")
1266  return parser
1267 
1268 
1269 class Winter2013ImageDifferenceConfig(ImageDifferenceConfig):
1270  winter2013WcsShift = pexConfig.Field(dtype=float, default=0.0,
1271  doc="Shift stars going into RegisterTask by this amount")
1272  winter2013WcsRms = pexConfig.Field(dtype=float, default=0.0,
1273  doc="Perturb stars going into RegisterTask by this amount")
1274 
1275  def setDefaults(self):
1276  ImageDifferenceConfig.setDefaults(self)
1277  self.getTemplate.retarget(GetCalexpAsTemplateTask)
1278 
1279 
1280 class Winter2013ImageDifferenceTask(ImageDifferenceTask):
1281  """!Image difference Task used in the Winter 2013 data challege.
1282  Enables testing the effects of registration shifts and scatter.
1283 
1284  For use with winter 2013 simulated images:
1285  Use --templateId visit=88868666 for sparse data
1286  --templateId visit=22222200 for dense data (g)
1287  --templateId visit=11111100 for dense data (i)
1288  """
1289  ConfigClass = Winter2013ImageDifferenceConfig
1290  _DefaultName = "winter2013ImageDifference"
1291 
1292  def __init__(self, **kwargs):
1293  ImageDifferenceTask.__init__(self, **kwargs)
1294 
1295  def fitAstrometry(self, templateSources, templateExposure, selectSources):
1296  """Fit the relative astrometry between templateSources and selectSources"""
1297  if self.config.winter2013WcsShift > 0.0:
1298  offset = geom.Extent2D(self.config.winter2013WcsShift,
1299  self.config.winter2013WcsShift)
1300  cKey = templateSources[0].getTable().getCentroidSlot().getMeasKey()
1301  for source in templateSources:
1302  centroid = source.get(cKey)
1303  source.set(cKey, centroid + offset)
1304  elif self.config.winter2013WcsRms > 0.0:
1305  cKey = templateSources[0].getTable().getCentroidSlot().getMeasKey()
1306  for source in templateSources:
1307  offset = geom.Extent2D(self.config.winter2013WcsRms*numpy.random.normal(),
1308  self.config.winter2013WcsRms*numpy.random.normal())
1309  centroid = source.get(cKey)
1310  source.set(cKey, centroid + offset)
1311 
1312  results = self.register.run(templateSources, templateExposure.getWcs(),
1313  templateExposure.getBBox(), selectSources)
1314  return results
def run(self, skyInfo, tempExpRefList, imageScalerList, weightList, altMaskList=None, mask=None, supplementaryData=None)