22 from __future__
import absolute_import, division
28 from builtins
import str
29 from builtins
import object
32 from lsst.base import disableImplicitThreading
33 import lsst.afw.table
as afwTable
34 from .task
import Task, TaskError
35 from .struct
import Struct
36 from .argumentParser
import ArgumentParser
40 __all__ = [
"CmdLineTask",
"TaskRunner",
"ButlerInitializedTaskRunner"]
43 def _poolFunctionWrapper(function, arg):
44 """Wrapper around function to catch exceptions that don't inherit from `Exception`. 46 Such exceptions aren't caught by multiprocessing, which causes the slave process to crash and you end up 55 cls, exc, tb = sys.exc_info()
56 log = Log.getDefaultLogger()
57 log.warn(
"Unhandled exception %s (%s):\n%s" % (cls.__name__, exc, traceback.format_exc()))
58 raise Exception(
"Unhandled exception: %s (%s)" % (cls.__name__, exc))
61 def _runPool(pool, timeout, function, iterable):
62 """Wrapper around ``pool.map_async``, to handle timeout 64 This is required so as to trigger an immediate interrupt on the KeyboardInterrupt (Ctrl-C); see 65 http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool 67 Further wraps the function in ``_poolFunctionWrapper`` to catch exceptions 68 that don't inherit from `Exception`. 70 return pool.map_async(functools.partial(_poolFunctionWrapper, function), iterable).get(timeout)
73 @contextlib.contextmanager
75 """Context manager for profiling with cProfile. 81 Filename to which to write profile (profiling disabled if `None` or empty). 82 log : `lsst.log.Log`, optional 83 Log object for logging the profile operations. 85 If profiling is enabled, the context manager returns the cProfile.Profile object (otherwise 86 it returns None), which allows additional control over profiling. You can obtain this using 87 the "as" clause, e.g.: 89 with profile(filename) as prof: 92 The output cumulative profile can be printed with a command-line like:: 94 python -c 'import pstats; pstats.Stats("<filename>").sort_stats("cumtime").print_stats(30)' 100 from cProfile
import Profile
103 log.info(
"Enabling cProfile profiling")
107 profile.dump_stats(filename)
109 log.info(
"cProfile stats written to %s" % filename)
113 """Run a command-line task, using `multiprocessing` if requested. 117 TaskClass : `lsst.pipe.base.Task` subclass 118 The class of the task to run. 119 parsedCmd : `argparse.Namespace` 120 The parsed command-line arguments, as returned by the task's argument parser's 121 `~lsst.pipe.base.ArgumentParser.parse_args` method. 125 Do not store ``parsedCmd``, as this instance is pickled (if multiprocessing) and parsedCmd may 126 contain non-picklable elements. It certainly contains more data than we need to send to each 127 instance of the task. 128 doReturnResults : `bool`, optional 129 Should run return the collected result from each invocation of the task? This is only intended for 130 unit tests and similar use. It can easily exhaust memory (if the task returns enough data and you 131 call it enough times) and it will fail when using multiprocessing if the returned data cannot be 134 Note that even if ``doReturnResults`` is False a struct with a single member "exitStatus" is returned, 135 with value 0 or 1 to be returned to the unix shell. 140 If multiprocessing is requested (and the task supports it) but the multiprocessing library cannot be 145 Each command-line task (subclass of `lsst.pipe.base.CmdLineTask`) has a task runner. By default it is this 146 class, but some tasks require a subclass. See the manual :ref:`creating-a-command-line-task` for more 147 information. See `CmdLineTask.parseAndRun` to see how a task runner is used. 149 You may use this task runner for your command-line task if your task has a run method that takes exactly 150 one argument: a butler data reference. Otherwise you must provide a task-specific subclass of this runner 151 for your task's ``RunnerClass`` that overrides `TaskRunner.getTargetList` and possibly 152 `TaskRunner.__call__`. See `TaskRunner.getTargetList` for details. 154 This design matches the common pattern for command-line tasks: the run method takes a single data 155 reference, of some suitable name. Additional arguments are rare, and if present, require a subclass of 156 `TaskRunner` that calls these additional arguments by name. 158 Instances of this class must be picklable in order to be compatible with multiprocessing. If 159 multiprocessing is requested (``parsedCmd.numProcesses > 1``) then `run` calls `prepareForMultiProcessing` 160 to jettison optional non-picklable elements. If your task runner is not compatible with multiprocessing 161 then indicate this in your task by setting class variable ``canMultiprocess=False``. 163 Due to a `python bug`__, handling a `KeyboardInterrupt` properly `requires specifying a timeout`__. This 164 timeout (in sec) can be specified as the ``timeout`` element in the output from 165 `~lsst.pipe.base.ArgumentParser` (the ``parsedCmd``), if available, otherwise we use `TaskRunner.TIMEOUT`. 167 .. __: http://bugs.python.org/issue8296 168 .. __: http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool 172 """Default timeout (seconds) for multiprocessing.""" 174 def __init__(self, TaskClass, parsedCmd, doReturnResults=False):
184 self.
timeout = getattr(parsedCmd,
'timeout',
None)
189 if not TaskClass.canMultiprocess:
190 self.
log.warn(
"This task does not support multiprocessing; using one process")
194 """Prepare this instance for multiprocessing 196 Optional non-picklable elements are removed. 198 This is only called if the task is run under multiprocessing. 203 """Run the task on all targets. 207 parsedCmd : `argparse.Namespace` 208 Parsed command `argparse.Namespace`. 213 A list of results returned by `TaskRunner.__call__`, or an empty list if `TaskRunner.__call__` 214 is not called (e.g. if `TaskRunner.precall` returns `False`). See `TaskRunner.__call__` 219 The task is run under multiprocessing if `TaskRunner.numProcesses` is more than 1; otherwise 220 processing is serial. 224 disableImplicitThreading()
225 import multiprocessing
227 pool = multiprocessing.Pool(processes=self.
numProcesses, maxtasksperchild=1)
228 mapFunc = functools.partial(_runPool, pool, self.
timeout)
234 profileName = parsedCmd.profile
if hasattr(parsedCmd,
"profile")
else None 237 if len(targetList) > 0:
238 with
profile(profileName, log):
240 resultList = list(mapFunc(self, targetList))
242 log.warn(
"Not running the task because there is no data to process; " 243 "you may preview data using \"--show data\"")
253 """Get a list of (dataRef, kwargs) for `TaskRunner.__call__`. 257 parsedCmd : `argparse.Namespace` 258 The parsed command object returned by `lsst.pipe.base.argumentParser.ArgumentParser.parse_args`. 260 Any additional keyword arguments. In the default `TaskRunner` this is an empty dict, but having 261 it simplifies overriding `TaskRunner` for tasks whose run method takes additional arguments 262 (see case (1) below). 266 The default implementation of `TaskRunner.getTargetList` and `TaskRunner.__call__` works for any 267 command-line task whose run method takes exactly one argument: a data reference. Otherwise you 268 must provide a variant of TaskRunner that overrides `TaskRunner.getTargetList` and possibly 269 `TaskRunner.__call__`. There are two cases. 273 If your command-line task has a ``run`` method that takes one data reference followed by additional 274 arguments, then you need only override `TaskRunner.getTargetList` to return the additional arguments 275 as an argument dict. To make this easier, your overridden version of `~TaskRunner.getTargetList` may 276 call `TaskRunner.getTargetList` with the extra arguments as keyword arguments. For example, the 277 following adds an argument dict containing a single key: "calExpList", whose value is the list of data 278 IDs for the calexp ID argument:: 280 def getTargetList(parsedCmd): 281 return TaskRunner.getTargetList( 283 calExpList=parsedCmd.calexp.idList 286 It is equivalent to this slightly longer version:: 289 def getTargetList(parsedCmd): 290 argDict = dict(calExpList=parsedCmd.calexp.idList) 291 return [(dataId, argDict) for dataId in parsedCmd.id.idList] 295 If your task does not meet condition (1) then you must override both TaskRunner.getTargetList and 296 `TaskRunner.__call__`. You may do this however you see fit, so long as `TaskRunner.getTargetList` 297 returns a list, each of whose elements is sent to `TaskRunner.__call__`, which runs your task. 299 return [(ref, kwargs)
for ref
in parsedCmd.id.refList]
302 """Create a Task instance. 307 Parsed command-line options (used for extra task args by some task runners). 309 Args tuple passed to `TaskRunner.__call__` (used for extra task arguments by some task runners). 313 ``makeTask`` can be called with either the ``parsedCmd`` argument or ``args`` argument set to None, 314 but it must construct identical Task instances in either case. 316 Subclasses may ignore this method entirely if they reimplement both `TaskRunner.precall` and 317 `TaskRunner.__call__`. 321 def _precallImpl(self, task, parsedCmd):
322 """The main work of `precall`. 324 We write package versions, schemas and configs, or compare these to existing files on disk if present. 326 if not parsedCmd.noVersions:
327 task.writePackageVersions(parsedCmd.butler, clobber=parsedCmd.clobberVersions)
332 """Hook for code that should run exactly once, before multiprocessing. 336 Must return True if `TaskRunner.__call__` should subsequently be called. 340 Implementations must take care to ensure that no unpicklable 341 attributes are added to the TaskRunner itself, for compatibility 342 with multiprocessing. 344 The default implementation writes package versions, schemas and configs, or compares them to existing 345 files on disk if present. 347 task = self.
makeTask(parsedCmd=parsedCmd)
354 except Exception
as e:
355 task.log.fatal(
"Failed in task initialization: %s", e)
356 if not isinstance(e, TaskError):
357 traceback.print_exc(file=sys.stderr)
362 """Run the Task on a single target. 367 Arguments for Task.run() 371 struct : `lsst.pipe.base.Struct` 372 Contains these fields if ``doReturnResults`` is `True`: 374 - ``dataRef``: the provided data reference. 375 - ``metadata``: task metadata after execution of run. 376 - ``result``: result returned by task run, or `None` if the task fails. 377 - ``exitStatus`: 0 if the task completed successfully, 1 otherwise. 379 If ``doReturnResults`` is `False` the struct contains: 381 - ``exitStatus`: 0 if the task completed successfully, 1 otherwise. 385 This default implementation assumes that the ``args`` is a tuple 386 containing a data reference and a dict of keyword arguments. 390 If you override this method and wish to return something when ``doReturnResults`` is `False`, 391 then it must be picklable to support multiprocessing and it should be small enough that pickling 392 and unpickling do not add excessive overhead. 394 dataRef, kwargs = args
396 self.
log = Log.getDefaultLogger()
397 if hasattr(dataRef,
"dataId"):
398 self.
log.MDC(
"LABEL", str(dataRef.dataId))
399 elif isinstance(dataRef, (list, tuple)):
400 self.
log.MDC(
"LABEL", str([ref.dataId
for ref
in dataRef
if hasattr(ref,
"dataId")]))
405 result = task.run(dataRef, **kwargs)
408 result = task.run(dataRef, **kwargs)
409 except Exception
as e:
415 eName = type(e).__name__
416 if hasattr(dataRef,
"dataId"):
417 task.log.fatal(
"Failed on dataId=%s: %s: %s", dataRef.dataId, eName, e)
418 elif isinstance(dataRef, (list, tuple)):
419 task.log.fatal(
"Failed on dataIds=[%s]: %s: %s",
420 ", ".join(str(ref.dataId)
for ref
in dataRef), eName, e)
422 task.log.fatal(
"Failed on dataRef=%s: %s: %s", dataRef, eName, e)
424 if not isinstance(e, TaskError):
425 traceback.print_exc(file=sys.stderr)
426 task.writeMetadata(dataRef)
429 self.
log.MDCRemove(
"LABEL")
433 exitStatus=exitStatus,
435 metadata=task.metadata,
440 exitStatus=exitStatus,
445 """A TaskRunner for `CmdLineTask`\ s that require a ``butler`` keyword argument to be passed to 450 """A variant of the base version that passes a butler argument to the task's constructor. 454 parsedCmd : `argparse.Namespace` 455 Parsed command-line options, as returned by the `~lsst.pipe.base.ArgumentParser`; if specified 456 then args is ignored. 458 Other arguments; if ``parsedCmd`` is `None` then this must be specified. 463 Raised if ``parsedCmd`` and ``args`` are both `None`. 465 if parsedCmd
is not None:
466 butler = parsedCmd.butler
467 elif args
is not None:
468 dataRef, kwargs = args
469 butler = dataRef.butlerSubset.butler
471 raise RuntimeError(
"parsedCmd or args must be specified")
476 """Base class for command-line tasks: tasks that may be executed from the command-line. 480 See :ref:`task-framework-overview` to learn what tasks are and :ref:`creating-a-command-line-task` for 481 more information about writing command-line tasks. 483 Subclasses must specify the following class variables: 485 - ``ConfigClass``: configuration class for your task (a subclass of `lsst.pex.config.Config`, or if your 486 task needs no configuration, then `lsst.pex.config.Config` itself). 487 - ``_DefaultName``: default name used for this task (a str). 489 Subclasses may also specify the following class variables: 491 - ``RunnerClass``: a task runner class. The default is ``TaskRunner``, which works for any task 492 with a run method that takes exactly one argument: a data reference. If your task does 493 not meet this requirement then you must supply a variant of ``TaskRunner``; see ``TaskRunner`` 494 for more information. 495 - ``canMultiprocess``: the default is `True`; set `False` if your task does not support multiprocessing. 497 Subclasses must specify a method named ``run``: 499 - By default ``run`` accepts a single butler data reference, but you can specify an alternate task runner 500 (subclass of ``TaskRunner``) as the value of class variable ``RunnerClass`` if your run method needs 502 - ``run`` is expected to return its data in a `lsst.pipe.base.Struct`. This provides safety for evolution 503 of the task since new values may be added without harming existing code. 504 - The data returned by ``run`` must be picklable if your task is to support multiprocessing. 506 RunnerClass = TaskRunner
507 canMultiprocess =
True 511 """A hook to allow a task to change the values of its config *after* the camera-specific 512 overrides are loaded but before any command-line overrides are applied. 516 config : instance of task's ``ConfigClass`` 521 This is necessary in some cases because the camera-specific overrides may retarget subtasks, 522 wiping out changes made in ConfigClass.setDefaults. See LSST Trac ticket #2282 for more discussion. 526 This is called by CmdLineTask.parseAndRun; other ways of constructing a config will not apply 532 def parseAndRun(cls, args=None, config=None, log=None, doReturnResults=False):
533 """Parse an argument list and run the command. 537 args : `list`, optional 538 List of command-line arguments; if `None` use `sys.argv`. 539 config : `lsst.pex.config.Config`-type, optional 540 Config for task. If `None` use `Task.ConfigClass`. 541 log : `lsst.log.Log`-type, optional 542 Log. If `None` use the default log. 543 doReturnResults : `bool`, optional 544 If `True`, return the results of this task. Default is `False`. This is only intended for 545 unit tests and similar use. It can easily exhaust memory (if the task returns enough data and you 546 call it enough times) and it will fail when using multiprocessing if the returned data cannot be 551 struct : `lsst.pipe.base.Struct` 554 - ``argumentParser``: the argument parser. 555 - ``parsedCmd``: the parsed command returned by the argument parser's 556 `lsst.pipe.base.ArgumentParser.parse_args` method. 557 - ``taskRunner``: the task runner used to run the task (an instance of `Task.RunnerClass`). 558 - ``resultList``: results returned by the task runner's ``run`` method, one entry per invocation. 559 This will typically be a list of `None` unless ``doReturnResults`` is `True`; 560 see `Task.RunnerClass` (`TaskRunner` by default) for more information. 564 Calling this method with no arguments specified is the standard way to run a command-line task 565 from the command-line. For an example see ``pipe_tasks`` ``bin/makeSkyMap.py`` or almost any other 566 file in that directory. 568 If one or more of the dataIds fails then this routine will exit (with a status giving the 569 number of failed dataIds) rather than returning this struct; this behaviour can be 570 overridden by specifying the ``--noExit`` command-line option. 573 commandAsStr =
" ".join(sys.argv)
580 config = cls.ConfigClass()
581 parsedCmd = argumentParser.parse_args(config=config, args=args, log=log, override=cls.
applyOverrides)
583 parsedCmd.log.info(
"Running: %s", commandAsStr)
585 taskRunner = cls.
RunnerClass(TaskClass=cls, parsedCmd=parsedCmd, doReturnResults=doReturnResults)
586 resultList = taskRunner.run(parsedCmd)
589 nFailed = sum(((res.exitStatus != 0)
for res
in resultList))
590 except (TypeError, AttributeError)
as e:
592 parsedCmd.log.warn(
"Unable to retrieve exit status (%s); assuming success", e)
597 parsedCmd.log.error(
"%d dataRefs failed; not exiting as --noExit was set", nFailed)
602 argumentParser=argumentParser,
604 taskRunner=taskRunner,
605 resultList=resultList,
609 def _makeArgumentParser(cls):
610 """Create and return an argument parser. 614 parser : `lsst.pipe.base.ArgumentParser` 615 The argument parser for this task. 619 By default this returns an `~lsst.pipe.base.ArgumentParser` with one ID argument named `--id` of 620 dataset type ``raw``. 622 Your task subclass may need to override this method to change the dataset type or data ref level, 623 or to add additional data ID arguments. If you add additional data ID arguments or your task's 624 run method takes more than a single data reference then you will also have to provide a task-specific 625 task runner (see TaskRunner for more information). 628 parser.add_id_argument(name=
"--id", datasetType=
"raw",
629 help=
"data IDs, e.g. --id visit=12345 ccd=1,2^0,3")
633 """Write the configuration used for processing the data, or check that an existing 634 one is equal to the new one if present. 638 butler : `lsst.daf.persistence.Butler` 639 Data butler used to write the config. The config is written to dataset type 640 `CmdLineTask._getConfigName`. 641 clobber : `bool`, optional 642 A boolean flag that controls what happens if a config already has been saved: 643 - `True`: overwrite or rename the existing config, depending on ``doBackup``. 644 - `False`: raise `TaskError` if this config does not match the existing config. 645 doBackup : bool, optional 646 Set to `True` to backup the config files if clobbering. 649 if configName
is None:
652 butler.put(self.
config, configName, doBackup=doBackup)
653 elif butler.datasetExists(configName, write=
True):
656 oldConfig = butler.get(configName, immediate=
True)
657 except Exception
as exc:
658 raise type(exc)(
"Unable to read stored config file %s (%s); consider using --clobber-config" %
661 def logConfigMismatch(msg):
662 self.
log.fatal(
"Comparing configuration: %s", msg)
664 if not self.
config.compare(oldConfig, shortcut=
False, output=logConfigMismatch):
666 (
"Config does not match existing task config %r on disk; tasks configurations " +
667 "must be consistent within the same output repo (override with --clobber-config)") %
670 butler.put(self.
config, configName)
673 """Write the schemas returned by `lsst.pipe.base.Task.getAllSchemaCatalogs`. 677 butler : `lsst.daf.persistence.Butler` 678 Data butler used to write the schema. Each schema is written to the dataset type specified as the 679 key in the dict returned by `~lsst.pipe.base.Task.getAllSchemaCatalogs`. 680 clobber : `bool`, optional 681 A boolean flag that controls what happens if a schema already has been saved: 682 - `True`: overwrite or rename the existing schema, depending on ``doBackup``. 683 - `False`: raise `TaskError` if this schema does not match the existing schema. 684 doBackup : `bool`, optional 685 Set to `True` to backup the schema files if clobbering. 689 If ``clobber`` is `False` and an existing schema does not match a current schema, 690 then some schemas may have been saved successfully and others may not, and there is no easy way to 694 schemaDataset = dataset +
"_schema" 696 butler.put(catalog, schemaDataset, doBackup=doBackup)
697 elif butler.datasetExists(schemaDataset, write=
True):
698 oldSchema = butler.get(schemaDataset, immediate=
True).getSchema()
699 if not oldSchema.compare(catalog.getSchema(), afwTable.Schema.IDENTICAL):
701 (
"New schema does not match schema %r on disk; schemas must be " +
702 " consistent within the same output repo (override with --clobber-config)") %
705 butler.put(catalog, schemaDataset)
708 """Write the metadata produced from processing the data. 713 Butler data reference used to write the metadata. 714 The metadata is written to dataset type `CmdLineTask._getMetadataName`. 718 if metadataName
is not None:
720 except Exception
as e:
721 self.
log.warn(
"Could not persist metadata for dataId=%s: %s", dataRef.dataId, e)
724 """Compare and write package versions. 728 butler : `lsst.daf.persistence.Butler` 729 Data butler used to read/write the package versions. 730 clobber : `bool`, optional 731 A boolean flag that controls what happens if versions already have been saved: 732 - `True`: overwrite or rename the existing version info, depending on ``doBackup``. 733 - `False`: raise `TaskError` if this version info does not match the existing. 734 doBackup : `bool`, optional 735 If `True` and clobbering, old package version files are backed up. 736 dataset : `str`, optional 737 Name of dataset to read/write. 742 Raised if there is a version mismatch with current and persisted lists of package versions. 746 Note that this operation is subject to a race condition. 748 packages = Packages.fromSystem()
751 return butler.put(packages, dataset, doBackup=doBackup)
752 if not butler.datasetExists(dataset, write=
True):
753 return butler.put(packages, dataset)
756 old = butler.get(dataset, immediate=
True)
757 except Exception
as exc:
758 raise type(exc)(
"Unable to read stored version dataset %s (%s); " 759 "consider using --clobber-versions or --no-versions" %
764 diff = packages.difference(old)
767 "Version mismatch (" +
768 "; ".join(
"%s: %s vs %s" % (pkg, diff[pkg][1], diff[pkg][0])
for pkg
in diff) +
769 "); consider using --clobber-versions or --no-versions")
771 extra = packages.extra(old)
774 butler.put(old, dataset, doBackup=doBackup)
776 def _getConfigName(self):
777 """Get the name of the config dataset type, or `None` if config is not to be persisted. 781 The name may depend on the config; that is why this is not a class method. 783 return self._DefaultName +
"_config" 785 def _getMetadataName(self):
786 """Get the name of the metadata dataset type, or `None` if metadata is not to be persisted. 790 The name may depend on the config; that is why this is not a class method. 792 return self._DefaultName +
"_metadata"
def _makeArgumentParser(cls)
def parseAndRun(cls, args=None, config=None, log=None, doReturnResults=False)
def _precallImpl(self, task, parsedCmd)
def getFullMetadata(self)
def writePackageVersions(self, butler, clobber=False, doBackup=True, dataset="packages")
def getAllSchemaCatalogs(self)
def writeSchemas(self, butler, clobber=False, doBackup=True)
def prepareForMultiProcessing(self)
def _getMetadataName(self)
def makeTask(self, parsedCmd=None, args=None)
def writeMetadata(self, dataRef)
def precall(self, parsedCmd)
def __init__(self, TaskClass, parsedCmd, doReturnResults=False)
def profile(filename, log=None)
def makeTask(self, parsedCmd=None, args=None)
def getTargetList(parsedCmd, kwargs)
def writeConfig(self, butler, clobber=False, doBackup=True)
def applyOverrides(cls, config)