26from astropy.stats
import gaussian_sigma_to_fwhm
42from lsst.images
import (
45 DifferenceImageTemplateInfo,
46 DifferenceImageTemplateInput,
51 get_legacy_optional_mask_planes,
52 get_legacy_template_mask_planes,
54from lsst.skymap
import BaseSkyMap
57 checkTemplateIsSufficient,
62from lsst.meas.algorithms
import CoaddPsf, CoaddPsfConfig, SubtractBackgroundTask, ScaleVarianceTask
63from lsst.utils.timer
import timeMethod
69 "GetDcrTemplateConfig",
73"""Width, in N sigma, of the Gaussian approximation to the CoaddPsf."""
75_UNKNOWN_INSTRUMENT =
"UNKNOWN"
76"""Instrument recorded for a coadd or template made from observations of an
80_FOOTPRINT_MARGIN = 32.0
81"""Distance, in coadd pixels, by which the science image's footprint in a
82coadd is grown before a coadd input is clipped to it. It must exceed twice
83the distance by which a distorted science image edge departs from a straight
84line between its corners, and limits how far outside the science image its
90 """Return a chainable transformation between two pixel frames.
94 fromWcs, toWcs : `lsst.afw.geom.SkyWcs`
95 WCSs of the input and output pixels.
99 transform : `lsst.images.Transform`
100 Transform from ``fromWcs`` pixels to ``toWcs`` pixels.
103 GeneralFrame(unit=astropy.units.pix),
104 GeneralFrame(unit=astropy.units.pix)
108def _getImageOverlap(record, coaddWcs, scienceFootprint, coaddToScienceTransform, scienceBox, border):
109 """Return the region enclosing the overlap of the science image and one
110 input image of the coadd.
112 Note that there are three different WCS's involved here: the WCS of the
113 original image that was warped to contribute to the coadd, the coadd WCS,
114 and the current science image WCS that we are building a template for.
118 record : `lsst.afw.table.ExposureRecord`
119 Input record of a coadd, with the input's WCS, bounding box and
120 optional valid polygon.
121 coaddWcs : `lsst.afw.geom.SkyWcs`
123 scienceFootprint : `lsst.images.Region`
124 ``scienceBox`` in coadd pixels, grown by ``_FOOTPRINT_MARGIN``.
125 coaddToScienceTransform : `lsst.images.Transform`
126 Transform from coadd pixels to science image pixels.
127 scienceBox : `lsst.images.Box`
128 Bounding box of the science image.
130 Width, in input pixels, of the border of the input that warping left
135 footprint : `lsst.images.Polygon` or `None`
136 The part of ``scienceBox`` the input's warp covers, in science image
137 pixels, or `None` if it covers none of it.
140 inputBox.grow(-border)
141 inputBounds = Polygon.from_legacy(afwGeom.Polygon(inputBox))
142 polygon = record.getValidPolygon()
145 if polygon
is not None:
146 inputBounds = inputBounds.intersection(Polygon.from_legacy(polygon))
150 inputBounds.transform(inputToCoadd)
151 .intersection(scienceFootprint)
152 .transform(coaddToScienceTransform)
155 footprint = footprint.convex_hull().intersection(scienceBox)
156 except NoOverlapError:
158 return Polygon.from_box(footprint)
if isinstance(footprint, Box)
else footprint
162 """Return the width of the border of an image that warping leaves out.
164 A warped pixel is computed only where the whole kernel lies on the image.
169 Name of the warping kernel, as `lsst.afw.math.Warper` takes it.
174 Width of the border on each side, in pixels from the edge of the
175 image's bounding box; 2.5 for ``lanczos3``.
178 return kernel.getCtr().getX() + 0.5
183 """Compute the phase-averaged sum of squared values of a warping kernel.
185 Warping with a kernel normalized to unit sum multiplies the variance by
186 this sum, which is less than one. The power the warp took off the
187 diagonal became covariance between neighboring pixels, which a variance
188 plane cannot represent, so dividing by it restores the noise power: the
189 variance of a flux measured over a region and not a single pixel.
194 Name of the warping kernel, as `lsst.afw.math.Warper` takes it.
195 nPhase : `int`, optional
196 Number of sub-pixel phases to average over.
201 Sum of the squared 2-D kernel values, averaged over sub-pixel
202 phase. Converges with large ``nPhase`` to 0.798 for ``lanczos3``,
203 4/9 for ``bilinear``, and 1 for no interpolation.
207 The kernels are separable and the phases of the two axes independent,
208 so this is the square of the 1-D average. The warper normalizes the
209 kernel to unit sum at each phase, which the analytic Lanczos integral
210 does not include, so the average is computed from the kernel itself.
214 kernel = afwMath.Warper(kernelName, cacheSize=0).getWarpingKernel()
215 image = afwImage.ImageD(kernel.getDimensions())
217 for phase
in (np.arange(nPhase) + 0.5)/nPhase:
218 kernel.setKernelParameters((float(phase), 0.0))
219 kernel.computeImage(image, doNormalize=
True)
220 total += float((image.array.sum(axis=0)**2).sum())
221 return (total/nPhase)**2
225 pipeBase.PipelineTaskConnections,
226 dimensions=(
"instrument",
"visit",
"detector"),
227 defaultTemplates={
"coaddName":
"goodSeeing",
"warpTypeSuffix":
"",
"fakesType":
""},
229 bbox = pipeBase.connectionTypes.Input(
230 doc=
"Bounding box of exposure to determine the geometry of the output template.",
231 name=
"{fakesType}calexp.bbox",
232 storageClass=
"Box2I",
233 dimensions=(
"instrument",
"visit",
"detector"),
234 deprecated=
"Replaced by the `detector` connection. Will be removed after v31.",
236 detector = pipeBase.connectionTypes.Input(
237 doc=
"Detector of the exposure that we will construct the template for."
238 " Its bounding box sets the geometry of the output template.",
239 name=
"{fakesType}calexp.detector",
240 storageClass=
"Detector",
241 dimensions=(
"instrument",
"visit",
"detector"),
243 obs_info = pipeBase.connectionTypes.Input(
244 doc=
"Observation metadata of the exposure the template is built for."
245 " Only read with output_image_type='future', which needs this to set"
246 " the obs_info component of a lsst.images.VisitImage.",
247 name=
"{fakesType}calexp.obs_info",
248 storageClass=
"ObservationInfo",
249 dimensions=(
"instrument",
"visit",
"detector"),
251 wcs = pipeBase.connectionTypes.Input(
252 doc=
"WCS of the exposure that we will construct the template for.",
253 name=
"{fakesType}calexp.wcs",
255 dimensions=(
"instrument",
"visit",
"detector"),
257 skyMap = pipeBase.connectionTypes.Input(
258 doc=
"Geometry of the tracts and patches that the coadds are defined on.",
259 name=BaseSkyMap.SKYMAP_DATASET_TYPE_NAME,
260 dimensions=(
"skymap",),
261 storageClass=
"SkyMap",
263 coaddExposures = pipeBase.connectionTypes.Input(
264 doc=
"Coadds that may overlap the desired region, as possible inputs to the template."
265 " Will be restricted to those that directly overlap the projected bounding box.",
266 dimensions=(
"tract",
"patch",
"skymap",
"band"),
267 storageClass=
"ExposureF",
268 name=
"{fakesType}{coaddName}Coadd{warpTypeSuffix}",
271 deferGraphConstraint=
True,
274 template = pipeBase.connectionTypes.Output(
275 doc=
"Warped template, pixel matched to the bounding box and WCS.",
276 dimensions=(
"instrument",
"visit",
"detector"),
277 storageClass=
"ExposureF",
278 name=
"{fakesType}{coaddName}Diff_templateExp{warpTypeSuffix}",
281 def __init__(self, *, config=None):
282 super().__init__(config=config)
285 if config.requireCoaddAtGraphBuild:
286 self.coaddExposures = dataclasses.replace(
288 deferGraphConstraint=
False,
290 if config.output_image_type ==
"future":
291 self.template = dataclasses.replace(self.template, storageClass=
"DifferenceImage")
296class GetTemplateConfig(
297 pipeBase.PipelineTaskConfig, pipelineConnections=GetTemplateConnections
299 templateBorderSize = pexConfig.Field(
302 doc=
"Number of pixels to grow the requested template image to account for warping",
304 warp = pexConfig.ConfigField(
305 dtype=afwMath.Warper.ConfigClass,
306 doc=
"warper configuration",
308 doCorrectVarianceWarpCorrelation = pexConfig.Field(
311 doc=
"Correct the template variance for the correlation that warping"
312 " introduced between neighboring pixels? This covers both warps: the"
313 " one that built the coadds, named by coaddWarpKernel, and the one"
314 " this task performs, named by warp.warpingKernelName. It is a single"
315 " scalar factor, fixed entirely by those two kernels and independent"
316 " of the pixel scales involved.",
318 coaddWarpKernel = pexConfig.ChoiceField(
322 "bilinear":
"bilinear interpolation",
323 "lanczos3":
"Lanczos kernel of order 3",
324 "lanczos4":
"Lanczos kernel of order 4",
325 "lanczos5":
"Lanczos kernel of order 5",
327 doc=
"Warping kernel that was used to build the input coadds. This"
328 " cannot be recovered from the coadds themselves. It is used to"
329 " correct the variance if doCorrectVarianceWarpCorrelation is True,"
330 " and to trim the coadd inputs bboxes to account for the size of the"
333 coaddPsf = pexConfig.ConfigField(
334 doc=
"Configuration for CoaddPsf",
335 dtype=CoaddPsfConfig,
337 fwhmExposureGrid = pexConfig.Field(
338 doc=
"Grid size to compute the average PSF FWHM in an exposure (pixels)",
342 fwhmExposureBuffer = pexConfig.Field(
343 doc=
"Fractional buffer margin to be left out of all sides of the image during construction"
344 " of grid to compute average PSF FWHM in an exposure",
348 minTemplateFractionForExpectedSuccess = pexConfig.Field(
349 doc=
"Raise NoWorkFound if the template PSF cannot be evaluated and less than this fraction"
350 " of the template pixels have data. With more coverage, the PSF error is raised.",
354 varianceBackground = pexConfig.ConfigurableField(
355 target=SubtractBackgroundTask,
356 doc=
"Task to estimate the background variance.",
358 highVarianceThreshold = pexConfig.RangeField(
362 doc=
"Set the HIGH_VARIANCE mask plane for regions with variance"
363 " greater than the median by this factor.",
365 highVarianceMaskFraction = pexConfig.Field(
368 doc=
"Minimum fraction of unmasked pixels needed to set the"
369 " HIGH_VARIANCE mask plane.",
371 doScaleVariance = pexConfig.Field(
374 doc=
"Scale the variance of the template image to match its per-pixel"
375 " scatter? Warping correlates the noise, so when combined with"
376 " doCorrectVarianceWarpCorrelation this overcounts the correction.",
378 scaleVariance = pexConfig.ConfigurableField(
379 target=ScaleVarianceTask,
380 doc=
"Subtask to rescale the variance of the template to the statistically expected level."
382 requireCoaddAtGraphBuild = pexConfig.Field(
385 doc=
"If True, include the coadd dataset existence in the"
386 " initial butler query during QuantumGraph generation.",
388 output_image_type = pexConfig.ChoiceField[str](
389 "Which image type to use for the output template.",
391 "legacy":
"Write as a lsst.afw.image.ExposureF.",
392 "future":
"Write as a lsst.images.DifferenceImage.",
397 raiseOnUndefinedMaskMap = pexConfig.Field(
400 doc=
"Raise if the template has pixels set in a mask plane that"
401 " `lsst.images` does not map? If False, log a warning and drop that"
402 " plane from the output instead."
403 " Only used with output_image_type='future'.",
409 self.warp.cacheSize = 100000
410 self.coaddPsf.cacheSize = self.warp.cacheSize
413 self.warp.interpLength = 100
414 self.warp.warpingKernelName =
"lanczos3"
415 self.coaddPsf.warpingKernelName = self.warp.warpingKernelName
418 self.varianceBackground.algorithm =
"LINEAR"
419 self.varianceBackground.binSize = 32
420 self.varianceBackground.useApprox =
False
421 self.varianceBackground.statisticsProperty =
"MEDIAN"
422 self.varianceBackground.doFilterSuperPixels =
True
423 self.varianceBackground.ignoredPixelMask = [
"BAD",
432 ConfigClass = GetTemplateConfig
433 _DefaultName =
"getTemplate"
437 if self.config.doScaleVariance:
438 self.makeSubtask(
"scaleVariance")
439 self.
warper = afwMath.Warper.fromConfig(self.config.warp)
440 self.
schema = afwTable.ExposureTable.makeMinimalSchema()
442 "tract", type=np.int32, doc=
"Which tract this exposure came from."
447 doc=
"Which patch in the tract this exposure came from.",
452 doc=
"Weight for each exposure, used to make the CoaddPsf; should always be 1.",
458 doc=
"Instrument whose observations were coadded to make the template, or UNKNOWN.",
460 self.makeSubtask(
"varianceBackground")
463 inputs = butlerQC.get(inputRefs)
464 detector = inputs.pop(
"detector")
465 bbox = detector.getBBox()
466 wcs = inputs.pop(
"wcs")
467 obsInfo = inputs.pop(
"obs_info",
None)
468 coaddExposures = inputs.pop(
"coaddExposures")
469 skymap = inputs.pop(
"skyMap")
472 assert not inputs,
"runQuantum got more inputs than expected"
474 results = self.
getExposures(coaddExposures, bbox, skymap, wcs)
475 physical_filter = butlerQC.quantum.dataId[
"physical_filter"]
477 coaddExposureHandles=results.coaddExposures,
480 dataIds=results.dataIds,
481 physical_filter=physical_filter,
482 visit=outputRefs.template.dataId[
"visit"],
483 instrument=butlerQC.quantum.dataId[
"instrument"],
485 if self.config.output_image_type ==
"future":
486 dataId = butlerQC.quantum.dataId
487 exposureRecord = record_from_obs_info(obsInfo, dataId[
"instrument"], dataId[
"visit"],
490 inputRefs.coaddExposures,
492 exposureRecord=exposureRecord,
493 templateInputs=outputs.templateInputs)
494 butlerQC.put(outputs, outputRefs)
497 templateInputs=None):
498 """Convert a template image to DifferenceImage format.
500 This replaces ``template`` with an `lsst.images.DifferenceImage`
501 instance and records the coadds contributed to it, along with the
502 instrument they were made from and their input image identifiers.
503 The Gaussian PSF set by `run` is converted to an
504 `lsst.images.psfs.GaussianPointSpreadFunction`.
508 template : `lsst.afw.image.Exposure`
509 Template to convert. Its detector is replaced with ``detector``
510 and its mask is modified in place.
511 coadd_refs : `list` [`lsst.daf.butler.DatasetRef`]
512 References to the coadds that may have gone into the template.
513 May be a superset of the coadds that were used; supplies the
514 dataset id and RUN collection recorded for each coadd that was.
515 detector : `lsst.afw.cameraGeom.Detector`
516 Detector of the science image that the template was built for.
517 exposureRecord : `lsst.daf.butler.DimensionRecord`
518 The ``exposure`` record of the observation the template was built
519 for, which supplies the observation metadata recorded on the
521 templateInputs : `dict` [`tuple` [`int`, `int`], \
522 `list` [`lsst.images.DifferenceImageTemplateInput`]], optional
523 Input image records of each coadd, keyed by tract and patch, as
524 returned by `run`. Coadds not listed record no inputs.
528 convertedTemplate : `lsst.images.DifferenceImage`
534 Raised if the template has pixels set in a mask plane that
535 `lsst.images.get_legacy_template_mask_planes` does not map and
536 ``config.raiseOnUndefinedMaskMap`` is True, or if ``coadd_refs``
537 spans more than one skymap.
541 catalog = template.getInfo().getCoaddInputs().ccds
542 coaddPsf = self.
_makePsf(template, catalog, template.getWcs())
544 instrument = catalog[0][
"instrument"]
545 template.setDetector(detector)
546 skymaps = {ref.dataId[
"skymap"]
for ref
in coadd_refs}
547 if len(skymaps) != 1:
548 raise RuntimeError(
"Expected the template inputs to come from one skymap;"
549 f
" got {sorted(skymaps)}.")
550 butler_info = {(ref.dataId[
"tract"], ref.dataId[
"patch"]): (ref.id, ref.run)
551 for ref
in coadd_refs}
552 planeMap = get_legacy_template_mask_planes()
553 if not self.config.raiseOnUndefinedMaskMap:
555 convertedTemplate = DifferenceImage.from_legacy(
557 exposure_record=exposureRecord,
558 unit=astropy.units.nJy,
562 convertedTemplate.templates = DifferenceImageTemplateInfo.from_legacy_psf(
563 convertedTemplate.sky_projection.pixel_frame,
568 instrument=instrument,
571 for info
in convertedTemplate.templates:
572 info.inputs = templateInputs.get((info.tract, info.patch), [])
573 return convertedTemplate
576 """Clear the pixels of every mask plane that conversion would reject.
580 mask : `lsst.afw.image.Mask`
581 Template mask to modify in place.
582 planeMap : `dict` [`str`, `lsst.images.MaskPlane`]
583 Plane map the template will be converted with. The optional
584 planes of `lsst.images.get_legacy_optional_mask_planes` are kept
585 as well, since conversion adds them when they have pixels set.
587 keep = planeMap.keys() | get_legacy_optional_mask_planes().keys()
588 for name
in mask.getMaskPlaneDict():
591 bitmask = mask.getPlaneBitMask(name)
592 nSet = np.count_nonzero(mask.array & bitmask)
594 self.
log.warning(
"Dropping mask plane %s from the template: %d pixels are set, but"
595 " the template plane map does not include it.", name, nSet)
596 mask.array &= ~bitmask
599 """Return a data structure containing the coadds that overlap the
600 specified bbox projected onto the sky, and a corresponding data
601 structure of their dataIds.
602 These are the appropriate inputs to this task's `run` method.
604 The spatial index in the butler registry has generous padding and often
605 supplies patches near, but not directly overlapping the desired region.
606 This method filters the inputs so that `run` does not have to read in
607 all possibly-matching coadd exposures.
611 coaddExposureHandles : `iterable` \
612 [`lsst.daf.butler.DeferredDatasetHandle` of \
613 `lsst.afw.image.Exposure`]
614 Dataset handles to exposures that might overlap the desired
616 bbox : `lsst.geom.Box2I`
617 Template bounding box of the pixel geometry onto which the
618 coaddExposures will be resampled.
619 skymap : `lsst.skymap.SkyMap`
620 Geometry of the tracts and patches the coadds are defined on.
621 wcs : `lsst.afw.geom.SkyWcs`
622 Template WCS onto which the coadds will be resampled.
626 result : `lsst.pipe.base.Struct`
627 A struct with attributes:
630 Dict of coadd exposures that overlap the projected bbox,
632 (`dict` [`int`, `list` [`lsst.daf.butler.DeferredDatasetHandle` of
633 `lsst.afw.image.Exposure`] ]).
635 Dict of data IDs of the coadd exposures that overlap the
636 projected bbox, indexed on tract id
637 (`dict` [`int`, `list [`lsst.daf.butler.DataCoordinate`] ]).
642 Raised if no patches overlap the input detector bbox, or the input
646 raise pipeBase.NoWorkFound(
647 "WCS is None; cannot find overlapping exposures."
652 detectorCorners = wcs.pixelToSky(detectorPolygon.getCorners())
654 coaddExposures = collections.defaultdict(list)
655 dataIds = collections.defaultdict(list)
657 for coaddRef
in coaddExposureHandles:
658 dataId = coaddRef.dataId
659 patchWcs = skymap[dataId[
"tract"]].getWcs()
660 patchBBox = skymap[dataId[
"tract"]][dataId[
"patch"]].getOuterBBox()
661 patchPolygon = afwGeom.Polygon(
geom.Box2D(patchBBox))
666 detectorInPatchCoordinates = afwGeom.Polygon(patchWcs.skyToPixel(detectorCorners))
667 if patchPolygon.intersection(detectorInPatchCoordinates):
668 overlappingArea += patchPolygon.intersectionSingle(
669 detectorInPatchCoordinates
672 "Using template input tract=%s, patch=%s",
676 coaddExposures[dataId[
"tract"]].append(coaddRef)
677 dataIds[dataId[
"tract"]].append(dataId)
679 if not overlappingArea:
680 raise pipeBase.NoWorkFound(
"No patches overlap detector")
682 return pipeBase.Struct(coaddExposures=coaddExposures, dataIds=dataIds)
685 def run(self, *, coaddExposureHandles, bbox, wcs, dataIds, physical_filter, visit=None, instrument=None):
686 """Warp coadds from multiple tracts and patches to form a template to
687 subtract from a science image.
689 Tract and patch overlap regions are combined by a variance-weighted
690 average, and the variance planes are combined with the same weights,
691 not added in quadrature; the overlap regions are not statistically
692 independent, because they're derived from the same original data.
693 The PSF of the template is a Gaussian with the same width as the
694 CoaddPsf evaluated at the center of the detector.
696 The template is built from coadds of one instrument: the science
697 image's ``instrument`` if any coadd was made from it, and otherwise the
698 one that most of the coadds were made from. Coadds made from another
699 instrument are dropped, and so are coadds that record no instrument
700 unless none of the coadds records one.
704 coaddExposureHandles : `dict` [`int`, `list` of \
705 [`lsst.daf.butler.DeferredDatasetHandle` of \
706 `lsst.afw.image.Exposure`]]
707 Coadds to be mosaicked, indexed on tract id.
708 bbox : `lsst.geom.Box2I`
709 Input Bounding box of the detector geometry onto which to
710 resample the ``coaddExposureHandles``. The output template bbox
711 will be grown by ``templateBorderSize``.
712 wcs : `lsst.afw.geom.SkyWcs`
713 Template WCS onto which to resample the ``coaddExposureHandles``.
714 dataIds : `dict` [`int`, `list` [`lsst.daf.butler.DataCoordinate`]]
715 Record of the tract and patch of each coaddExposure, indexed on
717 physical_filter : `str`
718 Physical filter of the science image.
719 visit : `int`, optional
720 If supplied, over-write the visit ID in the template's visitInfo
721 so that downstream source injection tasks can link the template and
722 science image for the visit.
723 instrument : `str`, optional
724 Instrument of the science image. Coadds made from it are used in
725 preference to coadds from any other instrument.
729 result : `lsst.pipe.base.Struct`
730 A struct with attributes:
733 A template coadd exposure assembled out of patches, with
734 pixels in nJy. Its PSF is a Gaussian approximation to the
735 CoaddPsf of its inputs (`lsst.afw.image.ExposureF`).
737 Input image records of each coadd that cover part of the
738 science image, keyed by tract and patch (`dict`
739 [`tuple` [`int`, `int`],
740 `list` [`lsst.images.DifferenceImageTemplateInput`]]). Empty
741 unless ``config.output_image_type`` is ``"future"``.
746 If no coadds are found with sufficient un-masked pixels, or if the
747 template PSF cannot be evaluated and too few of the template pixels
749 lsst.afw.detection.InvalidPsfError
750 If the template PSF cannot be evaluated and the template has
751 enough coverage that it was expected to succeed.
753 If the template is not known to be from the science image's
754 instrument and no coadd records the plate scale of its input
755 images, so the template variance cannot be corrected.
757 band, photoCalib, templateInstrument = self.
_checkInputs(dataIds, coaddExposureHandles, instrument)
761 bbox.grow(self.config.templateBorderSize)
766 plateScaleFactor = 1.0
if instrument == templateInstrument
else None
768 for tract
in coaddExposureHandles:
770 coaddExposureHandles[tract], dataIds[tract], templateInstrument
772 if len(catalog) == 0:
779 if plateScaleFactor
is None:
781 warpedBox = computeWarpedBBox(catalog[0].wcs, bbox, wcs)
784 unwarped, count, included = self.
_merge(
785 maskedImages, warpedBox, catalog[0].wcs
791 "No valid pixels from coadd patches in tract %s; not including in output.",
795 warpedBox.clip(totalBox)
796 potentialInput = self.
warper.warpExposure(
797 wcs, unwarped.subset(warpedBox), destBBox=bbox
802 potentialInput.mask.array
803 & potentialInput.mask.getPlaneBitMask(
"NO_DATA")
806 "No overlap from coadd patches in tract %s; not including in output.",
812 tempCatalog = afwTable.ExposureCatalog(self.
schema)
813 tempCatalog.reserve(len(included))
815 tempCatalog.append(catalog[i])
816 inputs.append(coaddInputs[i])
817 catalogs.append(tempCatalog)
818 warped[tract] = potentialInput.maskedImage
821 raise pipeBase.NoWorkFound(
"No patches found to overlap science exposure.")
824 template, count, _ = self.
_merge(warped, bbox, wcs)
826 raise pipeBase.NoWorkFound(
"No valid pixels in warped template.")
828 if self.config.doScaleVariance:
832 varianceFactor = self.scaleVariance.
run(template.maskedImage)
833 self.
log.info(
"Template variance scaling factor: %.2f", varianceFactor)
834 self.metadata[
"scaleTemplateVarianceFactor"] = varianceFactor
839 catalog = afwTable.ExposureCatalog(self.
schema)
840 catalog.reserve(sum([len(c)
for c
in catalogs]))
844 if self.config.output_image_type ==
"future":
851 if visit
is not None:
852 template.getInfo().setVisitInfo(
VisitInfo(id=visit))
855 if photoCalib
is not None and photoCalib != identity:
856 template.maskedImage = photoCalib.calibrateImage(template.maskedImage)
857 photoCalib = identity
858 template.setPhotoCalib(photoCalib)
859 template.setPsf(self.
_makePsf(template, catalog, wcs))
862 except afwDetection.InvalidPsfError
as e:
864 checkTemplateIsSufficient(
866 requiredTemplateFraction=self.config.minTemplateFractionForExpectedSuccess,
867 exceptionMessage=
"Template coverage lower than expected to succeed."
868 f
" Failure is tolerable: {e}"
876 coaddInputs.ccds.extend(catalog, deep=
True)
877 template.getInfo().setCoaddInputs(coaddInputs)
878 return pipeBase.Struct(template=template, templateInputs=templateInputs)
881 """Correct the template variance plane for the effects of warping.
883 Warping introduces a covariance between neighboring pixels, while the
884 input variance plane captures only the diagonal term. Compute a
885 multiplicative correction factor to apply to the final variance so that
886 the detection significance on the convolved difference image is correct
889 Separately, also apply a scalar multiplicative correction factor to the
890 template variance if the plate scale of the coadd's constituent images
891 is different than the science image the template is being constructed
892 for. This should only be necessary if the coadd images were from a
893 different instrument than the science image, since the scale change
894 otherwise cancels between the two warps. If the plate scale of the
895 science instrument is smaller than the plate scale of the coadd
896 instrument, then the template pixels will be correlated and the true
897 variance will be higher than the image pixel noise level would suggest.
901 template : `lsst.afw.image.Exposure`
902 Assembled template; its variance plane is modified in place.
903 plateScaleFactor : `float` or `None`
904 Correction for the change in pixel area, from `_plateScaleFactor`.
909 Raised if ``plateScaleFactor`` is `None`.
911 if plateScaleFactor
is None:
913 "Could not determine the plate scale of the images the template coadds were made from,"
914 " so the template variance cannot be corrected for the change in pixel area."
916 self.metadata[
"variancePlateScaleFactor"] = plateScaleFactor
917 correlationFactor = 1.0
918 if self.config.doCorrectVarianceWarpCorrelation:
923 self.metadata[
"varianceWarpCorrelationFactor"] = correlationFactor
924 scale = correlationFactor*plateScaleFactor
927 template.variance.array *= scale
928 self.metadata[
"templateVarianceCorrectionFactor"] = scale
930 "Variance correction factor due to plate scale changes: %.4f",
934 "Variance correction factor due to warping correlations: %.4f",
938 "Overall template variance correction factor: %.4f",
943 """Compute the variance correction for the total change in pixel area
944 between the coadd's constituent images and the science image.
948 coaddInputs : `lsst.afw.image.CoaddInputs` or `None`
949 Input records of one of the coadd patches.
950 wcs : `lsst.afw.geom.SkyWcs`
951 WCS of the science image the template is being built for.
952 bbox : `lsst.geom.Box2I`
953 Bounding box of the template, used only to choose where to
954 evaluate the science image pixel scale.
958 factor : `float` or `None`
959 The correction factor equivalent to the ratio of the area of a pixel
960 from the coadd's instrument to the science instrument, or `None` if
961 this patch carries no input record from which it could be computed.
963 if coaddInputs
is None:
965 scienceScale = wcs.getPixelScale(
geom.Box2D(bbox).getCenter()).asArcseconds()
967 for record
in coaddInputs.ccds:
970 originalWcs = record.getWcs()
971 if originalWcs
is None:
973 center =
geom.Box2D(record.getBBox()).getCenter()
974 pviScale = originalWcs.getPixelScale(center).asArcseconds()
976 factor = (pviScale/scienceScale)**2
977 if np.isfinite(factor)
and factor > 0:
982 """Find the input images and epochs of each coadd in the template.
986 catalog : `lsst.afw.table.ExposureCatalog`
987 Coadds the template was built from, with their tract, patch and
989 coaddInputs : `list` [`lsst.afw.image.CoaddInputs` or `None`]
990 Input records of each coadd in ``catalog``, in the same order.
991 wcs : `lsst.afw.geom.SkyWcs`
992 WCS of the science image.
993 bbox : `lsst.geom.Box2I`
994 Bounding box of the science image.
998 templateInputs : `dict` [`tuple` [`int`, `int`], \
999 `list` [`lsst.images.DifferenceImageTemplateInput`]]
1000 Inputs of each coadd that cover part of the science image, keyed
1001 by tract and patch, with the part their warps cover in science
1004 scienceBox = Box.from_legacy(bbox)
1008 for coadd, coaddInput
in zip(catalog, coaddInputs, strict=
True):
1009 coaddList = templateInputs.setdefault((coadd[
"tract"], coadd[
"patch"]), [])
1010 if coaddInput
is None:
1013 scienceFootprint = scienceBox.transform(scienceToCoadd).dilated_by(_FOOTPRINT_MARGIN)
1014 coaddToScience = scienceToCoadd.inverted()
1015 for record
in coaddInput.ccds:
1016 visitInfo = record.getVisitInfo()
1017 weight = record[
"weight"]
1018 if visitInfo
is None or not visitInfo.getDate().isValid()
or not weight > 0:
1020 key = (record[
"visit"], record[
"ccd"])
1022 if key
not in regions:
1023 regions[key] =
_getImageOverlap(record, coadd.getWcs(), scienceFootprint, coaddToScience,
1025 region = regions[key]
1028 mjd = visitInfo.getDate().get(DateTime.MJD, DateTime.TAI)
1029 coaddList.append(DifferenceImageTemplateInput(visit=key[0], detector=key[1],
1030 mid_mjd_tai=mjd, weight=weight,
1032 return templateInputs
1035 """Set a mask plane for regions with unusually high variance.
1039 template : `lsst.afw.image.Exposure`
1040 The warped template exposure, which will be modified in place.
1042 highVarianceMaskPlaneBit = template.mask.addMaskPlane(
"HIGH_VARIANCE")
1043 ignoredPixelBits = template.mask.getPlaneBitMask(self.varianceBackground.config.ignoredPixelMask)
1044 goodMask = (template.mask.array & ignoredPixelBits) == 0
1045 goodFraction = np.count_nonzero(goodMask)/template.mask.array.size
1046 if goodFraction < self.config.highVarianceMaskFraction:
1047 self.
log.info(
"Not setting HIGH_VARIANCE mask plane, only %2.1f%% of"
1048 " pixels were unmasked for background estimation, but"
1049 " %2.1f%% are required", 100*goodFraction, 100*self.config.highVarianceMaskFraction)
1051 varianceExposure = template.clone()
1052 varianceExposure.image.array = varianceExposure.variance.array
1053 varianceBackground = self.varianceBackground.
run(varianceExposure).background.getImage().array
1054 threshold = self.config.highVarianceThreshold*np.nanmedian(varianceBackground)
1055 highVariancePix = varianceBackground > threshold
1056 template.mask.array[highVariancePix] |= 2**highVarianceMaskPlaneBit
1060 """Check that the all the dataIds are from the same band and that
1061 the exposures all have the same photometric calibration, and choose
1062 the instrument of the template.
1066 dataIds : `dict` [`int`, `list` [`lsst.daf.butler.DataCoordinate`]]
1067 Record of the tract and patch of each coaddExposure.
1068 coaddExposures : `dict` [`int`, `list` of \
1069 [`lsst.daf.butler.DeferredDatasetHandle` of \
1070 `lsst.afw.image.Exposure` or
1071 `lsst.afw.image.Exposure`]]
1072 Coadds to be mosaicked.
1073 scienceInstrument : `str`, optional
1074 Instrument of the science image.
1079 Filter band of all the input exposures.
1080 photoCalib : `lsst.afw.image.PhotoCalib`
1081 Photometric calibration of all of the input exposures.
1083 ``scienceInstrument`` if any coadd was made from it, otherwise the
1084 instrument that the most coadds were made from, or ``"UNKNOWN"`` if
1085 no coadd records one. A tie goes to the instrument whose name sorts
1091 Raised if the bands or calibrations of the input exposures are not
1094 bands = set(dataId[
"band"]
for tract
in dataIds
for dataId
in dataIds[tract])
1096 raise RuntimeError(f
"GetTemplateTask called with multiple bands: {bands}")
1099 instrumentCounts = collections.Counter()
1100 for exposures
in coaddExposures.values():
1101 for exposure
in exposures:
1104 photoCalibs.append(exposure.get(component=
"photoCalib"))
1105 instrumentCounts[GetTemplateTask._getInstrument(exposure.get(component=
"coaddInputs"))] += 1
1106 if not all([photoCalibs[0] == x
for x
in photoCalibs]):
1107 msg = f
"GetTemplateTask called with exposures with different photoCalibs: {photoCalibs}"
1108 raise RuntimeError(msg)
1109 photoCalib = photoCalibs[0]
1111 del instrumentCounts[_UNKNOWN_INSTRUMENT]
1112 if scienceInstrument
in instrumentCounts:
1113 return band, photoCalib, scienceInstrument
1114 if not instrumentCounts:
1115 return band, photoCalib, _UNKNOWN_INSTRUMENT
1116 instrument = max(sorted(instrumentCounts), key=instrumentCounts.get)
1117 return band, photoCalib, instrument
1121 """Return the instrument whose observations were coadded to make a
1126 coaddInputs : `lsst.afw.image.CoaddInputs` or `None`
1127 Input records of the coadd.
1132 Instrument label of the coadd, or ``"UNKNOWN"`` if it records none.
1136 Every input of a coadd comes from the same instrument, so the first
1137 input record stands for all of them.
1139 if coaddInputs
is None or len(coaddInputs.ccds) == 0:
1140 return _UNKNOWN_INSTRUMENT
1141 visitInfo = coaddInputs.ccds[0].getVisitInfo()
1142 label = visitInfo.getInstrumentLabel()
if visitInfo
is not None else ""
1143 return label
or _UNKNOWN_INSTRUMENT
1146 """Make an exposure catalog for one tract.
1150 exposureRefs : `list` of [`lsst.daf.butler.DeferredDatasetHandle` of \
1151 `lsst.afw.image.Exposure`]
1152 Exposures to include in the catalog.
1153 dataIds : `list` [`lsst.daf.butler.DataCoordinate`]
1154 Data ids of each of the included exposures; must have "tract" and
1156 instrument : `str`, optional
1157 Instrument of the template, recorded in the catalog. Exposures
1158 made from another instrument are dropped, as are exposures that
1159 record no instrument unless ``instrument`` is ``"UNKNOWN"``.
1163 images : `dict` [`lsst.afw.image.MaskedImage`]
1164 MaskedImages of each of the input exposures, for warping.
1165 catalog : `lsst.afw.table.ExposureCatalog`
1166 Catalog of metadata for each exposure
1167 totalBox : `lsst.geom.Box2I`
1168 The union of the bounding boxes of all the input exposures.
1169 coaddInputs : `list` [`lsst.afw.image.CoaddInputs` or `None`]
1170 Input records of each exposure in ``catalog``, in the same order.
1172 catalog = afwTable.ExposureCatalog(self.
schema)
1173 catalog.reserve(len(exposureRefs))
1174 exposures = (exposureRef.get()
for exposureRef
in exposureRefs)
1177 keptCoaddInputs = []
1179 for coadd, dataId
in zip(exposures, dataIds):
1180 coaddInputs = coadd.getInfo().getCoaddInputs()
1182 if coaddInstrument != instrument:
1184 "Dropping template coadd %s: it was made from %s, but the template is made from %s.",
1190 keptCoaddInputs.append(coaddInputs)
1191 images[dataId] = coadd.maskedImage
1192 bbox = coadd.getBBox()
1193 totalBox = totalBox.expandedTo(bbox)
1194 record = catalog.addNew()
1195 record.setPsf(coadd.psf)
1196 record.setWcs(coadd.wcs)
1197 record.setPhotoCalib(coadd.photoCalib)
1198 record.setBBox(bbox)
1199 record.setValidPolygon(afwGeom.Polygon(
geom.Box2D(bbox).getCorners()))
1200 record.set(
"tract", dataId[
"tract"])
1201 record.set(
"patch", dataId[
"patch"])
1202 record.set(
"instrument", instrument)
1205 record.set(
"weight", 1)
1207 return images, catalog, totalBox, keptCoaddInputs
1210 """Merge the images that came from one tract into one larger image,
1211 ignoring NaN pixels and non-finite variance pixels from individual
1216 maskedImages : `dict` [`lsst.afw.image.MaskedImage` or
1217 `lsst.afw.image.Exposure`]
1218 Images to be merged into one larger bounding box.
1219 bbox : `lsst.geom.Box2I`
1220 Bounding box defining the image to merge into.
1221 wcs : `lsst.afw.geom.SkyWcs`
1222 WCS of all of the input images to set on the output image.
1226 merged : `lsst.afw.image.MaskedImage`
1227 Merged image with all of the inputs at their respective bbox
1230 Count of the number of good pixels (those with positive weights)
1231 in the merged image.
1232 included : `list` [`int`]
1233 List of indexes of patches that were included in the merged
1234 result, to be used to trim the exposure catalog.
1236 merged = afwImage.ExposureF(bbox, wcs)
1237 weights = afwImage.ImageF(bbox)
1239 for i, (dataId, maskedImage)
in enumerate(maskedImages.items()):
1241 clippedBox =
geom.Box2I(maskedImage.getBBox())
1242 clippedBox.clip(bbox)
1243 if clippedBox.area == 0:
1244 self.
log.debug(
"%s does not overlap template region.", dataId)
1246 maskedImage = maskedImage.subset(clippedBox)
1248 good = (maskedImage.variance.array > 0) & (
1249 np.isfinite(maskedImage.variance.array)
1251 weight = maskedImage.variance.array[good] ** (-0.5)
1252 bad = np.isnan(maskedImage.image.array) | ~good
1255 maskedImage.image.array[bad] = 0.0
1256 maskedImage.variance.array[bad] = 0.0
1258 maskedImage.mask.array[bad] = 0
1262 maskedImage.image.array[good] *= weight
1263 maskedImage.variance.array[good] *= weight
1264 weights[clippedBox].array[good] += weight
1267 merged.maskedImage[clippedBox] += maskedImage
1270 good = weights.array > 0
1275 weights = weights.array[good]
1276 merged.image.array[good] /= weights
1277 merged.variance.array[good] /= weights
1279 merged.mask.array[~good] |= merged.mask.getPlaneBitMask(
"NO_DATA")
1281 return merged, good.sum(), included
1284 """Return a PSF containing the PSF at each of the input regions.
1286 Note that although this includes all the exposures from the catalog,
1287 the PSF knows which part of the template the inputs came from, so when
1288 evaluated at a given position it will not include inputs that never
1289 went in to those pixels.
1293 template : `lsst.afw.image.Exposure`
1294 Generated template the PSF is for.
1295 catalog : `lsst.afw.table.ExposureCatalog`
1296 Catalog of exposures that went into the template that contains all
1298 wcs : `lsst.afw.geom.SkyWcs`
1299 WCS of the template, to warp the PSFs to.
1303 coaddPsf : `lsst.meas.algorithms.CoaddPsf`
1304 The meta-psf constructed from all of the input catalogs.
1308 boolmask = template.mask.array & template.mask.getPlaneBitMask(
"NO_DATA") == 0
1310 centerCoord = afwGeom.SpanSet.fromMask(maskx, 1).computeCentroid()
1312 ctrl = self.config.coaddPsf.makeControl()
1313 coaddPsf = CoaddPsf(
1314 catalog, wcs, centerCoord, ctrl.warpingKernelName, ctrl.cacheSize
1319 """Return a Gaussian PSF with the width of the template CoaddPsf.
1323 template : `lsst.afw.image.Exposure`
1324 Template with the CoaddPsf to approximate. The width is measured
1325 at the average position of the PSF, or averaged over a grid of
1326 positions if the PSF cannot be evaluated there.
1330 psf : `lsst.afw.detection.GaussianPsf`
1331 Gaussian with the width of the template PSF.
1335 lsst.afw.detection.InvalidPsfError
1336 Raised if the PSF cannot be evaluated at any grid position.
1341 fwhm = getPsfFwhm(template.psf)
1348 self.
log.info(
"Unable to evaluate PSF at the average position. "
1349 "Evaluating PSF on a grid of points.")
1350 fwhm = evaluateMeanPsfFwhm(template,
1351 fwhmExposureBuffer=self.config.fwhmExposureBuffer,
1352 fwhmExposureGrid=self.config.fwhmExposureGrid)
1353 sigma = fwhm/gaussian_sigma_to_fwhm
1354 size = 2*int(np.ceil(_PSF_STAMP_SIGMAS*sigma)) + 1
1355 self.metadata[
"templatePsfSigma"] = float(sigma)
1356 self.
log.info(
"Approximated the template PSF with a Gaussian of sigma %.3f pixels.", sigma)
1357 return afwDetection.GaussianPsf(size, size, sigma)
1361 GetTemplateConnections,
1362 dimensions=(
"instrument",
"visit",
"detector"),
1363 defaultTemplates={
"coaddName":
"dcr",
"warpTypeSuffix":
"",
"fakesType":
""},
1365 visitInfo = pipeBase.connectionTypes.Input(
1366 doc=
"VisitInfo of calexp used to determine observing conditions.",
1367 name=
"{fakesType}calexp.visitInfo",
1368 storageClass=
"VisitInfo",
1369 dimensions=(
"instrument",
"visit",
"detector"),
1371 dcrCoadds = pipeBase.connectionTypes.Input(
1372 doc=
"Input DCR template to match and subtract from the exposure",
1373 name=
"{fakesType}dcrCoadd{warpTypeSuffix}",
1374 storageClass=
"ExposureF",
1375 dimensions=(
"tract",
"patch",
"skymap",
"band",
"subfilter"),
1380 def __init__(self, *, config=None):
1381 super().__init__(config=config)
1382 self.inputs.remove(
"coaddExposures")
1385class GetDcrTemplateConfig(
1386 GetTemplateConfig, pipelineConnections=GetDcrTemplateConnections
1388 """Config for GetDcrTemplateTask.
1390 Only ``output_image_type="legacy"`` is supported: the task always writes
1391 an `lsst.afw.image.ExposureF`.
1394 numSubfilters = pexConfig.Field(
1395 doc=
"Number of subfilters in the DcrCoadd.",
1399 effectiveWavelength = pexConfig.Field(
1400 doc=
"Effective wavelength of the filter in nm.",
1404 bandwidth = pexConfig.Field(
1405 doc=
"Bandwidth of the physical filter.",
1411 if self.effectiveWavelength
is None or self.bandwidth
is None:
1413 "The effective wavelength and bandwidth of the physical filter "
1414 "must be set in the getTemplate config for DCR coadds. "
1415 "Required until transmission curves are used in DM-13668."
1420 ConfigClass = GetDcrTemplateConfig
1421 _DefaultName =
"getDcrTemplate"
1423 def runQuantum(self, butlerQC, inputRefs, outputRefs):
1424 inputs = butlerQC.get(inputRefs)
1425 detector = inputs.pop(
"detector")
1426 bbox = detector.getBBox()
1427 wcs = inputs.pop(
"wcs")
1428 dcrCoaddExposureHandles = inputs.pop(
"dcrCoadds")
1429 skymap = inputs.pop(
"skyMap")
1430 visitInfo = inputs.pop(
"visitInfo")
1433 inputs.pop(
"obs_info",
None)
1436 assert not inputs,
"runQuantum got more inputs than expected"
1438 results = self.getExposures(
1439 dcrCoaddExposureHandles, bbox, skymap, wcs, visitInfo
1441 physical_filter = butlerQC.quantum.dataId[
"physical_filter"]
1443 coaddExposureHandles=results.coaddExposures,
1446 dataIds=results.dataIds,
1447 physical_filter=physical_filter,
1448 visit=outputRefs.template.dataId[
"visit"],
1449 instrument=butlerQC.quantum.dataId[
"instrument"],
1451 butlerQC.put(outputs, outputRefs)
1453 def getExposures(self, dcrCoaddExposureHandles, bbox, skymap, wcs, visitInfo):
1454 """Return lists of coadds and their corresponding dataIds that overlap
1457 The spatial index in the registry has generous padding and often
1458 supplies patches near, but not directly overlapping the detector.
1459 Filters inputs so that we don't have to read in all input coadds.
1463 dcrCoaddExposureHandles : `list` \
1464 [`lsst.daf.butler.DeferredDatasetHandle` of \
1465 `lsst.afw.image.Exposure`]
1466 Data references to exposures that might overlap the detector.
1467 bbox : `lsst.geom.Box2I`
1468 Template Bounding box of the detector geometry onto which to
1469 resample the coaddExposures.
1470 skymap : `lsst.skymap.SkyMap`
1471 Input definition of geometry/bbox and projection/wcs for
1473 wcs : `lsst.afw.geom.SkyWcs`
1474 Template WCS onto which to resample the coaddExposures.
1475 visitInfo : `lsst.afw.image.VisitInfo`
1476 Metadata for the science image.
1480 result : `lsst.pipe.base.Struct`
1481 A struct with attibutes:
1484 Dict of coadd exposures that overlap the projected bbox,
1486 (`dict` [`int`, `list` [`lsst.afw.image.Exposure`] ]).
1488 Dict of data IDs of the coadd exposures that overlap the
1489 projected bbox, indexed on tract id
1490 (`dict` [`int`, `list [`lsst.daf.butler.DataCoordinate`] ]).
1494 pipeBase.NoWorkFound
1495 Raised if no patches overlatp the input detector bbox.
1500 raise pipeBase.NoWorkFound(
"Exposure has no WCS; cannot create a template.")
1504 dataIds = collections.defaultdict(list)
1506 for coaddRef
in dcrCoaddExposureHandles:
1507 dataId = coaddRef.dataId
1508 subfilter = dataId[
"subfilter"]
1509 patchWcs = skymap[dataId[
"tract"]].getWcs()
1510 patchBBox = skymap[dataId[
"tract"]][dataId[
"patch"]].getOuterBBox()
1511 patchCorners = patchWcs.pixelToSky(
geom.Box2D(patchBBox).getCorners())
1512 patchPolygon = afwGeom.Polygon(wcs.skyToPixel(patchCorners))
1513 if patchPolygon.intersection(detectorPolygon):
1514 overlappingArea += patchPolygon.intersectionSingle(
1518 "Using template input tract=%s, patch=%s, subfilter=%s"
1519 % (dataId[
"tract"], dataId[
"patch"], dataId[
"subfilter"])
1521 if dataId[
"tract"]
in patchList:
1522 patchList[dataId[
"tract"]].append(dataId[
"patch"])
1524 patchList[dataId[
"tract"]] = [
1528 dataIds[dataId[
"tract"]].append(dataId)
1530 if not overlappingArea:
1531 raise pipeBase.NoWorkFound(
"No patches overlap detector")
1533 self.checkPatchList(patchList)
1535 coaddExposures = self.getDcrModel(patchList, dcrCoaddExposureHandles, visitInfo)
1536 return pipeBase.Struct(coaddExposures=coaddExposures, dataIds=dataIds)
1539 """Check that all of the DcrModel subfilters are present for each
1545 Dict of the patches containing valid data for each tract.
1550 If the number of exposures found for a patch does not match the
1551 number of subfilters.
1553 for tract
in patchList:
1554 for patch
in set(patchList[tract]):
1555 if patchList[tract].count(patch) != self.config.numSubfilters:
1557 "Invalid number of DcrModel subfilters found: %d vs %d expected",
1558 patchList[tract].count(patch),
1559 self.config.numSubfilters,
1563 """Build DCR-matched coadds from a list of exposure references.
1568 Dict of the patches containing valid data for each tract.
1569 coaddRefs : `list` [`lsst.daf.butler.DeferredDatasetHandle`]
1570 Data references to `~lsst.afw.image.Exposure` representing
1571 DcrModels that overlap the detector.
1572 visitInfo : `lsst.afw.image.VisitInfo`
1573 Metadata for the science image.
1577 coaddExposures : `list` [`lsst.afw.image.Exposure`]
1578 Coadd exposures that overlap the detector.
1580 coaddExposures = collections.defaultdict(list)
1581 for tract
in patchList:
1582 for patch
in set(patchList[tract]):
1585 for coaddRef
in coaddRefs
1589 dcrModel = DcrModel.fromQuantum(
1591 self.config.effectiveWavelength,
1592 self.config.bandwidth,
1593 self.config.numSubfilters,
1595 coaddExposures[tract].append(dcrModel.buildMatchedExposureHandle(visitInfo=visitInfo))
1596 return coaddExposures
1600 condition = (coaddRef.dataId[
"tract"] == tract) & (
1601 coaddRef.dataId[
"patch"] == patch
checkHighVariance(self, template)
_clearUnmappedMaskPlanes(self, mask, planeMap)
_correctVariance(self, template, plateScaleFactor)
_getInstrument(coaddInputs)
convert_outputs_to_future(self, template, coadd_refs, detector, exposureRecord, templateInputs=None)
_makeGaussianPsf(self, template)
_plateScaleFactor(self, coaddInputs, wcs, bbox)
getExposures(self, coaddExposureHandles, bbox, skymap, wcs)
run(self, *, coaddExposureHandles, bbox, wcs, dataIds, physical_filter, visit=None, instrument=None)
_collectTemplateInputs(self, catalog, coaddInputs, wcs, bbox)
_checkInputs(dataIds, coaddExposures, scienceInstrument=None)
_makePsf(self, template, catalog, wcs)
_makeExposureCatalog(self, exposureRefs, dataIds, instrument=_UNKNOWN_INSTRUMENT)
_merge(self, maskedImages, bbox, wcs)
runQuantum(self, butlerQC, inputRefs, outputRefs)
__init__(self, *args, **kwargs)
std::shared_ptr< TransformPoint2ToPoint2 > makeWcsPairTransform(SkyWcs const &src, SkyWcs const &dst)
_getImageOverlap(record, coaddWcs, scienceFootprint, coaddToScienceTransform, scienceBox, border)
_warpKernelSumSq(kernelName, nPhase=100)
getDcrModel(self, patchList, coaddRefs, visitInfo)
_pixelTransform(fromWcs, toWcs)
checkPatchList(self, patchList)
_selectDataRef(coaddRef, tract, patch)