Skip to content

Add function to mermaid diagram #1490

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ jobs:
if [[ $INSTALL_NUMBA == "1" ]]; then micromamba install --yes -q -c conda-forge "python~=${PYTHON_VERSION}" "numba>=0.57"; fi
if [[ $INSTALL_JAX == "1" ]]; then micromamba install --yes -q -c conda-forge "python~=${PYTHON_VERSION}" jax jaxlib numpyro && pip install tensorflow-probability; fi
if [[ $INSTALL_TORCH == "1" ]]; then micromamba install --yes -q -c conda-forge "python~=${PYTHON_VERSION}" pytorch pytorch-cuda=12.1 "mkl<=2024.0" -c pytorch -c nvidia; fi
pip install pytest-sphinx
pip install pytest-sphinx pydot

pip install -e ./
micromamba list && pip freeze
Expand Down
4 changes: 4 additions & 0 deletions pytensor/d3viz/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pytensor.graph.basic import Apply, Constant, Variable, graph_inputs
from pytensor.graph.fg import FunctionGraph
from pytensor.printing import _try_pydot_import
from pytensor.tensor.elemwise import Elemwise


class PyDotFormatter:
Expand Down Expand Up @@ -291,6 +292,9 @@ def var_tag(var):

def apply_label(node):
"""Return label of apply node."""
if isinstance(node.op, Elemwise):
return node.op.scalar_op.__class__.__name__

return node.op.__class__.__name__


Expand Down
63 changes: 63 additions & 0 deletions pytensor/mermaid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from pytensor.d3viz.formatting import PyDotFormatter


def function_to_mermaid(fn):
formatter = PyDotFormatter()
dot = formatter(fn)

nodes = dot.get_nodes()
edges = dot.get_edges()

mermaid_lines = ["graph TD"]
mermaid_lines.append("%% Nodes:")
for node in nodes:
name = node.get_name()
label = node.get_label()
shape = node.get_shape()

if label.endswith("."):
label = f"{label}0"

if shape == "box":
shape = "rect"
else:
shape = "rounded"

mermaid_lines.extend(
[
f'{name}["{label}"]',
f"{name}@{{ shape: {shape} }}",
]
)

fillcolor = node.get_fillcolor()
if fillcolor is not None and not fillcolor.startswith("#"):
fillcolor = _color_to_hex(fillcolor)
mermaid_lines.append(f"style {name} fill:{fillcolor}")

mermaid_lines.append("\n%% Edges:")
for edge in edges:
source = edge.get_source()
target = edge.get_destination()

mermaid_lines.append(f"{source} --> {target}")

return "\n".join(mermaid_lines)


def _color_to_hex(color_name):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this a function?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mermaid needs hexcolors. the pydotformatter has strings names for colors

"""Based on the colors in d3viz module."""
return {
"limegreen": "#32CD32",
"SpringGreen": "#00FF7F",
"YellowGreen": "#9ACD32",
"dodgerblue": "#1E90FF",
"lightgrey": "#D3D3D3",
"yellow": "#FFFF00",
"cyan": "#00FFFF",
"magenta": "#FF00FF",
"red": "#FF0000",
"blue": "#0000FF",
"green": "#008000",
"grey": "#808080",
}.get(color_name)
63 changes: 63 additions & 0 deletions tests/test_mermaid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from textwrap import dedent

import pytest

from pytensor import function
from pytensor import tensor as pt
from pytensor.mermaid import function_to_mermaid


@pytest.fixture
def sample_function():
x = pt.dmatrix("x")
y = pt.dvector("y")
z = pt.dot(x, y)
z.name = "z"
return function([x, y], z)


def test_function_to_mermaid(sample_function):
diagram = function_to_mermaid(sample_function)

assert (
diagram
== dedent("""
graph TD
%% Nodes:
n1["Shape_i"]
n1@{ shape: rounded }
style n1 fill:#00FFFF
n2["x"]
n2@{ shape: rect }
style n2 fill:#32CD32
n2["x"]
n2@{ shape: rect }
style n2 fill:#32CD32
n4["AllocEmpty"]
n4@{ shape: rounded }
n6["CGemv"]
n6@{ shape: rounded }
n7["1.0"]
n7@{ shape: rect }
style n7 fill:#00FF7F
n8["y"]
n8@{ shape: rect }
style n8 fill:#32CD32
n9["0.0"]
n9@{ shape: rect }
style n9 fill:#00FF7F
n10["z"]
n10@{ shape: rect }
style n10 fill:#1E90FF

%% Edges:
n2 --> n1
n1 --> n4
n4 --> n6
n7 --> n6
n2 --> n6
n8 --> n6
n9 --> n6
n6 --> n10
""").strip()
)
Loading