|
| 1 | +""" |
| 2 | +Internal debugging utilities, that are not expected to be used in the rest of |
| 3 | +the codebase. |
| 4 | +
|
| 5 | +WARNING: Code in this module may change without prior notice! |
| 6 | +""" |
| 7 | + |
| 8 | +from io import StringIO |
| 9 | +from pathlib import Path |
| 10 | +import subprocess |
| 11 | + |
| 12 | +from matplotlib.transforms import TransformNode |
| 13 | + |
| 14 | + |
| 15 | +def graphviz_dump_transform(transform, dest, *, highlight=None): |
| 16 | + """ |
| 17 | + Generate a graphical representation of the transform tree for *transform* |
| 18 | + using the :program:`dot` program (which this function depends on). The |
| 19 | + output format (png, dot, etc.) is determined from the suffix of *dest*. |
| 20 | +
|
| 21 | + Parameters |
| 22 | + ---------- |
| 23 | + transform : `~matplotlib.transform.Transform` |
| 24 | + The represented transform. |
| 25 | + dest : str |
| 26 | + Output filename. The extension must be one of the formats supported |
| 27 | + by :program:`dot`, e.g. png, svg, dot, ... |
| 28 | + (see https://www.graphviz.org/doc/info/output.html). |
| 29 | + highlight : list of `~matplotlib.transform.Transform` or None |
| 30 | + The transforms in the tree to be drawn in bold. |
| 31 | + If *None*, *transform* is highlighted. |
| 32 | + """ |
| 33 | + |
| 34 | + if highlight is None: |
| 35 | + highlight = [transform] |
| 36 | + seen = set() |
| 37 | + |
| 38 | + def recurse(root, buf): |
| 39 | + if id(root) in seen: |
| 40 | + return |
| 41 | + seen.add(id(root)) |
| 42 | + props = {} |
| 43 | + label = type(root).__name__ |
| 44 | + if root._invalid: |
| 45 | + label = f'[{label}]' |
| 46 | + if root in highlight: |
| 47 | + props['style'] = 'bold' |
| 48 | + props['shape'] = 'box' |
| 49 | + props['label'] = '"%s"' % label |
| 50 | + props = ' '.join(map('{0[0]}={0[1]}'.format, props.items())) |
| 51 | + buf.write(f'{id(root)} [{props}];\n') |
| 52 | + for key, val in vars(root).items(): |
| 53 | + if isinstance(val, TransformNode) and id(root) in val._parents: |
| 54 | + buf.write(f'"{id(root)}" -> "{id(val)}" ' |
| 55 | + f'[label="{key}", fontsize=10];\n') |
| 56 | + recurse(val, buf) |
| 57 | + |
| 58 | + buf = StringIO() |
| 59 | + buf.write('digraph G {\n') |
| 60 | + recurse(transform, buf) |
| 61 | + buf.write('}\n') |
| 62 | + subprocess.run( |
| 63 | + ['dot', '-T', Path(dest).suffix[1:], '-o', dest], |
| 64 | + input=buf.getvalue().encode('utf-8'), check=True) |
0 commit comments