1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
import getpass
import json
import os
import tempfile
import webbrowser
from importlib.resources import files
from shutil import copytree
from ._nmodl import to_json
from ._nmodl.ast import * # noqa
def view(nmodl_ast):
"""Visualize given NMODL AST in web browser
In memory representation of AST can be converted to JSON
form and it can be visualized using AST viewer implemented
using d3.js.
Args:
nmodl_ast: AST object of nmodl file or string
Returns:
None
"""
path = files("nmodl") / "ext/viz"
if not path.is_dir():
raise FileNotFoundError("Could not find sample mod files")
work_dir = os.path.join(tempfile.gettempdir(), getpass.getuser(), "nmodl")
# first copy necessary files to temp work directory
copytree(path, work_dir, dirs_exist_ok=True)
# prepare json data
json_data = json.loads(to_json(nmodl_ast, True, True, True))
with open(os.path.join(work_dir, "ast.js"), "w", encoding="utf-8") as outfile:
outfile.write(f"var astRoot = {json.dumps(json_data)};")
# open browser with ast
url = 'file://' + os.path.join(work_dir, "index.html")
webbrowser.open(url, new=1, autoraise=True)
|