1 from __future__
import absolute_import, division, print_function
3 from builtins
import zip
4 from builtins
import map
13 from lsst.pipe.base import Struct, ArgumentParser, ConfigDatasetType
23 coaddName =
Field(dtype=str, default=
"deep", doc=
"Name for coadd")
25 target=WcsSelectImagesTask, doc=
"Select images to process")
27 target=MakeCoaddTempExpTask, doc=
"Warp images to sky")
29 dtype=bool, default=
False, doc=
"Build background reference?")
31 target=NullSelectImagesTask, doc=
"Build background reference")
33 target=SafeClipAssembleCoaddTask, doc=
"Assemble warps into coadd")
34 doDetection =
Field(dtype=bool, default=
True,
35 doc=
"Run detection on the coaddition product")
37 target=DetectCoaddSourcesTask, doc=
"Detect sources on coadd")
38 hasFakes =
Field(dtype=bool, default=
False,
39 doc=
"Should be set to True if fake sources were added to the data before processing.")
40 calexpType =
Field(dtype=str, default=
"calexp",
41 doc=
"Should be set to fakes_calexp if you want to process calexps with fakes in.")
51 "makeCoaddTempExp.coaddName and coaddName don't match")
54 "assembleCoadd.coaddName and coaddName don't match")
56 message = (
"assembleCoadd.matchingKernelSize (%s) and makeCoaddTempExp.matchingKernelSize (%s)" 59 raise RuntimeError(message)
64 def __init__(self, TaskClass, parsedCmd, doReturnResults=False):
65 CoaddTaskRunner.__init__(self, TaskClass, parsedCmd, doReturnResults)
69 return self.TaskClass(config=self.config, log=self.log, reuse=self.
reuse)
73 """!Get bare butler into Task 75 @param parsedCmd results of parsing command input 77 kwargs[
"butler"] = parsedCmd.butler
78 kwargs[
"selectIdList"] = [
79 ref.dataId
for ref
in parsedCmd.selectId.refList]
80 return [(parsedCmd.id.refList, kwargs), ]
84 """Unpickle something by calling a factory""" 85 return factory(*args, **kwargs)
89 ConfigClass = CoaddDriverConfig
90 _DefaultName =
"coaddDriver" 91 RunnerClass = CoaddDriverTaskRunner
94 BatchPoolTask.__init__(self, **kwargs)
97 self.
makeSubtask(
"makeCoaddTempExp", reuse=(
"makeCoaddTempExp" in self.
reuse))
108 return unpickle, (self.__class__, [], dict(config=self.
config, name=self.
_name,
113 def _makeArgumentParser(cls, **kwargs):
114 """!Build argument parser 116 Selection references are not cheap (reads Wcs), so are generated 117 only if we're not doing a batch submission. 120 parser.add_id_argument(
"--id",
"deepCoadd", help=
"data ID, e.g. --id tract=12345 patch=1,2",
121 ContainerClass=TractDataIdContainer)
123 parser.add_id_argument(
"--selectId", datasetType=datasetType,
124 help=
"data ID, e.g. --selectId visit=6789 ccd=0..9")
125 parser.addReuseOption([
"makeCoaddTempExp",
"assembleCoadd",
"detectCoaddSources"])
131 Return walltime request for batch job 133 @param time: Requested time per iteration 134 @param parsedCmd: Results of argument parsing 135 @param numCores: Number of cores 136 @return float walltime request length 138 numTargets = len(parsedCmd.selectId.refList)
139 return time*numTargets/
float(numCores)
142 def runDataRef(self, tractPatchRefList, butler, selectIdList=[]):
143 """!Determine which tracts are non-empty before processing 145 @param tractPatchRefList: List of tracts and patches to include in the coaddition 146 @param butler: butler reference object 147 @param selectIdList: List of data Ids (i.e. visit, ccd) to consider when making the coadd 148 @return list of references to sel.runTract function evaluation for each tractPatchRefList member 150 pool =
Pool(
"tracts")
151 pool.storeSet(butler=butler, skymap=butler.get(
152 self.
config.coaddName +
"Coadd_skyMap"))
154 for patchRefList
in tractPatchRefList:
155 tractSet =
set([patchRef.dataId[
"tract"]
156 for patchRef
in patchRefList])
157 assert len(tractSet) == 1
158 tractIdList.append(tractSet.pop())
160 selectDataList = [data
for data
in pool.mapNoBalance(self.
readSelection, selectIdList)
if 162 nonEmptyList = pool.mapNoBalance(
164 tractPatchRefList = [patchRefList
for patchRefList, nonEmpty
in 165 zip(tractPatchRefList, nonEmptyList)
if nonEmpty]
166 self.
log.
info(
"Non-empty tracts (%d): %s" % (len(tractPatchRefList),
167 [patchRefList[0].dataId[
"tract"]
for patchRefList
in 170 for data
in selectDataList:
174 return [self.
run(patchRefList, butler, selectDataList)
for patchRefList
in tractPatchRefList]
177 def run(self, patchRefList, butler, selectDataList=[]):
178 """!Run stacking on a tract 180 This method only runs on the master node. 182 @param patchRefList: List of patch data references for tract 183 @param butler: Data butler 184 @param selectDataList: List of SelectStruct for inputs 186 pool =
Pool(
"stacker")
188 pool.storeSet(butler=butler, warpType=self.
config.coaddName +
"Coadd_directWarp",
189 coaddType=self.
config.coaddName +
"Coadd")
190 patchIdList = [patchRef.dataId
for patchRef
in patchRefList]
192 selectedData = pool.map(self.
warp, patchIdList, selectDataList)
193 if self.
config.doBackgroundReference:
194 self.backgroundReference.
runDataRef(patchRefList, selectDataList)
196 def refNamer(patchRef):
197 return tuple(map(int, patchRef.dataId[
"patch"].split(
",")))
199 lookup = dict(zip(map(refNamer, patchRefList), selectedData))
200 coaddData = [
Struct(patchId=patchRef.dataId, selectDataList=lookup[refNamer(patchRef)])
for 201 patchRef
in patchRefList]
202 pool.map(self.
coadd, coaddData)
205 """!Read Wcs of selected inputs 207 This method only runs on slave nodes. 208 This method is similar to SelectDataIdContainer.makeDataRefList, 209 creating a Struct like a SelectStruct, except with a dataId instead 210 of a dataRef (to ease MPI). 212 @param cache: Pool cache 213 @param selectId: Data identifier for selected input 214 @return a SelectStruct with a dataId instead of dataRef 218 self.
log.
info(
"Reading Wcs from %s" % (selectId,))
219 md = ref.get(
"calexp_md", immediate=
True)
223 self.
log.
warn(
"Unable to construct Wcs from %s" % (selectId,))
228 """!Check whether a tract has any overlapping inputs 230 This method only runs on slave nodes. 232 @param cache: Pool cache 233 @param tractId: Data identifier for tract 234 @param selectDataList: List of selection data 235 @return whether tract has any overlapping inputs 237 def makePolygon(wcs, bbox):
238 """Return a polygon for the image, given Wcs and bounding box""" 240 boxSkyCorners = wcs.pixelToSky(boxPixelCorners)
243 skymap = cache.skymap
244 tract = skymap[tractId]
245 tractWcs = tract.getWcs()
246 tractPoly = makePolygon(tractWcs, tract.getBBox())
248 for selectData
in selectIdList:
249 if not hasattr(selectData,
"poly"):
250 selectData.poly = makePolygon(selectData.wcs, selectData.bbox)
251 if tractPoly.intersects(selectData.poly):
255 def warp(self, cache, patchId, selectDataList):
256 """!Warp all images for a patch 258 Only slave nodes execute this method. 260 Because only one argument may be passed, it is expected to 261 contain multiple elements, which are: 263 @param patchRef: data reference for patch 264 @param selectDataList: List of SelectStruct for inputs 265 @return selectDataList with non-overlapping elements removed 267 patchRef =
getDataRef(cache.butler, patchId, cache.coaddType)
269 with self.
logOperation(
"warping %s" % (patchRef.dataId,), catch=
True):
270 self.makeCoaddTempExp.
runDataRef(patchRef, selectDataList)
271 return selectDataList
274 """!Construct coadd for a patch and measure 276 Only slave nodes execute this method. 278 Because only one argument may be passed, it is expected to 279 contain multiple elements, which are: 281 @param patchRef: data reference for patch 282 @param selectDataList: List of SelectStruct for inputs 284 patchRef =
getDataRef(cache.butler, data.patchId, cache.coaddType)
285 selectDataList = data.selectDataList
292 "detectCoaddSources" in self.
reuse and 293 patchRef.datasetExists(self.detectCoaddSources.config.coaddName+
"Coadd_det", write=
True)
295 if "assembleCoadd" in self.
reuse:
296 if patchRef.datasetExists(cache.coaddType, write=
True):
297 self.
log.
info(
"%s: Skipping assembleCoadd for %s; outputs already exist." %
298 (NODE, patchRef.dataId))
299 coadd = patchRef.get(cache.coaddType, immediate=
True)
300 elif not self.
config.assembleCoadd.doWrite
and self.
config.doDetection
and canSkipDetection:
302 "%s: Skipping assembleCoadd and detectCoaddSources for %s; outputs already exist." %
303 (NODE, patchRef.dataId)
307 with self.
logOperation(
"coadding %s" % (patchRef.dataId,), catch=
True):
308 coaddResults = self.assembleCoadd.
runDataRef(patchRef, selectDataList)
309 if coaddResults
is not None:
310 coadd = coaddResults.coaddExposure
311 canSkipDetection =
False 319 if self.
config.doDetection:
321 self.
log.
info(
"%s: Skipping detectCoaddSources for %s; outputs already exist." %
322 (NODE, patchRef.dataId))
326 idFactory = self.detectCoaddSources.makeIdFactory(patchRef)
327 expId =
int(patchRef.get(self.
config.coaddName +
"CoaddId"))
330 detResults = self.detectCoaddSources.
run(coadd, idFactory, expId=expId)
331 self.detectCoaddSources.write(detResults, patchRef)
334 patchRef.put(coadd,
"fakes_" + self.assembleCoadd.config.coaddName +
"Coadd")
336 patchRef.put(coadd, self.assembleCoadd.config.coaddName +
"Coadd")
339 """!Select exposures to operate upon, via the SelectImagesTask 341 This is very similar to CoaddBaseTask.selectExposures, except we return 342 a list of SelectStruct (same as the input), so we can plug the results into 343 future uses of SelectImagesTask. 345 @param patchRef data reference to a particular patch 346 @param selectDataList list of references to specific data products (i.e. visit, ccd) 347 @return filtered list of SelectStruct 350 return tuple(dataRef.dataId[k]
for k
in sorted(dataRef.dataId))
351 inputs = dict((
key(select.dataRef), select)
352 for select
in selectDataList)
353 skyMap = patchRef.get(self.
config.coaddName +
"Coadd_skyMap")
354 tract = skyMap[patchRef.dataId[
"tract"]]
355 patch = tract[(tuple(
int(i)
356 for i
in patchRef.dataId[
"patch"].split(
",")))]
357 bbox = patch.getOuterBBox()
360 coordList = [wcs.pixelToSky(pos)
for pos
in cornerPosList]
362 patchRef, coordList, selectDataList=selectDataList).dataRefList
363 return [inputs[
key(dataRef)]
for dataRef
in dataRefList]
def batchWallTime(cls, time, parsedCmd, numCores)
Return walltime request for batch job.
def unpickle(factory, args, kwargs)
def makeSubtask(self, name, keyArgs)
A floating-point coordinate rectangle geometry.
def selectExposures(self, patchRef, selectDataList)
Select exposures to operate upon, via the SelectImagesTask.
daf::base::PropertySet * set
def makeTask(self, parsedCmd=None, args=None)
def getDataRef(butler, dataId, datasetType="raw")
def __init__(self, reuse=tuple(), kwargs)
static ConvexPolygon convexHull(std::vector< UnitVector3d > const &points)
convexHull returns the convex hull of the given set of points if it exists and throws an exception ot...
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
def coadd(self, cache, data)
Construct coadd for a patch and measure.
def runDataRef(self, tractPatchRefList, butler, selectIdList=[])
Determine which tracts are non-empty before processing.
def warp(self, cache, patchId, selectDataList)
Warp all images for a patch.
def logOperation(self, operation, catch=False, trace=True)
Provide a context manager for logging an operation.
def getTargetList(parsedCmd, kwargs)
Get bare butler into Task.
std::shared_ptr< SkyWcs > makeSkyWcs(TransformPoint2ToPoint2 const &pixelsToFieldAngle, lsst::geom::Angle const &orientation, bool flipX, lsst::geom::SpherePoint const &boresight, std::string const &projection="TAN")
Construct a FITS SkyWcs from camera geometry.
def readSelection(self, cache, selectId)
Read Wcs of selected inputs.
def __init__(self, TaskClass, parsedCmd, doReturnResults=False)
def checkTract(self, cache, tractId, selectIdList)
Check whether a tract has any overlapping inputs.
def writeMetadata(self, dataRef)
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects...
lsst::geom::Box2I bboxFromMetadata(daf::base::PropertySet &metadata)
Determine the image bounding box from its metadata (FITS header)
def run(self, patchRefList, butler, selectDataList=[])
Run stacking on a tract.