Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DM-33982: Add finalized psf support to MakeWarpTask. #650

Merged
merged 3 commits into from
Apr 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
70 changes: 67 additions & 3 deletions python/lsst/pipe/tasks/imageDifference.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,14 @@ class ImageDifferenceTaskConnections(pipeBase.PipelineTaskConnections,
multiple=True,
deferLoad=True
)
finalizedPsfApCorrCatalog = pipeBase.connectionTypes.Input(
doc=("Per-visit finalized psf models and aperture correction maps. "
"These catalogs use the detector id for the catalog id, "
"sorted on id for fast lookup."),
name="finalized_psf_ap_corr_catalog",
storageClass="ExposureCatalog",
dimensions=("instrument", "visit"),
)
outputSchema = pipeBase.connectionTypes.InitOutput(
doc="Schema (as an example catalog) for output DIASource catalog.",
storageClass="SourceCatalog",
Expand Down Expand Up @@ -149,6 +157,8 @@ def __init__(self, *, config=None):
self.outputs.remove("matchedExposure")
if not config.doWriteSources:
self.outputs.remove("diaSources")
if not config.doApplyFinalizedPsf:
self.inputs.remove("finalizedPsfApCorrCatalog")

# TODO DM-22953: Add support for refObjLoader (kernelSourcesFromRef)
# Make kernelSources optional
Expand Down Expand Up @@ -218,6 +228,11 @@ class ImageDifferenceConfig(pipeBase.PipelineTaskConfig,
doWriteSources = pexConfig.Field(dtype=bool, default=True, doc="Write sources?")
doAddMetrics = pexConfig.Field(dtype=bool, default=False,
doc="Add columns to the source table to hold analysis metrics?")
doApplyFinalizedPsf = pexConfig.Field(
doc="Whether to apply finalized psf models and aperture correction map.",
dtype=bool,
default=False,
)

coaddName = pexConfig.Field(
doc="coadd name: typically one of deep, goodSeeing, or dcr",
Expand Down Expand Up @@ -532,6 +547,13 @@ def runQuantum(self, butlerQC: pipeBase.ButlerQuantumContext,
outputRefs: pipeBase.OutputQuantizedConnection):
inputs = butlerQC.get(inputRefs)
self.log.info("Processing %s", butlerQC.quantum.dataId)

finalizedPsfApCorrCatalog = inputs.get("finalizedPsfApCorrCatalog", None)
exposure = self.prepareCalibratedExposure(
inputs["exposure"],
finalizedPsfApCorrCatalog=finalizedPsfApCorrCatalog
)

expId, expBits = butlerQC.quantum.dataId.pack("visit_detector",
returnMaxBits=True)
idFactory = self.makeIdFactory(expId=expId, expBits=expBits)
Expand All @@ -540,12 +562,12 @@ def runQuantum(self, butlerQC: pipeBase.ButlerQuantumContext,
else:
templateExposures = inputRefs.coaddExposures
templateStruct = self.getTemplate.runQuantum(
inputs['exposure'], butlerQC, inputRefs.skyMap, templateExposures
exposure, butlerQC, inputRefs.skyMap, templateExposures
)

self.checkTemplateIsSufficient(templateStruct.exposure)

outputs = self.run(exposure=inputs['exposure'],
outputs = self.run(exposure=exposure,
templateExposure=templateStruct.exposure,
idFactory=idFactory)
# Consistency with runDataref gen2 handling
Expand Down Expand Up @@ -634,6 +656,42 @@ def runDataRef(self, sensorRef, templateIdList=None):
sensorRef.put(results.scoreExposure, self.config.coaddName + "Diff_scoreExp")
return results

def prepareCalibratedExposure(self, exposure, finalizedPsfApCorrCatalog=None):
"""Prepare a calibrated exposure and apply finalized psf if so configured.

Parameters
----------
exposure : `lsst.afw.image.exposure.Exposure`
Input exposure to adjust calibrations.
finalizedPsfApCorrCatalog : `lsst.afw.table.ExposureCatalog`, optional
Exposure catalog with finalized psf models and aperture correction
maps to be applied if config.doApplyFinalizedPsf=True. Catalog uses
the detector id for the catalog id, sorted on id for fast lookup.

Returns
-------
exposure : `lsst.afw.image.exposure.Exposure`
Exposure with adjusted calibrations.
"""
detectorId = exposure.getInfo().getDetector().getId()

if finalizedPsfApCorrCatalog is not None:
row = finalizedPsfApCorrCatalog.find(detectorId)
if row is None:
self.log.warning("Detector id %s not found in finalizedPsfApCorrCatalog; "
"Using original psf.", detectorId)
else:
psf = row.getPsf()
apCorrMap = row.getApCorrMap()
if psf is None or apCorrMap is None:
self.log.warning("Detector id %s has None for psf/apCorrMap in "
"finalizedPsfApCorrCatalog; Using original psf.", detectorId)
else:
exposure.setPsf(psf)
exposure.setApCorrMap(apCorrMap)

return exposure

@timeMethod
def run(self, exposure=None, selectSources=None, templateExposure=None, templateSources=None,
idFactory=None, calexpBackgroundExposure=None, subtractedExposure=None):
Expand Down Expand Up @@ -1351,7 +1409,13 @@ def runQuantum(self, butlerQC, inputRefs, outputRefs):
returnMaxBits=True)
idFactory = self.makeIdFactory(expId=expId, expBits=expBits)

outputs = self.run(exposure=inputs['exposure'],
finalizedPsfApCorrCatalog = inputs.get("finalizedPsfApCorrCatalog", None)
exposure = self.prepareCalibratedExposure(
inputs["exposure"],
finalizedPsfApCorrCatalog=finalizedPsfApCorrCatalog
)

outputs = self.run(exposure=exposure,
templateExposure=inputs['inputTemplate'],
idFactory=idFactory)

Expand Down
52 changes: 49 additions & 3 deletions python/lsst/pipe/tasks/makeCoaddTempExp.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@ class MakeCoaddTempExpConfig(CoaddBaseTask.ConfigClass):
)
doApplySkyCorr = pexConfig.Field(dtype=bool, default=False, doc="Apply sky correction?")

doApplyFinalizedPsf = pexConfig.Field(
doc="Whether to apply finalized psf models and aperture correction map.",
dtype=bool,
default=False,
)

def validate(self):
CoaddBaseTask.ConfigClass.validate(self)
if not self.makePsfMatched and not self.makeDirect:
Expand Down Expand Up @@ -646,6 +652,14 @@ class MakeWarpConnections(pipeBase.PipelineTaskConnections,
storageClass="ExposureCatalog",
dimensions=("instrument", "visit"),
)
finalizedPsfApCorrCatalog = connectionTypes.Input(
doc=("Per-visit finalized psf models and aperture correction maps. "
"These catalogs use the detector id for the catalog id, "
"sorted on id for fast lookup."),
name="finalized_psf_ap_corr_catalog",
storageClass="ExposureCatalog",
dimensions=("instrument", "visit"),
)
direct = connectionTypes.Output(
doc=("Output direct warped exposure (previously called CoaddTempExp), produced by resampling ",
"calexps onto the skyMap patch geometry."),
Expand Down Expand Up @@ -711,6 +725,8 @@ def __init__(self, *, config=None):
else:
self.inputs.remove("externalPhotoCalibTractCatalog")
self.inputs.remove("externalPhotoCalibGlobalCatalog")
if not config.doApplyFinalizedPsf:
self.inputs.remove("finalizedPsfApCorrCatalog")
if not config.makeDirect:
self.outputs.remove("direct")
if not config.makePsfMatched:
Expand Down Expand Up @@ -798,9 +814,15 @@ def runQuantum(self, butlerQC, inputRefs, outputRefs):
else:
externalPhotoCalibCatalog = None

if self.config.doApplyFinalizedPsf:
finalizedPsfApCorrCatalog = inputs.pop("finalizedPsfApCorrCatalog")
else:
finalizedPsfApCorrCatalog = None

completeIndices = self.prepareCalibratedExposures(**inputs,
externalSkyWcsCatalog=externalSkyWcsCatalog,
externalPhotoCalibCatalog=externalPhotoCalibCatalog)
externalPhotoCalibCatalog=externalPhotoCalibCatalog,
finalizedPsfApCorrCatalog=finalizedPsfApCorrCatalog)
# Redo the input selection with inputs with complete wcs/photocalib info.
inputs = self.filterInputs(indices=completeIndices, inputs=inputs)

Expand Down Expand Up @@ -829,6 +851,7 @@ def filterInputs(self, indices, inputs):

def prepareCalibratedExposures(self, calExpList, backgroundList=None, skyCorrList=None,
externalSkyWcsCatalog=None, externalPhotoCalibCatalog=None,
finalizedPsfApCorrCatalog=None,
**kwargs):
"""Calibrate and add backgrounds to input calExpList in place

Expand All @@ -848,6 +871,10 @@ def prepareCalibratedExposures(self, calExpList, backgroundList=None, skyCorrLis
Exposure catalog with external photoCalib to be applied
if config.doApplyExternalPhotoCalib=True. Catalog uses the detector
id for the catalog id, sorted on id for fast lookup.
finalizedPsfApCorrCatalog : `lsst.afw.table.ExposureCatalog`, optional
Exposure catalog with finalized psf models and aperture correction
maps to be applied if config.doApplyFinalizedPsf=True. Catalog uses
the detector id for the catalog id, sorted on id for fast lookup.

Returns
-------
Expand All @@ -866,8 +893,7 @@ def prepareCalibratedExposures(self, calExpList, backgroundList=None, skyCorrLis
if not self.config.bgSubtracted:
calexp.maskedImage += background.getImage()

if externalSkyWcsCatalog is not None or externalPhotoCalibCatalog is not None:
detectorId = calexp.getInfo().getDetector().getId()
detectorId = calexp.getInfo().getDetector().getId()

# Find the external photoCalib
if externalPhotoCalibCatalog is not None:
Expand Down Expand Up @@ -909,6 +935,26 @@ def prepareCalibratedExposures(self, calExpList, backgroundList=None, skyCorrLis
"and will not be used in the warp.", detectorId)
continue

# Find and apply finalized psf and aperture correction
if finalizedPsfApCorrCatalog is not None:
row = finalizedPsfApCorrCatalog.find(detectorId)
if row is None:
self.log.warning("Detector id %s not found in finalizedPsfApCorrCatalog "
"and will not be used in the warp.", detectorId)
continue
psf = row.getPsf()
if psf is None:
self.log.warning("Detector id %s has None for psf in finalizedPsfApCorrCatalog "
"and will not be used in the warp.", detectorId)
continue
calexp.setPsf(psf)
apCorrMap = row.getApCorrMap()
if apCorrMap is None:
self.log.warning("Detector id %s has None for ApCorrMap in finalizedPsfApCorrCatalog "
"and will not be used in the warp.", detectorId)
continue
calexp.setApCorrMap(apCorrMap)

# Calibrate the image
calexp.maskedImage = photoCalib.calibrateImage(calexp.maskedImage,
includeScaleUncertainty=includeCalibVar)
Expand Down