Coverage for python/lsst/ctrl/mpexec/dotTools.py: 10%
153 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-20 11:03 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-20 11:03 +0000
1# This file is part of ctrl_mpexec.
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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28"""Module defining few methods to generate GraphViz diagrams from pipelines
29or quantum graphs.
30"""
32from __future__ import annotations
34__all__ = ["graph2dot", "pipeline2dot"]
36# -------------------------------
37# Imports of standard modules --
38# -------------------------------
39import html
40import io
41import re
42from collections.abc import Iterable
43from typing import TYPE_CHECKING, Any
45# -----------------------------
46# Imports for other modules --
47# -----------------------------
48from lsst.daf.butler import DatasetType, DimensionUniverse
49from lsst.pipe.base import Pipeline, connectionTypes, iterConnections
51if TYPE_CHECKING:
52 from lsst.daf.butler import DatasetRef
53 from lsst.pipe.base import QuantumGraph, QuantumNode, TaskDef
55# ----------------------------------
56# Local non-exported definitions --
57# ----------------------------------
59# Attributes applied to directed graph objects.
60_NODELABELPOINTSIZE = "18"
61_ATTRIBS = dict(
62 defaultGraph=dict(splines="ortho", nodesep="0.5", ranksep="0.75", pad="0.5"),
63 defaultNode=dict(shape="box", fontname="Monospace", fontsize="14", margin="0.2,0.1", penwidth="3"),
64 defaultEdge=dict(color="black", arrowsize="1.5", penwidth="1.5"),
65 task=dict(style="filled", color="black", fillcolor="#B1F2EF"),
66 quantum=dict(style="filled", color="black", fillcolor="#B1F2EF"),
67 dsType=dict(style="rounded,filled,bold", color="#00BABC", fillcolor="#F5F5F5"),
68 dataset=dict(style="rounded,filled,bold", color="#00BABC", fillcolor="#F5F5F5"),
69)
72def _renderDefault(type: str, attribs: dict[str, str], file: io.TextIOBase) -> None:
73 """Set default attributes for a given type."""
74 default_attribs = ", ".join([f'{key}="{val}"' for key, val in attribs.items()])
75 print(f"{type} [{default_attribs}];", file=file)
78def _renderNode(file: io.TextIOBase, nodeName: str, style: str, labels: list[str]) -> None:
79 """Render GV node"""
80 label = r"</TD></TR><TR><TD>".join(labels)
81 attrib_dict = dict(_ATTRIBS[style], label=label)
82 pre = '<<TABLE BORDER="0" CELLPADDING="5"><TR><TD>'
83 post = "</TD></TR></TABLE>>"
84 attrib = ", ".join(
85 [
86 f'{key}="{val}"' if key != "label" else f"{key}={pre}{val}{post}"
87 for key, val in attrib_dict.items()
88 ]
89 )
90 print(f'"{nodeName}" [{attrib}];', file=file)
93def _renderTaskNode(nodeName: str, taskDef: TaskDef, file: io.TextIOBase, idx: Any = None) -> None:
94 """Render GV node for a task"""
95 labels = [
96 f'<B><FONT POINT-SIZE="{_NODELABELPOINTSIZE}">' + html.escape(taskDef.label) + "</FONT></B>",
97 html.escape(taskDef.taskName),
98 ]
99 if idx is not None:
100 labels.append(f"<I>index:</I> {idx}")
101 if taskDef.connections:
102 # don't print collection of str directly to avoid visually noisy quotes
103 dimensions_str = ", ".join(sorted(taskDef.connections.dimensions))
104 labels.append(f"<I>dimensions:</I> {html.escape(dimensions_str)}")
105 _renderNode(file, nodeName, "task", labels)
108def _renderQuantumNode(
109 nodeName: str, taskDef: TaskDef, quantumNode: QuantumNode, file: io.TextIOBase
110) -> None:
111 """Render GV node for a quantum"""
112 labels = [f"{quantumNode.nodeId}", html.escape(taskDef.label)]
113 dataId = quantumNode.quantum.dataId
114 assert dataId is not None, "Quantum DataId cannot be None"
115 labels.extend(f"{key} = {dataId[key]}" for key in sorted(dataId.keys()))
116 _renderNode(file, nodeName, "quantum", labels)
119def _renderDSTypeNode(name: str, dimensions: list[str], file: io.TextIOBase) -> None:
120 """Render GV node for a dataset type"""
121 labels = [f'<B><FONT POINT-SIZE="{_NODELABELPOINTSIZE}">' + html.escape(name) + "</FONT></B>"]
122 if dimensions:
123 labels.append("<I>dimensions:</I> " + html.escape(", ".join(sorted(dimensions))))
124 _renderNode(file, name, "dsType", labels)
127def _renderDSNode(nodeName: str, dsRef: DatasetRef, file: io.TextIOBase) -> None:
128 """Render GV node for a dataset"""
129 labels = [html.escape(dsRef.datasetType.name), f"run: {dsRef.run!r}"]
130 labels.extend(f"{key} = {dsRef.dataId[key]}" for key in sorted(dsRef.dataId.keys()))
131 _renderNode(file, nodeName, "dataset", labels)
134def _renderEdge(fromName: str, toName: str, file: io.TextIOBase, **kwargs: Any) -> None:
135 """Render GV edge"""
136 if kwargs:
137 attrib = ", ".join([f'{key}="{val}"' for key, val in kwargs.items()])
138 print(f'"{fromName}" -> "{toName}" [{attrib}];', file=file)
139 else:
140 print(f'"{fromName}" -> "{toName}";', file=file)
143def _datasetRefId(dsRef: DatasetRef) -> str:
144 """Make an identifying string for given ref"""
145 dsId = [dsRef.datasetType.name]
146 dsId.extend(f"{key} = {dsRef.dataId[key]}" for key in sorted(dsRef.dataId.keys()))
147 return ":".join(dsId)
150def _makeDSNode(dsRef: DatasetRef, allDatasetRefs: dict[str, str], file: io.TextIOBase) -> str:
151 """Make new node for dataset if it does not exist.
153 Returns node name.
154 """
155 dsRefId = _datasetRefId(dsRef)
156 nodeName = allDatasetRefs.get(dsRefId)
157 if nodeName is None:
158 idx = len(allDatasetRefs)
159 nodeName = f"dsref_{idx}"
160 allDatasetRefs[dsRefId] = nodeName
161 _renderDSNode(nodeName, dsRef, file)
162 return nodeName
165# ------------------------
166# Exported definitions --
167# ------------------------
170def graph2dot(qgraph: QuantumGraph, file: Any) -> None:
171 """Convert QuantumGraph into GraphViz digraph.
173 This method is mostly for documentation/presentation purposes.
175 Parameters
176 ----------
177 qgraph : `lsst.pipe.base.QuantumGraph`
178 QuantumGraph instance.
179 file : `str` or file object
180 File where GraphViz graph (DOT language) is written, can be a file name
181 or file object.
183 Raises
184 ------
185 `OSError` is raised when output file cannot be open.
186 `ImportError` is raised when task class cannot be imported.
187 """
188 # open a file if needed
189 close = False
190 if not hasattr(file, "write"):
191 file = open(file, "w")
192 close = True
194 print("digraph QuantumGraph {", file=file)
195 _renderDefault("graph", _ATTRIBS["defaultGraph"], file)
196 _renderDefault("node", _ATTRIBS["defaultNode"], file)
197 _renderDefault("edge", _ATTRIBS["defaultEdge"], file)
199 allDatasetRefs: dict[str, str] = {}
200 for taskId, taskDef in enumerate(qgraph.taskGraph):
201 quanta = qgraph.getNodesForTask(taskDef)
202 for qId, quantumNode in enumerate(quanta):
203 # node for a task
204 taskNodeName = f"task_{taskId}_{qId}"
205 _renderQuantumNode(taskNodeName, taskDef, quantumNode, file)
207 # quantum inputs
208 for dsRefs in quantumNode.quantum.inputs.values():
209 for dsRef in dsRefs:
210 nodeName = _makeDSNode(dsRef, allDatasetRefs, file)
211 _renderEdge(nodeName, taskNodeName, file)
213 # quantum outputs
214 for dsRefs in quantumNode.quantum.outputs.values():
215 for dsRef in dsRefs:
216 nodeName = _makeDSNode(dsRef, allDatasetRefs, file)
217 _renderEdge(taskNodeName, nodeName, file)
219 print("}", file=file)
220 if close:
221 file.close()
224def pipeline2dot(pipeline: Pipeline | Iterable[TaskDef], file: Any) -> None:
225 """Convert `~lsst.pipe.base.Pipeline` into GraphViz digraph.
227 This method is mostly for documentation/presentation purposes.
228 Unlike other methods this method does not validate graph consistency.
230 Parameters
231 ----------
232 pipeline : `lsst.pipe.base.Pipeline`
233 Pipeline description.
234 file : `str` or file object
235 File where GraphViz graph (DOT language) is written, can be a file name
236 or file object.
238 Raises
239 ------
240 `OSError` is raised when output file cannot be open.
241 `ImportError` is raised when task class cannot be imported.
242 `MissingTaskFactoryError` is raised when TaskFactory is needed but not
243 provided.
244 """
245 universe = DimensionUniverse()
247 def expand_dimensions(connection: connectionTypes.BaseConnection) -> list[str]:
248 """Return expanded list of dimensions, with special skypix treatment.
250 Parameters
251 ----------
252 connection : `list` [`str`]
253 Connection to examine.
255 Returns
256 -------
257 dimensions : `list` [`str`]
258 Expanded list of dimensions.
259 """
260 dimension_set = set()
261 if isinstance(connection, connectionTypes.DimensionedConnection):
262 dimension_set = set(connection.dimensions)
263 skypix_dim = []
264 if "skypix" in dimension_set:
265 dimension_set.remove("skypix")
266 skypix_dim = ["skypix"]
267 dimensions = universe.conform(dimension_set)
268 return list(dimensions.names) + skypix_dim
270 # open a file if needed
271 close = False
272 if not hasattr(file, "write"):
273 file = open(file, "w")
274 close = True
276 print("digraph Pipeline {", file=file)
277 _renderDefault("graph", _ATTRIBS["defaultGraph"], file)
278 _renderDefault("node", _ATTRIBS["defaultNode"], file)
279 _renderDefault("edge", _ATTRIBS["defaultEdge"], file)
281 allDatasets: set[str | tuple[str, str]] = set()
282 if isinstance(pipeline, Pipeline):
283 pipeline = pipeline.toExpandedPipeline()
285 # The next two lines are a workaround until DM-29658 at which time metadata
286 # connections should start working with the above code
287 labelToTaskName = {}
288 metadataNodesToLink = set()
290 for idx, taskDef in enumerate(sorted(pipeline, key=lambda x: x.label)):
291 # node for a task
292 taskNodeName = f"task{idx}"
294 # next line is workaround until DM-29658
295 labelToTaskName[taskDef.label] = taskNodeName
297 _renderTaskNode(taskNodeName, taskDef, file, None)
299 metadataRePattern = re.compile("^(.*)_metadata$")
300 for attr in sorted(iterConnections(taskDef.connections, "inputs"), key=lambda x: x.name):
301 if attr.name not in allDatasets:
302 dimensions = expand_dimensions(attr)
303 _renderDSTypeNode(attr.name, dimensions, file)
304 allDatasets.add(attr.name)
305 nodeName, component = DatasetType.splitDatasetTypeName(attr.name)
306 _renderEdge(attr.name, taskNodeName, file)
307 # connect component dataset types to the composite type that
308 # produced it
309 if component is not None and (nodeName, attr.name) not in allDatasets:
310 _renderEdge(nodeName, attr.name, file)
311 allDatasets.add((nodeName, attr.name))
312 if nodeName not in allDatasets:
313 dimensions = expand_dimensions(attr)
314 _renderDSTypeNode(nodeName, dimensions, file)
315 # The next if block is a workaround until DM-29658 at which time
316 # metadata connections should start working with the above code
317 if (match := metadataRePattern.match(attr.name)) is not None:
318 matchTaskLabel = match.group(1)
319 metadataNodesToLink.add((matchTaskLabel, attr.name))
321 for attr in sorted(iterConnections(taskDef.connections, "prerequisiteInputs"), key=lambda x: x.name):
322 if attr.name not in allDatasets:
323 dimensions = expand_dimensions(attr)
324 _renderDSTypeNode(attr.name, dimensions, file)
325 allDatasets.add(attr.name)
326 # use dashed line for prerequisite edges to distinguish them
327 _renderEdge(attr.name, taskNodeName, file, style="dashed")
329 for attr in sorted(iterConnections(taskDef.connections, "outputs"), key=lambda x: x.name):
330 if attr.name not in allDatasets:
331 dimensions = expand_dimensions(attr)
332 _renderDSTypeNode(attr.name, dimensions, file)
333 allDatasets.add(attr.name)
334 _renderEdge(taskNodeName, attr.name, file)
336 # This for loop is a workaround until DM-29658 at which time metadata
337 # connections should start working with the above code
338 for matchLabel, dsTypeName in metadataNodesToLink:
339 # only render an edge to metadata if the label is part of the current
340 # graph
341 if (result := labelToTaskName.get(matchLabel)) is not None:
342 _renderEdge(result, dsTypeName, file)
344 print("}", file=file)
345 if close:
346 file.close()