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 _runPool(pool, timeout, function, iterable):
44 """Wrapper around ``pool.map_async``, to handle timeout 46 This is required so as to trigger an immediate interrupt on the KeyboardInterrupt (Ctrl-C); see 47 http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool 49 return pool.map_async(function, iterable).get(timeout)
52 @contextlib.contextmanager
54 """Context manager for profiling with cProfile. 60 Filename to which to write profile (profiling disabled if `None` or empty). 61 log : `lsst.log.Log`, optional 62 Log object for logging the profile operations. 64 If profiling is enabled, the context manager returns the cProfile.Profile object (otherwise 65 it returns None), which allows additional control over profiling. You can obtain this using 66 the "as" clause, e.g.: 68 with profile(filename) as prof: 71 The output cumulative profile can be printed with a command-line like:: 73 python -c 'import pstats; pstats.Stats("<filename>").sort_stats("cumtime").print_stats(30)' 79 from cProfile
import Profile
82 log.info(
"Enabling cProfile profiling")
86 profile.dump_stats(filename)
88 log.info(
"cProfile stats written to %s" % filename)
92 """Run a command-line task, using `multiprocessing` if requested. 96 TaskClass : `lsst.pipe.base.Task` subclass 97 The class of the task to run. 98 parsedCmd : `argparse.Namespace` 99 The parsed command-line arguments, as returned by the task's argument parser's 100 `~lsst.pipe.base.ArgumentParser.parse_args` method. 104 Do not store ``parsedCmd``, as this instance is pickled (if multiprocessing) and parsedCmd may 105 contain non-picklable elements. It certainly contains more data than we need to send to each 106 instance of the task. 107 doReturnResults : `bool`, optional 108 Should run return the collected result from each invocation of the task? This is only intended for 109 unit tests and similar use. It can easily exhaust memory (if the task returns enough data and you 110 call it enough times) and it will fail when using multiprocessing if the returned data cannot be 113 Note that even if ``doReturnResults`` is False a struct with a single member "exitStatus" is returned, 114 with value 0 or 1 to be returned to the unix shell. 119 If multiprocessing is requested (and the task supports it) but the multiprocessing library cannot be 124 Each command-line task (subclass of `lsst.pipe.base.CmdLineTask`) has a task runner. By default it is this 125 class, but some tasks require a subclass. See the manual :ref:`creating-a-command-line-task` for more 126 information. See `CmdLineTask.parseAndRun` to see how a task runner is used. 128 You may use this task runner for your command-line task if your task has a run method that takes exactly 129 one argument: a butler data reference. Otherwise you must provide a task-specific subclass of this runner 130 for your task's ``RunnerClass`` that overrides `TaskRunner.getTargetList` and possibly 131 `TaskRunner.__call__`. See `TaskRunner.getTargetList` for details. 133 This design matches the common pattern for command-line tasks: the run method takes a single data 134 reference, of some suitable name. Additional arguments are rare, and if present, require a subclass of 135 `TaskRunner` that calls these additional arguments by name. 137 Instances of this class must be picklable in order to be compatible with multiprocessing. If 138 multiprocessing is requested (``parsedCmd.numProcesses > 1``) then `run` calls `prepareForMultiProcessing` 139 to jettison optional non-picklable elements. If your task runner is not compatible with multiprocessing 140 then indicate this in your task by setting class variable ``canMultiprocess=False``. 142 Due to a `python bug`__, handling a `KeyboardInterrupt` properly `requires specifying a timeout`__. This 143 timeout (in sec) can be specified as the ``timeout`` element in the output from 144 `~lsst.pipe.base.ArgumentParser` (the ``parsedCmd``), if available, otherwise we use `TaskRunner.TIMEOUT`. 146 By default, we disable "implicit" threading -- ie, as provided by underlying numerical libraries such as 147 MKL or BLAS. This is designed to avoid thread contention both when a single command line task spawns 148 multiple processes and when multiple users are running on a shared system. Users can override this 149 behaviour by setting the ``LSST_ALLOW_IMPLICIT_THREADS`` environment variable. 151 .. __: http://bugs.python.org/issue8296 152 .. __: http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool 156 """Default timeout (seconds) for multiprocessing.""" 158 def __init__(self, TaskClass, parsedCmd, doReturnResults=False):
168 self.
timeout = getattr(parsedCmd,
'timeout',
None)
173 if not TaskClass.canMultiprocess:
174 self.
log.warn(
"This task does not support multiprocessing; using one process")
178 """Prepare this instance for multiprocessing 180 Optional non-picklable elements are removed. 182 This is only called if the task is run under multiprocessing. 187 """Run the task on all targets. 191 parsedCmd : `argparse.Namespace` 192 Parsed command `argparse.Namespace`. 197 A list of results returned by `TaskRunner.__call__`, or an empty list if `TaskRunner.__call__` 198 is not called (e.g. if `TaskRunner.precall` returns `False`). See `TaskRunner.__call__` 203 The task is run under multiprocessing if `TaskRunner.numProcesses` is more than 1; otherwise 204 processing is serial. 207 disableImplicitThreading()
209 import multiprocessing
211 pool = multiprocessing.Pool(processes=self.
numProcesses, maxtasksperchild=1)
212 mapFunc = functools.partial(_runPool, pool, self.
timeout)
218 profileName = parsedCmd.profile
if hasattr(parsedCmd,
"profile")
else None 221 if len(targetList) > 0:
222 with
profile(profileName, log):
224 resultList = list(mapFunc(self, targetList))
226 log.warn(
"Not running the task because there is no data to process; " 227 "you may preview data using \"--show data\"")
237 """Get a list of (dataRef, kwargs) for `TaskRunner.__call__`. 241 parsedCmd : `argparse.Namespace` 242 The parsed command object returned by `lsst.pipe.base.argumentParser.ArgumentParser.parse_args`. 244 Any additional keyword arguments. In the default `TaskRunner` this is an empty dict, but having 245 it simplifies overriding `TaskRunner` for tasks whose run method takes additional arguments 246 (see case (1) below). 250 The default implementation of `TaskRunner.getTargetList` and `TaskRunner.__call__` works for any 251 command-line task whose run method takes exactly one argument: a data reference. Otherwise you 252 must provide a variant of TaskRunner that overrides `TaskRunner.getTargetList` and possibly 253 `TaskRunner.__call__`. There are two cases. 257 If your command-line task has a ``run`` method that takes one data reference followed by additional 258 arguments, then you need only override `TaskRunner.getTargetList` to return the additional arguments 259 as an argument dict. To make this easier, your overridden version of `~TaskRunner.getTargetList` may 260 call `TaskRunner.getTargetList` with the extra arguments as keyword arguments. For example, the 261 following adds an argument dict containing a single key: "calExpList", whose value is the list of data 262 IDs for the calexp ID argument:: 264 def getTargetList(parsedCmd): 265 return TaskRunner.getTargetList( 267 calExpList=parsedCmd.calexp.idList 270 It is equivalent to this slightly longer version:: 273 def getTargetList(parsedCmd): 274 argDict = dict(calExpList=parsedCmd.calexp.idList) 275 return [(dataId, argDict) for dataId in parsedCmd.id.idList] 279 If your task does not meet condition (1) then you must override both TaskRunner.getTargetList and 280 `TaskRunner.__call__`. You may do this however you see fit, so long as `TaskRunner.getTargetList` 281 returns a list, each of whose elements is sent to `TaskRunner.__call__`, which runs your task. 283 return [(ref, kwargs)
for ref
in parsedCmd.id.refList]
286 """Create a Task instance. 291 Parsed command-line options (used for extra task args by some task runners). 293 Args tuple passed to `TaskRunner.__call__` (used for extra task arguments by some task runners). 297 ``makeTask`` can be called with either the ``parsedCmd`` argument or ``args`` argument set to None, 298 but it must construct identical Task instances in either case. 300 Subclasses may ignore this method entirely if they reimplement both `TaskRunner.precall` and 301 `TaskRunner.__call__`. 305 def _precallImpl(self, task, parsedCmd):
306 """The main work of `precall`. 308 We write package versions, schemas and configs, or compare these to existing files on disk if present. 310 if not parsedCmd.noVersions:
311 task.writePackageVersions(parsedCmd.butler, clobber=parsedCmd.clobberVersions)
316 """Hook for code that should run exactly once, before multiprocessing. 320 Must return True if `TaskRunner.__call__` should subsequently be called. 324 Implementations must take care to ensure that no unpicklable 325 attributes are added to the TaskRunner itself, for compatibility 326 with multiprocessing. 328 The default implementation writes package versions, schemas and configs, or compares them to existing 329 files on disk if present. 331 task = self.
makeTask(parsedCmd=parsedCmd)
338 except Exception
as e:
339 task.log.fatal(
"Failed in task initialization: %s", e)
340 if not isinstance(e, TaskError):
341 traceback.print_exc(file=sys.stderr)
346 """Run the Task on a single target. 351 Arguments for Task.run() 355 struct : `lsst.pipe.base.Struct` 356 Contains these fields if ``doReturnResults`` is `True`: 358 - ``dataRef``: the provided data reference. 359 - ``metadata``: task metadata after execution of run. 360 - ``result``: result returned by task run, or `None` if the task fails. 361 - ``exitStatus``: 0 if the task completed successfully, 1 otherwise. 363 If ``doReturnResults`` is `False` the struct contains: 365 - ``exitStatus``: 0 if the task completed successfully, 1 otherwise. 369 This default implementation assumes that the ``args`` is a tuple 370 containing a data reference and a dict of keyword arguments. 374 If you override this method and wish to return something when ``doReturnResults`` is `False`, 375 then it must be picklable to support multiprocessing and it should be small enough that pickling 376 and unpickling do not add excessive overhead. 378 dataRef, kwargs = args
380 self.
log = Log.getDefaultLogger()
381 if hasattr(dataRef,
"dataId"):
382 self.
log.MDC(
"LABEL", str(dataRef.dataId))
383 elif isinstance(dataRef, (list, tuple)):
384 self.
log.MDC(
"LABEL", str([ref.dataId
for ref
in dataRef
if hasattr(ref,
"dataId")]))
389 result = task.run(dataRef, **kwargs)
392 result = task.run(dataRef, **kwargs)
393 except Exception
as e:
399 eName = type(e).__name__
400 if hasattr(dataRef,
"dataId"):
401 task.log.fatal(
"Failed on dataId=%s: %s: %s", dataRef.dataId, eName, e)
402 elif isinstance(dataRef, (list, tuple)):
403 task.log.fatal(
"Failed on dataIds=[%s]: %s: %s",
404 ", ".join(str(ref.dataId)
for ref
in dataRef), eName, e)
406 task.log.fatal(
"Failed on dataRef=%s: %s: %s", dataRef, eName, e)
408 if not isinstance(e, TaskError):
409 traceback.print_exc(file=sys.stderr)
415 task.writeMetadata(dataRef)
418 self.
log.MDCRemove(
"LABEL")
422 exitStatus=exitStatus,
424 metadata=task.metadata,
429 exitStatus=exitStatus,
434 """A `TaskRunner` for `CmdLineTask`\ s that require a ``butler`` keyword argument to be passed to 439 """A variant of the base version that passes a butler argument to the task's constructor. 443 parsedCmd : `argparse.Namespace` 444 Parsed command-line options, as returned by the `~lsst.pipe.base.ArgumentParser`; if specified 445 then args is ignored. 447 Other arguments; if ``parsedCmd`` is `None` then this must be specified. 452 Raised if ``parsedCmd`` and ``args`` are both `None`. 454 if parsedCmd
is not None:
455 butler = parsedCmd.butler
456 elif args
is not None:
457 dataRef, kwargs = args
458 butler = dataRef.butlerSubset.butler
460 raise RuntimeError(
"parsedCmd or args must be specified")
465 """Base class for command-line tasks: tasks that may be executed from the command-line. 469 See :ref:`task-framework-overview` to learn what tasks are and :ref:`creating-a-command-line-task` for 470 more information about writing command-line tasks. 472 Subclasses must specify the following class variables: 474 - ``ConfigClass``: configuration class for your task (a subclass of `lsst.pex.config.Config`, or if your 475 task needs no configuration, then `lsst.pex.config.Config` itself). 476 - ``_DefaultName``: default name used for this task (a str). 478 Subclasses may also specify the following class variables: 480 - ``RunnerClass``: a task runner class. The default is ``TaskRunner``, which works for any task 481 with a run method that takes exactly one argument: a data reference. If your task does 482 not meet this requirement then you must supply a variant of ``TaskRunner``; see ``TaskRunner`` 483 for more information. 484 - ``canMultiprocess``: the default is `True`; set `False` if your task does not support multiprocessing. 486 Subclasses must specify a method named ``run``: 488 - By default ``run`` accepts a single butler data reference, but you can specify an alternate task runner 489 (subclass of ``TaskRunner``) as the value of class variable ``RunnerClass`` if your run method needs 491 - ``run`` is expected to return its data in a `lsst.pipe.base.Struct`. This provides safety for evolution 492 of the task since new values may be added without harming existing code. 493 - The data returned by ``run`` must be picklable if your task is to support multiprocessing. 495 RunnerClass = TaskRunner
496 canMultiprocess =
True 500 """A hook to allow a task to change the values of its config *after* the camera-specific 501 overrides are loaded but before any command-line overrides are applied. 505 config : instance of task's ``ConfigClass`` 510 This is necessary in some cases because the camera-specific overrides may retarget subtasks, 511 wiping out changes made in ConfigClass.setDefaults. See LSST Trac ticket #2282 for more discussion. 515 This is called by CmdLineTask.parseAndRun; other ways of constructing a config will not apply 521 def parseAndRun(cls, args=None, config=None, log=None, doReturnResults=False):
522 """Parse an argument list and run the command. 526 args : `list`, optional 527 List of command-line arguments; if `None` use `sys.argv`. 528 config : `lsst.pex.config.Config`-type, optional 529 Config for task. If `None` use `Task.ConfigClass`. 530 log : `lsst.log.Log`-type, optional 531 Log. If `None` use the default log. 532 doReturnResults : `bool`, optional 533 If `True`, return the results of this task. Default is `False`. This is only intended for 534 unit tests and similar use. It can easily exhaust memory (if the task returns enough data and you 535 call it enough times) and it will fail when using multiprocessing if the returned data cannot be 540 struct : `lsst.pipe.base.Struct` 543 - ``argumentParser``: the argument parser. 544 - ``parsedCmd``: the parsed command returned by the argument parser's 545 `lsst.pipe.base.ArgumentParser.parse_args` method. 546 - ``taskRunner``: the task runner used to run the task (an instance of `Task.RunnerClass`). 547 - ``resultList``: results returned by the task runner's ``run`` method, one entry per invocation. 548 This will typically be a list of `None` unless ``doReturnResults`` is `True`; 549 see `Task.RunnerClass` (`TaskRunner` by default) for more information. 553 Calling this method with no arguments specified is the standard way to run a command-line task 554 from the command-line. For an example see ``pipe_tasks`` ``bin/makeSkyMap.py`` or almost any other 555 file in that directory. 557 If one or more of the dataIds fails then this routine will exit (with a status giving the 558 number of failed dataIds) rather than returning this struct; this behaviour can be 559 overridden by specifying the ``--noExit`` command-line option. 562 commandAsStr =
" ".join(sys.argv)
569 config = cls.ConfigClass()
570 parsedCmd = argumentParser.parse_args(config=config, args=args, log=log, override=cls.
applyOverrides)
572 parsedCmd.log.info(
"Running: %s", commandAsStr)
574 taskRunner = cls.
RunnerClass(TaskClass=cls, parsedCmd=parsedCmd, doReturnResults=doReturnResults)
575 resultList = taskRunner.run(parsedCmd)
578 nFailed = sum(((res.exitStatus != 0)
for res
in resultList))
579 except (TypeError, AttributeError)
as e:
581 parsedCmd.log.warn(
"Unable to retrieve exit status (%s); assuming success", e)
586 parsedCmd.log.error(
"%d dataRefs failed; not exiting as --noExit was set", nFailed)
591 argumentParser=argumentParser,
593 taskRunner=taskRunner,
594 resultList=resultList,
598 def _makeArgumentParser(cls):
599 """Create and return an argument parser. 603 parser : `lsst.pipe.base.ArgumentParser` 604 The argument parser for this task. 608 By default this returns an `~lsst.pipe.base.ArgumentParser` with one ID argument named `--id` of 609 dataset type ``raw``. 611 Your task subclass may need to override this method to change the dataset type or data ref level, 612 or to add additional data ID arguments. If you add additional data ID arguments or your task's 613 run method takes more than a single data reference then you will also have to provide a task-specific 614 task runner (see TaskRunner for more information). 617 parser.add_id_argument(name=
"--id", datasetType=
"raw",
618 help=
"data IDs, e.g. --id visit=12345 ccd=1,2^0,3")
622 """Write the configuration used for processing the data, or check that an existing 623 one is equal to the new one if present. 627 butler : `lsst.daf.persistence.Butler` 628 Data butler used to write the config. The config is written to dataset type 629 `CmdLineTask._getConfigName`. 630 clobber : `bool`, optional 631 A boolean flag that controls what happens if a config already has been saved: 632 - `True`: overwrite or rename the existing config, depending on ``doBackup``. 633 - `False`: raise `TaskError` if this config does not match the existing config. 634 doBackup : bool, optional 635 Set to `True` to backup the config files if clobbering. 638 if configName
is None:
641 butler.put(self.
config, configName, doBackup=doBackup)
642 elif butler.datasetExists(configName, write=
True):
645 oldConfig = butler.get(configName, immediate=
True)
646 except Exception
as exc:
647 raise type(exc)(
"Unable to read stored config file %s (%s); consider using --clobber-config" %
650 def logConfigMismatch(msg):
651 self.
log.fatal(
"Comparing configuration: %s", msg)
653 if not self.
config.compare(oldConfig, shortcut=
False, output=logConfigMismatch):
655 (
"Config does not match existing task config %r on disk; tasks configurations " +
656 "must be consistent within the same output repo (override with --clobber-config)") %
659 butler.put(self.
config, configName)
662 """Write the schemas returned by `lsst.pipe.base.Task.getAllSchemaCatalogs`. 666 butler : `lsst.daf.persistence.Butler` 667 Data butler used to write the schema. Each schema is written to the dataset type specified as the 668 key in the dict returned by `~lsst.pipe.base.Task.getAllSchemaCatalogs`. 669 clobber : `bool`, optional 670 A boolean flag that controls what happens if a schema already has been saved: 671 - `True`: overwrite or rename the existing schema, depending on ``doBackup``. 672 - `False`: raise `TaskError` if this schema does not match the existing schema. 673 doBackup : `bool`, optional 674 Set to `True` to backup the schema files if clobbering. 678 If ``clobber`` is `False` and an existing schema does not match a current schema, 679 then some schemas may have been saved successfully and others may not, and there is no easy way to 683 schemaDataset = dataset +
"_schema" 685 butler.put(catalog, schemaDataset, doBackup=doBackup)
686 elif butler.datasetExists(schemaDataset, write=
True):
687 oldSchema = butler.get(schemaDataset, immediate=
True).getSchema()
688 if not oldSchema.compare(catalog.getSchema(), afwTable.Schema.IDENTICAL):
690 (
"New schema does not match schema %r on disk; schemas must be " +
691 " consistent within the same output repo (override with --clobber-config)") %
694 butler.put(catalog, schemaDataset)
697 """Write the metadata produced from processing the data. 702 Butler data reference used to write the metadata. 703 The metadata is written to dataset type `CmdLineTask._getMetadataName`. 707 if metadataName
is not None:
709 except Exception
as e:
710 self.
log.warn(
"Could not persist metadata for dataId=%s: %s", dataRef.dataId, e)
713 """Compare and write package versions. 717 butler : `lsst.daf.persistence.Butler` 718 Data butler used to read/write the package versions. 719 clobber : `bool`, optional 720 A boolean flag that controls what happens if versions already have been saved: 721 - `True`: overwrite or rename the existing version info, depending on ``doBackup``. 722 - `False`: raise `TaskError` if this version info does not match the existing. 723 doBackup : `bool`, optional 724 If `True` and clobbering, old package version files are backed up. 725 dataset : `str`, optional 726 Name of dataset to read/write. 731 Raised if there is a version mismatch with current and persisted lists of package versions. 735 Note that this operation is subject to a race condition. 737 packages = Packages.fromSystem()
740 return butler.put(packages, dataset, doBackup=doBackup)
741 if not butler.datasetExists(dataset, write=
True):
742 return butler.put(packages, dataset)
745 old = butler.get(dataset, immediate=
True)
746 except Exception
as exc:
747 raise type(exc)(
"Unable to read stored version dataset %s (%s); " 748 "consider using --clobber-versions or --no-versions" %
753 diff = packages.difference(old)
756 "Version mismatch (" +
757 "; ".join(
"%s: %s vs %s" % (pkg, diff[pkg][1], diff[pkg][0])
for pkg
in diff) +
758 "); consider using --clobber-versions or --no-versions")
760 extra = packages.extra(old)
763 butler.put(old, dataset, doBackup=doBackup)
765 def _getConfigName(self):
766 """Get the name of the config dataset type, or `None` if config is not to be persisted. 770 The name may depend on the config; that is why this is not a class method. 772 return self._DefaultName +
"_config" 774 def _getMetadataName(self):
775 """Get the name of the metadata dataset type, or `None` if metadata is not to be persisted. 779 The name may depend on the config; that is why this is not a class method. 781 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)