Coverage for python/lsst/ctrl/mpexec/dotTools.py: 10%

153 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-09 12:06 +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/>. 

27 

28"""Module defining few methods to generate GraphViz diagrams from pipelines 

29or quantum graphs. 

30""" 

31 

32from __future__ import annotations 

33 

34__all__ = ["graph2dot", "pipeline2dot"] 

35 

36# ------------------------------- 

37# Imports of standard modules -- 

38# ------------------------------- 

39import html 

40import io 

41import re 

42from collections.abc import Iterable 

43from typing import TYPE_CHECKING, Any 

44 

45# ----------------------------- 

46# Imports for other modules -- 

47# ----------------------------- 

48from lsst.daf.butler import DatasetType, DimensionUniverse 

49from lsst.pipe.base import Pipeline, connectionTypes, iterConnections 

50 

51if TYPE_CHECKING: 

52 from lsst.daf.butler import DatasetRef 

53 from lsst.pipe.base import QuantumGraph, QuantumNode, TaskDef 

54 

55# ---------------------------------- 

56# Local non-exported definitions -- 

57# ---------------------------------- 

58 

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) 

70 

71 

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) 

76 

77 

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) 

91 

92 

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>&nbsp;{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>&nbsp;{html.escape(dimensions_str)}") 

105 _renderNode(file, nodeName, "task", labels) 

106 

107 

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) 

117 

118 

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>&nbsp;" + html.escape(", ".join(sorted(dimensions)))) 

124 _renderNode(file, name, "dsType", labels) 

125 

126 

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) 

132 

133 

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) 

141 

142 

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) 

148 

149 

150def _makeDSNode(dsRef: DatasetRef, allDatasetRefs: dict[str, str], file: io.TextIOBase) -> str: 

151 """Make new node for dataset if it does not exist. 

152 

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 

163 

164 

165# ------------------------ 

166# Exported definitions -- 

167# ------------------------ 

168 

169 

170def graph2dot(qgraph: QuantumGraph, file: Any) -> None: 

171 """Convert QuantumGraph into GraphViz digraph. 

172 

173 This method is mostly for documentation/presentation purposes. 

174 

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. 

182 

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 

193 

194 print("digraph QuantumGraph {", file=file) 

195 _renderDefault("graph", _ATTRIBS["defaultGraph"], file) 

196 _renderDefault("node", _ATTRIBS["defaultNode"], file) 

197 _renderDefault("edge", _ATTRIBS["defaultEdge"], file) 

198 

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) 

206 

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) 

212 

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) 

218 

219 print("}", file=file) 

220 if close: 

221 file.close() 

222 

223 

224def pipeline2dot(pipeline: Pipeline | Iterable[TaskDef], file: Any) -> None: 

225 """Convert `~lsst.pipe.base.Pipeline` into GraphViz digraph. 

226 

227 This method is mostly for documentation/presentation purposes. 

228 Unlike other methods this method does not validate graph consistency. 

229 

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. 

237 

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() 

246 

247 def expand_dimensions(connection: connectionTypes.BaseConnection) -> list[str]: 

248 """Return expanded list of dimensions, with special skypix treatment. 

249 

250 Parameters 

251 ---------- 

252 dimensions : `list` [`str`] 

253 

254 Returns 

255 ------- 

256 dimensions : `list` [`str`] 

257 """ 

258 dimension_set = set() 

259 if isinstance(connection, connectionTypes.DimensionedConnection): 

260 dimension_set = set(connection.dimensions) 

261 skypix_dim = [] 

262 if "skypix" in dimension_set: 

263 dimension_set.remove("skypix") 

264 skypix_dim = ["skypix"] 

265 dimensions = universe.conform(dimension_set) 

266 return list(dimensions.names) + skypix_dim 

267 

268 # open a file if needed 

269 close = False 

270 if not hasattr(file, "write"): 

271 file = open(file, "w") 

272 close = True 

273 

274 print("digraph Pipeline {", file=file) 

275 _renderDefault("graph", _ATTRIBS["defaultGraph"], file) 

276 _renderDefault("node", _ATTRIBS["defaultNode"], file) 

277 _renderDefault("edge", _ATTRIBS["defaultEdge"], file) 

278 

279 allDatasets: set[str | tuple[str, str]] = set() 

280 if isinstance(pipeline, Pipeline): 

281 pipeline = pipeline.toExpandedPipeline() 

282 

283 # The next two lines are a workaround until DM-29658 at which time metadata 

284 # connections should start working with the above code 

285 labelToTaskName = {} 

286 metadataNodesToLink = set() 

287 

288 for idx, taskDef in enumerate(sorted(pipeline, key=lambda x: x.label)): 

289 # node for a task 

290 taskNodeName = f"task{idx}" 

291 

292 # next line is workaround until DM-29658 

293 labelToTaskName[taskDef.label] = taskNodeName 

294 

295 _renderTaskNode(taskNodeName, taskDef, file, None) 

296 

297 metadataRePattern = re.compile("^(.*)_metadata$") 

298 for attr in sorted(iterConnections(taskDef.connections, "inputs"), key=lambda x: x.name): 

299 if attr.name not in allDatasets: 

300 dimensions = expand_dimensions(attr) 

301 _renderDSTypeNode(attr.name, dimensions, file) 

302 allDatasets.add(attr.name) 

303 nodeName, component = DatasetType.splitDatasetTypeName(attr.name) 

304 _renderEdge(attr.name, taskNodeName, file) 

305 # connect component dataset types to the composite type that 

306 # produced it 

307 if component is not None and (nodeName, attr.name) not in allDatasets: 

308 _renderEdge(nodeName, attr.name, file) 

309 allDatasets.add((nodeName, attr.name)) 

310 if nodeName not in allDatasets: 

311 dimensions = expand_dimensions(attr) 

312 _renderDSTypeNode(nodeName, dimensions, file) 

313 # The next if block is a workaround until DM-29658 at which time 

314 # metadata connections should start working with the above code 

315 if (match := metadataRePattern.match(attr.name)) is not None: 

316 matchTaskLabel = match.group(1) 

317 metadataNodesToLink.add((matchTaskLabel, attr.name)) 

318 

319 for attr in sorted(iterConnections(taskDef.connections, "prerequisiteInputs"), key=lambda x: x.name): 

320 if attr.name not in allDatasets: 

321 dimensions = expand_dimensions(attr) 

322 _renderDSTypeNode(attr.name, dimensions, file) 

323 allDatasets.add(attr.name) 

324 # use dashed line for prerequisite edges to distinguish them 

325 _renderEdge(attr.name, taskNodeName, file, style="dashed") 

326 

327 for attr in sorted(iterConnections(taskDef.connections, "outputs"), key=lambda x: x.name): 

328 if attr.name not in allDatasets: 

329 dimensions = expand_dimensions(attr) 

330 _renderDSTypeNode(attr.name, dimensions, file) 

331 allDatasets.add(attr.name) 

332 _renderEdge(taskNodeName, attr.name, file) 

333 

334 # This for loop is a workaround until DM-29658 at which time metadata 

335 # connections should start working with the above code 

336 for matchLabel, dsTypeName in metadataNodesToLink: 

337 # only render an edge to metadata if the label is part of the current 

338 # graph 

339 if (result := labelToTaskName.get(matchLabel)) is not None: 

340 _renderEdge(result, dsTypeName, file) 

341 

342 print("}", file=file) 

343 if close: 

344 file.close()