Coverage for python/lsst/pipe/base/pipeTools.py: 14%
69 statements
« prev ^ index » next coverage.py v7.2.1, created at 2023-03-12 20:54 -0700
« prev ^ index » next coverage.py v7.2.1, created at 2023-03-12 20:54 -0700
1# This file is part of pipe_base.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22"""Module defining few methods to manipulate or query pipelines.
23"""
25from __future__ import annotations
27# No one should do import * from this module
28__all__ = ["isPipelineOrdered", "orderPipeline"]
30# -------------------------------
31# Imports of standard modules --
32# -------------------------------
33import itertools
34from typing import TYPE_CHECKING, Iterable, List, Optional, Union
36# -----------------------------
37# Imports for other modules --
38# -----------------------------
39from .connections import iterConnections
41if TYPE_CHECKING: 41 ↛ 42line 41 didn't jump to line 42, because the condition on line 41 was never true
42 from .pipeline import Pipeline, TaskDef
43 from .taskFactory import TaskFactory
45# ----------------------------------
46# Local non-exported definitions --
47# ----------------------------------
49# ------------------------
50# Exported definitions --
51# ------------------------
54class MissingTaskFactoryError(Exception):
55 """Exception raised when client fails to provide TaskFactory instance."""
57 pass
60class DuplicateOutputError(Exception):
61 """Exception raised when Pipeline has more than one task for the same
62 output.
63 """
65 pass
68class PipelineDataCycleError(Exception):
69 """Exception raised when Pipeline has data dependency cycle."""
71 pass
74def isPipelineOrdered(
75 pipeline: Union[Pipeline, Iterable[TaskDef]], taskFactory: Optional[TaskFactory] = None
76) -> bool:
77 """Checks whether tasks in pipeline are correctly ordered.
79 Pipeline is correctly ordered if for any DatasetType produced by a task
80 in a pipeline all its consumer tasks are located after producer.
82 Parameters
83 ----------
84 pipeline : `pipe.base.Pipeline`
85 Pipeline description.
86 taskFactory: `pipe.base.TaskFactory`, optional
87 Instance of an object which knows how to import task classes. It is
88 only used if pipeline task definitions do not define task classes.
90 Returns
91 -------
92 True for correctly ordered pipeline, False otherwise.
94 Raises
95 ------
96 `ImportError` is raised when task class cannot be imported.
97 `DuplicateOutputError` is raised when there is more than one producer for a
98 dataset type.
99 `MissingTaskFactoryError` is raised when TaskFactory is needed but not
100 provided.
101 """
102 # Build a map of DatasetType name to producer's index in a pipeline
103 producerIndex = {}
104 for idx, taskDef in enumerate(pipeline):
105 for attr in iterConnections(taskDef.connections, "outputs"):
106 if attr.name in producerIndex:
107 raise DuplicateOutputError(
108 "DatasetType `{}' appears more than once as output".format(attr.name)
109 )
110 producerIndex[attr.name] = idx
112 # check all inputs that are also someone's outputs
113 for idx, taskDef in enumerate(pipeline):
114 # get task input DatasetTypes, this can only be done via class method
115 inputs = {name: getattr(taskDef.connections, name) for name in taskDef.connections.inputs}
116 for dsTypeDescr in inputs.values():
117 # all pre-existing datasets have effective index -1
118 prodIdx = producerIndex.get(dsTypeDescr.name, -1)
119 if prodIdx >= idx:
120 # not good, producer is downstream
121 return False
123 return True
126def orderPipeline(pipeline: List[TaskDef]) -> List[TaskDef]:
127 """Re-order tasks in pipeline to satisfy data dependencies.
129 When possible new ordering keeps original relative order of the tasks.
131 Parameters
132 ----------
133 pipeline : `list` of `pipe.base.TaskDef`
134 Pipeline description.
136 Returns
137 -------
138 Correctly ordered pipeline (`list` of `pipe.base.TaskDef` objects).
140 Raises
141 ------
142 `DuplicateOutputError` is raised when there is more than one producer for a
143 dataset type.
144 `PipelineDataCycleError` is also raised when pipeline has dependency
145 cycles. `MissingTaskFactoryError` is raised when TaskFactory is needed but
146 not provided.
147 """
149 # This is a modified version of Kahn's algorithm that preserves order
151 # build mapping of the tasks to their inputs and outputs
152 inputs = {} # maps task index to its input DatasetType names
153 outputs = {} # maps task index to its output DatasetType names
154 allInputs = set() # all inputs of all tasks
155 allOutputs = set() # all outputs of all tasks
156 for idx, taskDef in enumerate(pipeline):
157 # task outputs
158 dsMap = {name: getattr(taskDef.connections, name) for name in taskDef.connections.outputs}
159 for dsTypeDescr in dsMap.values():
160 if dsTypeDescr.name in allOutputs:
161 raise DuplicateOutputError(
162 "DatasetType `{}' appears more than once as output".format(dsTypeDescr.name)
163 )
164 outputs[idx] = set(dsTypeDescr.name for dsTypeDescr in dsMap.values())
165 allOutputs.update(outputs[idx])
167 # task inputs
168 connectionInputs = itertools.chain(taskDef.connections.inputs, taskDef.connections.prerequisiteInputs)
169 inputs[idx] = set(getattr(taskDef.connections, name).name for name in connectionInputs)
170 allInputs.update(inputs[idx])
172 # for simplicity add pseudo-node which is a producer for all pre-existing
173 # inputs, its index is -1
174 preExisting = allInputs - allOutputs
175 outputs[-1] = preExisting
177 # Set of nodes with no incoming edges, initially set to pseudo-node
178 queue = [-1]
179 result = []
180 while queue:
181 # move to final list, drop -1
182 idx = queue.pop(0)
183 if idx >= 0:
184 result.append(idx)
186 # remove task outputs from other tasks inputs
187 thisTaskOutputs = outputs.get(idx, set())
188 for taskInputs in inputs.values():
189 taskInputs -= thisTaskOutputs
191 # find all nodes with no incoming edges and move them to the queue
192 topNodes = [key for key, value in inputs.items() if not value]
193 queue += topNodes
194 for key in topNodes:
195 del inputs[key]
197 # keep queue ordered
198 queue.sort()
200 # if there is something left it means cycles
201 if inputs:
202 # format it in usable way
203 loops = []
204 for idx, inputNames in inputs.items():
205 taskName = pipeline[idx].label
206 outputNames = outputs[idx]
207 edge = " {} -> {} -> {}".format(inputNames, taskName, outputNames)
208 loops.append(edge)
209 raise PipelineDataCycleError("Pipeline has data cycles:\n" + "\n".join(loops))
211 return [pipeline[idx] for idx in result]