File: ast.py

package info (click to toggle)
nmodl 0.6-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,016 kB
  • sloc: cpp: 28,492; javascript: 9,841; yacc: 2,804; python: 1,971; lex: 1,674; xml: 181; sh: 136; ansic: 37; makefile: 17; pascal: 7
file content (44 lines) | stat: -rw-r--r-- 1,206 bytes parent folder | download
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)