triordinal-dtree-explorer 3.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dtree_explorer/__init__.py +3 -0
- dtree_explorer/__main__.py +112 -0
- dtree_explorer/bridge.py +160 -0
- dtree_explorer/explorer.html +3419 -0
- triordinal_dtree_explorer-3.1.0.dist-info/METADATA +89 -0
- triordinal_dtree_explorer-3.1.0.dist-info/RECORD +9 -0
- triordinal_dtree_explorer-3.1.0.dist-info/WHEEL +5 -0
- triordinal_dtree_explorer-3.1.0.dist-info/entry_points.txt +2 -0
- triordinal_dtree_explorer-3.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Start the DTree Explorer: a local web page that computes with the installed triordinal-dtree.
|
|
2
|
+
|
|
3
|
+
dtree-explorer open the Explorer in the browser
|
|
4
|
+
dtree-explorer --port 8765 use a fixed port (default: a free one)
|
|
5
|
+
dtree-explorer --no-browser only start the server and print its address
|
|
6
|
+
dtree-explorer --save FILE write the page as one HTML file and exit
|
|
7
|
+
|
|
8
|
+
The server listens on 127.0.0.1 only and serves the page and one computing endpoint;
|
|
9
|
+
nothing leaves your machine. Stop it with Ctrl+C.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import platform
|
|
15
|
+
import sys
|
|
16
|
+
import webbrowser
|
|
17
|
+
from urllib.parse import parse_qs
|
|
18
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
19
|
+
from importlib import resources
|
|
20
|
+
|
|
21
|
+
import triordinal.dtree as dtree
|
|
22
|
+
|
|
23
|
+
from . import __version__, bridge
|
|
24
|
+
|
|
25
|
+
MAX_INPUT = 4 * 1024 * 1024 # bytes of tree description per request
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def page() -> bytes:
|
|
29
|
+
return resources.files(__package__).joinpath("explorer.html").read_bytes()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Handler(BaseHTTPRequestHandler):
|
|
33
|
+
server_version = "DTreeExplorer/" + __version__
|
|
34
|
+
|
|
35
|
+
def _local_host(self) -> bool:
|
|
36
|
+
host = (self.headers.get("Host") or "").rsplit(":", 1)[0]
|
|
37
|
+
return host in ("127.0.0.1", "localhost") # refuses requests under other host names
|
|
38
|
+
|
|
39
|
+
def _send(self, code, kind, body: bytes):
|
|
40
|
+
self.send_response(code)
|
|
41
|
+
self.send_header("Content-Type", kind)
|
|
42
|
+
self.send_header("Content-Length", str(len(body)))
|
|
43
|
+
self.send_header("Cache-Control", "no-store")
|
|
44
|
+
self.end_headers()
|
|
45
|
+
self.wfile.write(body)
|
|
46
|
+
|
|
47
|
+
def do_GET(self):
|
|
48
|
+
if not self._local_host():
|
|
49
|
+
return self._send(403, "text/plain", b"forbidden")
|
|
50
|
+
path = self.path.split("?", 1)[0]
|
|
51
|
+
if path in ("/", "/index.html"):
|
|
52
|
+
return self._send(200, "text/html; charset=utf-8", page())
|
|
53
|
+
if path == "/api/info":
|
|
54
|
+
info = {"dtree": dtree.__version__, "python": platform.python_version(), "explorer": __version__}
|
|
55
|
+
return self._send(200, "application/json", json.dumps(info).encode())
|
|
56
|
+
self._send(404, "text/plain", b"not found")
|
|
57
|
+
|
|
58
|
+
def do_POST(self):
|
|
59
|
+
if not self._local_host():
|
|
60
|
+
return self._send(403, "text/plain", b"forbidden")
|
|
61
|
+
path, _, query = self.path.partition("?")
|
|
62
|
+
if path != "/api/encode":
|
|
63
|
+
return self._send(404, "text/plain", b"not found")
|
|
64
|
+
q = parse_qs(query)
|
|
65
|
+
kind = q.get("kind", ["dtree"])[0]
|
|
66
|
+
positions = q.get("positions", ["rational"])[0]
|
|
67
|
+
if kind not in bridge.KINDS or positions not in bridge.POSITIONS:
|
|
68
|
+
return self._send(400, "text/plain", b"kind must be dtree, dtree2 or euler, positions rational or integer")
|
|
69
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
70
|
+
if n > MAX_INPUT:
|
|
71
|
+
return self._send(413, "text/plain", b"description too large")
|
|
72
|
+
text = self.rfile.read(n).decode("utf-8", "replace")
|
|
73
|
+
self._send(200, "application/json", bridge.encode(text, kind=kind, positions=positions).encode())
|
|
74
|
+
|
|
75
|
+
def log_message(self, *args): # quiet
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def serve(port=0):
|
|
80
|
+
"""Create the server (not yet running); port 0 picks a free port."""
|
|
81
|
+
return ThreadingHTTPServer(("127.0.0.1", port), Handler)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def main(argv=None):
|
|
85
|
+
ap = argparse.ArgumentParser(prog="dtree-explorer", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
86
|
+
ap.add_argument("--port", type=int, default=0, help="port on 127.0.0.1 (default: a free one)")
|
|
87
|
+
ap.add_argument("--no-browser", action="store_true", help="do not open the browser")
|
|
88
|
+
ap.add_argument("--save", metavar="FILE", help="write the page as one HTML file and exit")
|
|
89
|
+
ap.add_argument("--version", action="version", version=f"DTree Explorer {__version__}, triordinal-dtree {dtree.__version__}")
|
|
90
|
+
args = ap.parse_args(argv)
|
|
91
|
+
if args.save:
|
|
92
|
+
with open(args.save, "wb") as fh:
|
|
93
|
+
fh.write(page())
|
|
94
|
+
print(f"Wrote {args.save}. Open it in a browser; it loads Python (Pyodide) from the internet.")
|
|
95
|
+
return 0
|
|
96
|
+
httpd = serve(args.port)
|
|
97
|
+
url = f"http://127.0.0.1:{httpd.server_address[1]}/"
|
|
98
|
+
print(f"DTree Explorer {__version__} with triordinal-dtree {dtree.__version__} at {url}")
|
|
99
|
+
print("Press Ctrl+C to stop.")
|
|
100
|
+
if not args.no_browser:
|
|
101
|
+
webbrowser.open(url)
|
|
102
|
+
try:
|
|
103
|
+
httpd.serve_forever()
|
|
104
|
+
except KeyboardInterrupt:
|
|
105
|
+
print("\nStopped.")
|
|
106
|
+
finally:
|
|
107
|
+
httpd.server_close()
|
|
108
|
+
return 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
sys.exit(main())
|
dtree_explorer/bridge.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Bridge between the DTree Explorer page and the library (package triordinal-dtree).
|
|
2
|
+
|
|
3
|
+
The page runs this module in the browser (Pyodide) with the published triordinal-dtree
|
|
4
|
+
package; the same code runs under CPython for the tests and to precompute the example
|
|
5
|
+
that is shown while the Python runtime loads. Everything the page displays about the
|
|
6
|
+
encoding (the order of the lists, the positions, the parents) comes from here.
|
|
7
|
+
|
|
8
|
+
Three encodings: "dtree" (DTree 3.0: one list Q1, the structure in the vertices; the end of a
|
|
9
|
+
block is its delimiter, the right sibling or the parent's delimiter), "dtree2" (DTree 2.x, two
|
|
10
|
+
lists Q1 and Q2) and "euler" (EulerTree, one list: Q1 with its closing cells, the Euler tour).
|
|
11
|
+
Two kinds of position: "rational" and "integer".
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
from fractions import Fraction
|
|
16
|
+
|
|
17
|
+
import triordinal.dtree as dtree
|
|
18
|
+
from triordinal.dtree import DTree
|
|
19
|
+
from triordinal.dtree.euler import EulerTree
|
|
20
|
+
from triordinal.dtree.two_lists import DTree as DTree2
|
|
21
|
+
|
|
22
|
+
LIMIT = 300 # insertions recorded step by step; larger trees show the final state only
|
|
23
|
+
KINDS = {"dtree": DTree, "dtree2": DTree2, "euler": EulerTree}
|
|
24
|
+
POSITIONS = ("rational", "integer")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _split(line):
|
|
28
|
+
at = min((i for i in (line.find(":"), line.find(">"), line.find("<")) if i >= 0), default=-1)
|
|
29
|
+
if at < 0:
|
|
30
|
+
return None
|
|
31
|
+
return line[at], line[:at].strip(), [c.strip() for c in line[at + 1:].split(";") if c.strip()]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _position(t, cell):
|
|
35
|
+
"""A cell's position as the library stores it: an integer, or a fraction."""
|
|
36
|
+
return str(cell.num) if t.positions == "integer" else str(Fraction(cell.num, cell.den))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _rl_preorder(t):
|
|
40
|
+
"""DTree 3.0 stores no Q2: read it from the kids lists, right to left (for the plane)."""
|
|
41
|
+
out, stack = [], [t.get_node(t.root)]
|
|
42
|
+
while stack:
|
|
43
|
+
n = stack.pop()
|
|
44
|
+
out.append(n.name)
|
|
45
|
+
stack.extend(n.children) # pushed LR, popped RL
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _state(t, kind):
|
|
50
|
+
q1 = t.q1
|
|
51
|
+
if kind == "dtree":
|
|
52
|
+
# DTree 3.0: the one list Q1 as stored (no closing cells); each node's block runs from its
|
|
53
|
+
# own cell to the cell before its delimiter: its right sibling, or its parent's delimiter
|
|
54
|
+
cells, opens = [], {}
|
|
55
|
+
c = t.get_node(t.root).c
|
|
56
|
+
while c.name != "]":
|
|
57
|
+
cells.append([c.name, _position(t, c)])
|
|
58
|
+
opens[c.name] = len(cells) - 1
|
|
59
|
+
c = c.next
|
|
60
|
+
delim, end = {}, {}
|
|
61
|
+
for v in q1:
|
|
62
|
+
d = t._delimiter(t.get_node(v))
|
|
63
|
+
delim[v] = d.name # a vertex, or "]" (SINK)
|
|
64
|
+
end[v] = (opens[d.name] if d.name in opens else len(cells)) - 1
|
|
65
|
+
dpos = {v: (_position(t, t.get_node(delim[v]).c) if delim[v] in opens else "]") for v in q1}
|
|
66
|
+
pos = {v: [cells[opens[v]][1], dpos[v]] for v in q1}
|
|
67
|
+
run = {v: (n.run.top.name if n.run is not None else v) for v in q1 for n in [t.get_node(v)]}
|
|
68
|
+
return {"q1": q1, "q2": _rl_preorder(t), "pos": pos, "cells": cells, "open": opens,
|
|
69
|
+
"end": end, "delim": delim, "run": run}
|
|
70
|
+
if kind == "dtree2":
|
|
71
|
+
pos = {v: [str(t.Q1.index(v)), str(t.Q2.index(v))] for v in q1}
|
|
72
|
+
return {"q1": q1, "q2": t.q2, "pos": pos}
|
|
73
|
+
# EulerTree: the whole list, with the closing cells; each node's block runs from its own cell
|
|
74
|
+
# to its closing cell (to its own cell for a leaf). Read from the right, the block ends give
|
|
75
|
+
# Q2: sorting the nodes by their block end, last first, is DTree's second list.
|
|
76
|
+
cells, opens, ends = [], {}, {}
|
|
77
|
+
c = t.get_node(t.root).c1
|
|
78
|
+
while c.name != "]": # up to SINK
|
|
79
|
+
if c.name is None: # a closing cell: ")x" closes x's block
|
|
80
|
+
cells.append([")" + c.node.name, _position(t, c)])
|
|
81
|
+
ends[c.node.name] = len(cells) - 1
|
|
82
|
+
else:
|
|
83
|
+
cells.append([c.name, _position(t, c)])
|
|
84
|
+
opens[c.name] = len(cells) - 1
|
|
85
|
+
c = c.next
|
|
86
|
+
end = {v: ends.get(v, opens[v]) for v in q1}
|
|
87
|
+
q2 = sorted(q1, key=lambda v: -end[v])
|
|
88
|
+
pos = {v: [cells[opens[v]][1], cells[end[v]][1]] for v in q1}
|
|
89
|
+
return {"q1": q1, "q2": q2, "pos": pos, "cells": cells, "open": opens, "end": end}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def encode(text, limit=LIMIT, kind="dtree", positions="rational"):
|
|
93
|
+
"""Build a tree from the description and return the steps as JSON.
|
|
94
|
+
|
|
95
|
+
Each step is one inserted node: the operation, its line, the new node and its parent,
|
|
96
|
+
and (up to ``limit`` insertions) the full state after it: the lists and the positions.
|
|
97
|
+
``kind`` is "dtree" (DTree 3.0), "dtree2" (DTree 2.x, two lists) or "euler" (EulerTree),
|
|
98
|
+
``positions`` "rational" or "integer".
|
|
99
|
+
"""
|
|
100
|
+
if kind not in KINDS:
|
|
101
|
+
raise ValueError(f"kind must be one of {sorted(KINDS)}, not {kind!r}")
|
|
102
|
+
if positions not in POSITIONS:
|
|
103
|
+
raise ValueError(f"positions must be one of {POSITIONS}, not {positions!r}")
|
|
104
|
+
t = KINDS[kind]("E", positions=positions)
|
|
105
|
+
steps, errors, parents = [], [], {}
|
|
106
|
+
recording = True
|
|
107
|
+
for no, raw in enumerate(text.splitlines(), 1):
|
|
108
|
+
line = raw.strip().lstrip("")
|
|
109
|
+
if not line or line.startswith(("#", "--", "**")):
|
|
110
|
+
continue
|
|
111
|
+
if line.startswith("@@"):
|
|
112
|
+
break
|
|
113
|
+
parts = _split(line)
|
|
114
|
+
if parts is None:
|
|
115
|
+
errors.append({"line": no, "text": line, "msg": "expected ':', '>' or '<'"})
|
|
116
|
+
continue
|
|
117
|
+
op, anchor, kids = parts
|
|
118
|
+
for child in kids:
|
|
119
|
+
try:
|
|
120
|
+
if op == ":":
|
|
121
|
+
t.insert(anchor, child)
|
|
122
|
+
shown = f"{anchor}:{child}"
|
|
123
|
+
elif op == ">":
|
|
124
|
+
t.insert_after(anchor, child)
|
|
125
|
+
shown = f"{anchor}>{child}"
|
|
126
|
+
anchor = child
|
|
127
|
+
else:
|
|
128
|
+
t.insert_before(anchor, child)
|
|
129
|
+
shown = f"{anchor}<{child}"
|
|
130
|
+
except (KeyError, ValueError, TypeError) as e:
|
|
131
|
+
msg = e.args[0] if e.args else str(e)
|
|
132
|
+
errors.append({"line": no, "text": line, "msg": f"{child}: {msg}"})
|
|
133
|
+
continue
|
|
134
|
+
parents[child] = t.get_parent(child)
|
|
135
|
+
step = {"line": no, "op": shown, "new": child}
|
|
136
|
+
if recording and len(steps) < limit:
|
|
137
|
+
step.update(_state(t, kind))
|
|
138
|
+
elif recording:
|
|
139
|
+
recording = False
|
|
140
|
+
for s in steps:
|
|
141
|
+
for k in ("q1", "q2", "pos", "cells", "open", "end", "delim", "run"):
|
|
142
|
+
s.pop(k, None)
|
|
143
|
+
steps.append(step)
|
|
144
|
+
empty = {"q1": [], "q2": [], "pos": {}, "cells": [], "open": {}, "end": {}, "delim": {}, "run": {}}
|
|
145
|
+
final = _state(t, kind) if t.root is not None else empty
|
|
146
|
+
renumber = ([t.renumber_count] if kind == "dtree" else
|
|
147
|
+
[t.Q1.renumber_count] if kind == "euler" else [t.Q1.renumber_count, t.Q2.renumber_count])
|
|
148
|
+
return json.dumps({
|
|
149
|
+
"version": dtree.__version__,
|
|
150
|
+
"kind": kind,
|
|
151
|
+
"positions": positions,
|
|
152
|
+
"root": t.root,
|
|
153
|
+
"parents": parents,
|
|
154
|
+
"steps": steps,
|
|
155
|
+
"final": final,
|
|
156
|
+
"stepwise": recording,
|
|
157
|
+
"limit": limit,
|
|
158
|
+
"renumber": renumber,
|
|
159
|
+
"errors": errors,
|
|
160
|
+
})
|