LSST Applications g070148d5b3+33e5256705,g0d53e28543+25c8b88941,g0da5cf3356+2dd1178308,g1081da9e2a+62d12e78cb,g17e5ecfddb+7e422d6136,g1c76d35bf8+ede3a706f7,g295839609d+225697d880,g2e2c1a68ba+cc1f6f037e,g2ffcdf413f+853cd4dcde,g38293774b4+62d12e78cb,g3b44f30a73+d953f1ac34,g48ccf36440+885b902d19,g4b2f1765b6+7dedbde6d2,g5320a0a9f6+0c5d6105b6,g56b687f8c9+ede3a706f7,g5c4744a4d9+ef6ac23297,g5ffd174ac0+0c5d6105b6,g6075d09f38+66af417445,g667d525e37+2ced63db88,g670421136f+2ced63db88,g71f27ac40c+2ced63db88,g774830318a+463cbe8d1f,g7876bc68e5+1d137996f1,g7985c39107+62d12e78cb,g7fdac2220c+0fd8241c05,g96f01af41f+368e6903a7,g9ca82378b8+2ced63db88,g9d27549199+ef6ac23297,gabe93b2c52+e3573e3735,gb065e2a02a+3dfbe639da,gbc3249ced9+0c5d6105b6,gbec6a3398f+0c5d6105b6,gc9534b9d65+35b9f25267,gd01420fc67+0c5d6105b6,geee7ff78d7+a14128c129,gf63283c776+ede3a706f7,gfed783d017+0c5d6105b6,w.2022.47
LSST Data Management Base Package
Loading...
Searching...
No Matches
multiBandDriver.py
Go to the documentation of this file.
1import os
2
3from lsst.coadd.utils.getGen3CoaddExposureId import getGen3CoaddExposureId
4from lsst.pex.config import Config, Field, ConfigurableField
5from lsst.pipe.base import ArgumentParser, TaskRunner
6from lsst.pipe.tasks.multiBand import (DetectCoaddSourcesTask,
7 MergeDetectionsTask,
8 DeblendCoaddSourcesTask,
9 MeasureMergedCoaddSourcesTask,
10 MergeMeasurementsTask,)
11from lsst.ctrl.pool.parallel import BatchPoolTask
12from lsst.ctrl.pool.pool import Pool, abortOnError
13from lsst.meas.base.references import MultiBandReferencesTask
14from lsst.meas.base.forcedPhotCoadd import ForcedPhotCoaddTask
15from lsst.pipe.drivers.utils import getDataRef, TractDataIdContainer
16
17import lsst.afw.table as afwTable
18
19
21 coaddName = Field(dtype=str, default="deep", doc="Name of coadd")
22 doDetection = Field(dtype=bool, default=False,
23 doc="Re-run detection? (requires *Coadd dataset to have been written)")
24 detectCoaddSources = ConfigurableField(target=DetectCoaddSourcesTask,
25 doc="Detect sources on coadd")
26 mergeCoaddDetections = ConfigurableField(
27 target=MergeDetectionsTask, doc="Merge detections")
28 deblendCoaddSources = ConfigurableField(target=DeblendCoaddSourcesTask, doc="Deblend merged detections")
29 measureCoaddSources = ConfigurableField(target=MeasureMergedCoaddSourcesTask,
30 doc="Measure merged and (optionally) deblended detections")
31 mergeCoaddMeasurements = ConfigurableField(
32 target=MergeMeasurementsTask, doc="Merge measurements")
33 forcedPhotCoadd = ConfigurableField(target=ForcedPhotCoaddTask,
34 doc="Forced measurement on coadded images")
35 reprocessing = Field(
36 dtype=bool, default=False,
37 doc=("Are we reprocessing?\n\n"
38 "This exists as a workaround for large deblender footprints causing large memory use "
39 "and/or very slow processing. We refuse to deblend those footprints when running on a cluster "
40 "and return to reprocess on a machine with larger memory or more time "
41 "if we consider those footprints important to recover."),
42 )
43
44 hasFakes = Field(
45 dtype=bool,
46 default=False,
47 doc="Should be set to True if fakes were inserted into the data being processed."
48 )
49
50 def setDefaults(self):
51 Config.setDefaults(self)
52 self.forcedPhotCoadd.references.retarget(MultiBandReferencesTask)
53
54 def validate(self):
55
56 for subtask in ("mergeCoaddDetections", "deblendCoaddSources", "measureCoaddSources",
57 "mergeCoaddMeasurements", "forcedPhotCoadd"):
58 coaddName = getattr(self, subtask).coaddName
59 if coaddName != self.coaddName:
60 raise RuntimeError("%s.coaddName (%s) doesn't match root coaddName (%s)" %
61 (subtask, coaddName, self.coaddName))
62
63
64class MultiBandDriverTaskRunner(TaskRunner):
65 """TaskRunner for running MultiBandTask
66
67 This is similar to the lsst.pipe.base.ButlerInitializedTaskRunner,
68 except that we have a list of data references instead of a single
69 data reference being passed to the Task.run, and we pass the results
70 of the '--reuse-outputs-from' command option to the Task constructor.
71 """
72
73 def __init__(self, TaskClass, parsedCmd, doReturnResults=False):
74 TaskRunner.__init__(self, TaskClass, parsedCmd, doReturnResults)
75 self.reuse = parsedCmd.reuse
76
77 def makeTask(self, parsedCmd=None, args=None):
78 """A variant of the base version that passes a butler argument to the task's constructor
79 parsedCmd or args must be specified.
80 """
81 if parsedCmd is not None:
82 butler = parsedCmd.butler
83 elif args is not None:
84 dataRefList, kwargs = args
85 butler = dataRefList[0].butlerSubset.butler
86 else:
87 raise RuntimeError("parsedCmd or args must be specified")
88 return self.TaskClass(config=self.config, log=self.log, butler=butler, reuse=self.reuse)
89
90
91def unpickle(factory, args, kwargs):
92 """Unpickle something by calling a factory"""
93 return factory(*args, **kwargs)
94
95
97 """Multi-node driver for multiband processing"""
98 ConfigClass = MultiBandDriverConfig
99 _DefaultName = "multiBandDriver"
100 RunnerClass = MultiBandDriverTaskRunner
101
102 def __init__(self, butler=None, schema=None, refObjLoader=None, reuse=tuple(), **kwargs):
103 """!
104 @param[in] butler: the butler can be used to retrieve schema or passed to the refObjLoader constructor
105 in case it is needed.
106 @param[in] schema: the schema of the source detection catalog used as input.
107 @param[in] refObjLoader: an instance of LoadReferenceObjectsTasks that supplies an external reference
108 catalog. May be None if the butler argument is provided or all steps requiring a reference
109 catalog are disabled.
110 """
111 BatchPoolTask.__init__(self, **kwargs)
112 if schema is None:
113 assert butler is not None, "Butler not provided"
114 schema = butler.get(self.config.coaddName +
115 "Coadd_det_schema", immediate=True).schema
116 self.butler = butler
117 self.reuse = tuple(reuse)
118 self.makeSubtask("detectCoaddSources")
119 self.makeSubtask("mergeCoaddDetections", schema=schema)
120 if self.config.measureCoaddSources.inputCatalog.startswith("deblended"):
121 # Ensure that the output from deblendCoaddSources matches the input to measureCoaddSources
122 self.measurementInput = self.config.measureCoaddSources.inputCatalog
124 self.deblenderOutput.append("deblendedFlux")
125 if self.measurementInput not in self.deblenderOutput:
126 err = "Measurement input '{0}' is not in the list of deblender output catalogs '{1}'"
127 raise ValueError(err.format(self.measurementInput, self.deblenderOutput))
128
129 self.makeSubtask("deblendCoaddSources",
130 schema=afwTable.Schema(self.mergeCoaddDetections.schema),
131 peakSchema=afwTable.Schema(self.mergeCoaddDetections.merged.getPeakSchema()),
132 butler=butler)
133 measureInputSchema = afwTable.Schema(self.deblendCoaddSources.schema)
134 else:
135 measureInputSchema = afwTable.Schema(self.mergeCoaddDetections.schema)
136 self.makeSubtask("measureCoaddSources", schema=measureInputSchema,
137 peakSchema=afwTable.Schema(
138 self.mergeCoaddDetections.merged.getPeakSchema()),
139 refObjLoader=refObjLoader, butler=butler)
140 self.makeSubtask("mergeCoaddMeasurements", schema=afwTable.Schema(
141 self.measureCoaddSources.schema))
142 self.makeSubtask("forcedPhotCoadd", refSchema=afwTable.Schema(
143 self.mergeCoaddMeasurements.schema))
144 if self.config.hasFakes:
145 self.coaddType = "fakes_" + self.config.coaddName
146 else:
147 self.coaddType = self.config.coaddName
148
149 def __reduce__(self):
150 """Pickler"""
151 return unpickle, (self.__class__, [], dict(config=self.config, name=self._name,
152 parentTask=self._parentTask, log=self.log,
153 butler=self.butler, reuse=self.reuse))
154
155 @classmethod
156 def _makeArgumentParser(cls, *args, **kwargs):
157 kwargs.pop("doBatch", False)
158 parser = ArgumentParser(name=cls._DefaultName, *args, **kwargs)
159 parser.add_id_argument("--id", "deepCoadd", help="data ID, e.g. --id tract=12345 patch=1,2",
160 ContainerClass=TractDataIdContainer)
161 parser.addReuseOption(["detectCoaddSources", "mergeCoaddDetections", "measureCoaddSources",
162 "mergeCoaddMeasurements", "forcedPhotCoadd", "deblendCoaddSources"])
163 return parser
164
165 @classmethod
166 def batchWallTime(cls, time, parsedCmd, numCpus):
167 """!Return walltime request for batch job
168
169 @param time: Requested time per iteration
170 @param parsedCmd: Results of argument parsing
171 @param numCores: Number of cores
172 """
173 numTargets = 0
174 for refList in parsedCmd.id.refList:
175 numTargets += len(refList)
176 return time*numTargets/float(numCpus)
177
178 @abortOnError
179 def runDataRef(self, patchRefList):
180 """!Run multiband processing on coadds
181
182 Only the master node runs this method.
183
184 No real MPI communication (scatter/gather) takes place: all I/O goes
185 through the disk. We want the intermediate stages on disk, and the
186 component Tasks are implemented around this, so we just follow suit.
187
188 @param patchRefList: Data references to run measurement
189 """
190 for patchRef in patchRefList:
191 if patchRef:
192 butler = patchRef.getButler()
193 break
194 else:
195 raise RuntimeError("No valid patches")
196 pool = Pool("all")
197 pool.cacheClear()
198 pool.storeSet(butler=butler)
199 # MultiBand measurements require that the detection stage be completed
200 # before measurements can be made.
201 #
202 # The configuration for coaddDriver.py allows detection to be turned
203 # of in the event that fake objects are to be added during the
204 # detection process. This allows the long co-addition process to be
205 # run once, and multiple different MultiBand reruns (with different
206 # fake objects) to exist from the same base co-addition.
207 #
208 # However, we only re-run detection if doDetection is explicitly True
209 # here (this should always be the opposite of coaddDriver.doDetection);
210 # otherwise we have no way to tell reliably whether any detections
211 # present in an input repo are safe to use.
212 if self.config.doDetection:
213 detectionList = []
214 for patchRef in patchRefList:
215 if ("detectCoaddSources" in self.reuse and
216 patchRef.datasetExists(self.coaddType + "Coadd_calexp", write=True)):
217 self.log.info("Skipping detectCoaddSources for %s; output already exists." %
218 patchRef.dataId)
219 continue
220 if not patchRef.datasetExists(self.coaddType + "Coadd"):
221 self.log.debug("Not processing %s; required input %sCoadd missing." %
222 (patchRef.dataId, self.config.coaddName))
223 continue
224 detectionList.append(patchRef)
225
226 pool.map(self.runDetection, detectionList)
227
228 patchRefList = [patchRef for patchRef in patchRefList if
229 patchRef.datasetExists(self.coaddType + "Coadd_calexp") and
230 patchRef.datasetExists(self.config.coaddName + "Coadd_det",
231 write=self.config.doDetection)]
232 dataIdList = [patchRef.dataId for patchRef in patchRefList]
233
234 # Group by patch
235 patches = {}
236 tract = None
237 for patchRef in patchRefList:
238 dataId = patchRef.dataId
239 if tract is None:
240 tract = dataId["tract"]
241 else:
242 assert tract == dataId["tract"]
243
244 patch = dataId["patch"]
245 if patch not in patches:
246 patches[patch] = []
247 patches[patch].append(dataId)
248
249 pool.map(self.runMergeDetections, patches.values())
250
251 # Deblend merged detections, and test for reprocessing
252 #
253 # The reprocessing allows us to have multiple attempts at deblending large footprints. Large
254 # footprints can suck up a lot of memory in the deblender, which means that when we process on a
255 # cluster, we want to refuse to deblend them (they're flagged "deblend.parent-too-big"). But since
256 # they may have astronomically interesting data, we want the ability to go back and reprocess them
257 # with a more permissive configuration when we have more memory or processing time.
258 #
259 # self.runDeblendMerged will return whether there are any footprints in that image that required
260 # reprocessing. We need to convert that list of booleans into a dict mapping the patchId (x,y) to
261 # a boolean. That tells us whether the merge measurement and forced photometry need to be re-run on
262 # a particular patch.
263 #
264 # This determination of which patches need to be reprocessed exists only in memory (the measurements
265 # have been written, clobbering the old ones), so if there was an exception we would lose this
266 # information, leaving things in an inconsistent state (measurements, merged measurements and
267 # forced photometry old). To attempt to preserve this status, we touch a file (dataset named
268 # "deepCoadd_multibandReprocessing") --- if this file exists, we need to re-run the measurements,
269 # merge and forced photometry.
270 #
271 # This is, hopefully, a temporary workaround until we can improve the
272 # deblender.
273 try:
274 reprocessed = pool.map(self.runDeblendMerged, patches.values())
275 finally:
276 if self.config.reprocessing:
277 patchReprocessing = {}
278 for dataId, reprocess in zip(dataIdList, reprocessed):
279 patchId = dataId["patch"]
280 patchReprocessing[patchId] = patchReprocessing.get(
281 patchId, False) or reprocess
282 # Persist the determination, to make error recover easier
283 reprocessDataset = self.config.coaddName + "Coadd_multibandReprocessing"
284 for patchId in patchReprocessing:
285 if not patchReprocessing[patchId]:
286 continue
287 dataId = dict(tract=tract, patch=patchId)
288 if patchReprocessing[patchId]:
289 filename = butler.get(
290 reprocessDataset + "_filename", dataId)[0]
291 open(filename, 'a').close() # Touch file
292 elif butler.datasetExists(reprocessDataset, dataId):
293 # We must have failed at some point while reprocessing
294 # and we're starting over
295 patchReprocessing[patchId] = True
296
297 # Only process patches that have been identifiedz as needing it
298 pool.map(self.runMeasurements, [dataId1 for dataId1 in dataIdList if not self.config.reprocessing or
299 patchReprocessing[dataId1["patch"]]])
300 pool.map(self.runMergeMeasurements, [idList for patchId, idList in patches.items() if
301 not self.config.reprocessing or patchReprocessing[patchId]])
302 pool.map(self.runForcedPhot, [dataId1 for dataId1 in dataIdList if not self.config.reprocessing or
303 patchReprocessing[dataId1["patch"]]])
304
305 # Remove persisted reprocessing determination
306 if self.config.reprocessing:
307 for patchId in patchReprocessing:
308 if not patchReprocessing[patchId]:
309 continue
310 dataId = dict(tract=tract, patch=patchId)
311 filename = butler.get(
312 reprocessDataset + "_filename", dataId)[0]
313 os.unlink(filename)
314
315 def runDetection(self, cache, patchRef):
316 """! Run detection on a patch
317
318 Only slave nodes execute this method.
319
320 @param cache: Pool cache, containing butler
321 @param patchRef: Patch on which to do detection
322 """
323 with self.logOperation("do detections on {}".format(patchRef.dataId)):
324 idFactory = self.detectCoaddSources.makeIdFactory(patchRef)
325 coadd = patchRef.get(self.coaddType + "Coadd", immediate=True)
326 expId = getGen3CoaddExposureId(patchRef, coaddName=self.config.coaddName, log=self.log)
327 self.detectCoaddSources.emptyMetadata()
328 detResults = self.detectCoaddSources.run(coadd, idFactory, expId=expId)
329 self.detectCoaddSources.write(detResults, patchRef)
330 self.detectCoaddSources.writeMetadata(patchRef)
331
332 def runMergeDetections(self, cache, dataIdList):
333 """!Run detection merging on a patch
334
335 Only slave nodes execute this method.
336
337 @param cache: Pool cache, containing butler
338 @param dataIdList: List of data identifiers for the patch in different filters
339 """
340 with self.logOperation("merge detections from %s" % (dataIdList,)):
341 dataRefList = [getDataRef(cache.butler, dataId, self.coaddType + "Coadd_calexp") for
342 dataId in dataIdList]
343 if ("mergeCoaddDetections" in self.reuse and
344 dataRefList[0].datasetExists(self.config.coaddName + "Coadd_mergeDet", write=True)):
345 self.log.info("Skipping mergeCoaddDetections for %s; output already exists." %
346 dataRefList[0].dataId)
347 return
348 self.mergeCoaddDetections.runDataRef(dataRefList)
349
350 def runDeblendMerged(self, cache, dataIdList):
351 """Run the deblender on a list of dataId's
352
353 Only slave nodes execute this method.
354
355 Parameters
356 ----------
357 cache: Pool cache
358 Pool cache with butler.
359 dataIdList: list
360 Data identifier for patch in each band.
361
362 Returns
363 -------
364 result: bool
365 whether the patch requires reprocessing.
366 """
367 with self.logOperation("deblending %s" % (dataIdList,)):
368 dataRefList = [getDataRef(cache.butler, dataId, self.coaddType + "Coadd_calexp") for
369 dataId in dataIdList]
370 reprocessing = False # Does this patch require reprocessing?
371 if ("deblendCoaddSources" in self.reuse and
372 all([dataRef.datasetExists(self.config.coaddName + "Coadd_" + self.measurementInput,
373 write=True) for dataRef in dataRefList])):
374 if not self.config.reprocessing:
375 self.log.info("Skipping deblendCoaddSources for %s; output already exists" % dataIdList)
376 return False
377
378 # Footprints are the same every band, therefore we can check just one
379 catalog = dataRefList[0].get(self.config.coaddName + "Coadd_" + self.measurementInput)
380 bigFlag = catalog["deblend_parentTooBig"]
381 # Footprints marked too large by the previous deblender run
382 numOldBig = bigFlag.sum()
383 if numOldBig == 0:
384 self.log.info("No large footprints in %s" % (dataRefList[0].dataId))
385 return False
386
387 # This if-statement can be removed after DM-15662
388 if self.config.deblendCoaddSources.simultaneous:
389 deblender = self.deblendCoaddSources.multiBandDeblend
390 else:
391 deblender = self.deblendCoaddSources.singleBandDeblend
392
393 # isLargeFootprint() can potentially return False for a source that is marked
394 # too big in the catalog, because of "new"/different deblender configs.
395 # numNewBig is the number of footprints that *will* be too big if reprocessed
396 numNewBig = sum((deblender.isLargeFootprint(src.getFootprint()) for
397 src in catalog[bigFlag]))
398 if numNewBig == numOldBig:
399 self.log.info("All %d formerly large footprints continue to be large in %s" %
400 (numOldBig, dataRefList[0].dataId,))
401 return False
402 self.log.info("Found %d large footprints to be reprocessed in %s" %
403 (numOldBig - numNewBig, [dataRef.dataId for dataRef in dataRefList]))
404 reprocessing = True
405
406 self.deblendCoaddSources.runDataRef(dataRefList)
407 return reprocessing
408
409 def runMeasurements(self, cache, dataId):
410 """Run measurement on a patch for a single filter
411
412 Only slave nodes execute this method.
413
414 Parameters
415 ----------
416 cache: Pool cache
417 Pool cache, with butler
418 dataId: dataRef
419 Data identifier for patch
420 """
421 with self.logOperation("measurements on %s" % (dataId,)):
422 dataRef = getDataRef(cache.butler, dataId, self.coaddType + "Coadd_calexp")
423 if ("measureCoaddSources" in self.reuse and
424 not self.config.reprocessing and
425 dataRef.datasetExists(self.config.coaddName + "Coadd_meas", write=True)):
426 self.log.info("Skipping measuretCoaddSources for %s; output already exists" % dataId)
427 return
428 self.measureCoaddSources.runDataRef(dataRef)
429
430 def runMergeMeasurements(self, cache, dataIdList):
431 """!Run measurement merging on a patch
432
433 Only slave nodes execute this method.
434
435 @param cache: Pool cache, containing butler
436 @param dataIdList: List of data identifiers for the patch in different filters
437 """
438 with self.logOperation("merge measurements from %s" % (dataIdList,)):
439 dataRefList = [getDataRef(cache.butler, dataId, self.coaddType + "Coadd_calexp") for
440 dataId in dataIdList]
441 if ("mergeCoaddMeasurements" in self.reuse and
442 not self.config.reprocessing and
443 dataRefList[0].datasetExists(self.config.coaddName + "Coadd_ref", write=True)):
444 self.log.info("Skipping mergeCoaddMeasurements for %s; output already exists" %
445 dataRefList[0].dataId)
446 return
447 self.mergeCoaddMeasurements.runDataRef(dataRefList)
448
449 def runForcedPhot(self, cache, dataId):
450 """!Run forced photometry on a patch for a single filter
451
452 Only slave nodes execute this method.
453
454 @param cache: Pool cache, with butler
455 @param dataId: Data identifier for patch
456 """
457 with self.logOperation("forced photometry on %s" % (dataId,)):
458 dataRef = getDataRef(cache.butler, dataId,
459 self.coaddType + "Coadd_calexp")
460 if ("forcedPhotCoadd" in self.reuse and
461 not self.config.reprocessing and
462 dataRef.datasetExists(self.config.coaddName + "Coadd_forced_src", write=True)):
463 self.log.info("Skipping forcedPhotCoadd for %s; output already exists" % dataId)
464 return
465 self.forcedPhotCoadd.runDataRef(dataRef)
466
467 def writeMetadata(self, dataRef):
468 """We don't collect any metadata, so skip"""
469 pass
Defines the fields and offsets for a table.
Definition: Schema.h:51
def logOperation(self, operation, catch=False, trace=True)
Provide a context manager for logging an operation.
Definition: parallel.py:502
def batchWallTime(cls, time, parsedCmd, numCpus)
Return walltime request for batch job.
def runDetection(self, cache, patchRef)
Run detection on a patch.
def runMergeMeasurements(self, cache, dataIdList)
Run measurement merging on a patch.
def runMergeDetections(self, cache, dataIdList)
Run detection merging on a patch.
def runDataRef(self, patchRefList)
Run multiband processing on coadds.
def runForcedPhot(self, cache, dataId)
Run forced photometry on a patch for a single filter.
def __init__(self, butler=None, schema=None, refObjLoader=None, reuse=tuple(), **kwargs)
def __init__(self, TaskClass, parsedCmd, doReturnResults=False)
def unpickle(factory, args, kwargs)