Created
March 28, 2017 17:55
-
-
Save goerz/178811cece8e96ae5378be71b8ea904a to your computer and use it in GitHub Desktop.
Render Sympy Expression as graphical tree inside IPython notebook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def render_sympy_tree(expr): | |
"""Render the given Sympy Expression as a graphical tree, inside an IPython notebook""" | |
from sympy.printing.dot import dotprint | |
import tempfile | |
import subprocess | |
import os | |
from IPython.display import SVG | |
with tempfile.NamedTemporaryFile(mode='w', delete=False) as out_fh: | |
out_fh.write(dotprint(expr)) | |
subprocess.run(['/usr/bin/dot', '-Tsvg', out_fh.name, '-o', out_fh.name + ".svg"]) | |
svg = SVG(filename=(out_fh.name + ".svg")) | |
os.unlink(out_fh.name) | |
os.unlink(out_fh.name + ".svg") | |
return svg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm having problems with
dot
inside a conda environment (due to #1357), which also breaks the graphviz package. The above code solves the problem of rendering the graphviz tree representation of Sympy expressions in Python 3.5, via a temporary file. Note the use of the system/usr/bin/dot
instead of justdot
(which would refer to the broken binary that's installed by conda).