triordinal-dtree-explorer 3.1.0__tar.gz
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.
- triordinal_dtree_explorer-3.1.0/PKG-INFO +89 -0
- triordinal_dtree_explorer-3.1.0/README.md +63 -0
- triordinal_dtree_explorer-3.1.0/dtree_explorer/__init__.py +3 -0
- triordinal_dtree_explorer-3.1.0/dtree_explorer/__main__.py +112 -0
- triordinal_dtree_explorer-3.1.0/dtree_explorer/bridge.py +160 -0
- triordinal_dtree_explorer-3.1.0/dtree_explorer/explorer.html +3419 -0
- triordinal_dtree_explorer-3.1.0/pyproject.toml +42 -0
- triordinal_dtree_explorer-3.1.0/setup.cfg +4 -0
- triordinal_dtree_explorer-3.1.0/tests/test_explorer.py +201 -0
- triordinal_dtree_explorer-3.1.0/triordinal_dtree_explorer.egg-info/PKG-INFO +89 -0
- triordinal_dtree_explorer-3.1.0/triordinal_dtree_explorer.egg-info/SOURCES.txt +13 -0
- triordinal_dtree_explorer-3.1.0/triordinal_dtree_explorer.egg-info/dependency_links.txt +1 -0
- triordinal_dtree_explorer-3.1.0/triordinal_dtree_explorer.egg-info/entry_points.txt +2 -0
- triordinal_dtree_explorer-3.1.0/triordinal_dtree_explorer.egg-info/requires.txt +1 -0
- triordinal_dtree_explorer-3.1.0/triordinal_dtree_explorer.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: triordinal-dtree-explorer
|
|
3
|
+
Version: 3.1.0
|
|
4
|
+
Summary: DTree Explorer: encode a directed tree with DTree 3.0 (one list, the structure in the nodes), DTree 2.x (two lists) or EulerTree and watch it step by step, in the browser
|
|
5
|
+
Author-email: Enis Olgac <enis@digraphs.info>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/EnisOlgac/Triordinal
|
|
8
|
+
Project-URL: Source, https://github.com/EnisOlgac/Triordinal/tree/main/python/explorer
|
|
9
|
+
Project-URL: Changelog, https://github.com/EnisOlgac/Triordinal/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Earlier versions, https://github.com/EnisOlgac/DTree-Explorer
|
|
11
|
+
Project-URL: Online, https://dtree.digraphs.net/
|
|
12
|
+
Project-URL: Paper, https://doi.org/10.5772/intechopen.1013408
|
|
13
|
+
Keywords: directed tree,tree topology,reachability,visualization,incremental encoding,teaching
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Intended Audience :: Education
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
Requires-Dist: triordinal-dtree<4,>=3.1.0
|
|
26
|
+
|
|
27
|
+
# DTree Explorer (triordinal-dtree-explorer)
|
|
28
|
+
|
|
29
|
+
Part of [Triordinal](https://github.com/EnisOlgac/Triordinal), next to DList and DTree, with the same version number. Versions up to 1.3.3 were published as `dtree-explorer` from [DTree-Explorer](https://github.com/EnisOlgac/DTree-Explorer) (archive: [doi:10.5281/zenodo.23701538](https://doi.org/10.5281/zenodo.23701538)).
|
|
30
|
+
|
|
31
|
+
Encode a directed tree with [DTree](https://github.com/EnisOlgac/Triordinal) and watch it happen, edge by edge. The Explorer draws the tree, places every node in the plane at its rank in Q1 and Q2, lists the projections with the positions the library stores, and answers reachability questions by clicking.
|
|
32
|
+
|
|
33
|
+
The card *Encoding*, below the tree description, offers two choices:
|
|
34
|
+
|
|
35
|
+
- **Lists:** **DTree 3.0** (the default) keeps one list, Q1, and the structure in the nodes: a node's block runs from its own cell to just before its *delimiter*, its next sibling or, for a last child, its parent's delimiter, and *u* reaches *v* exactly when *v* lies inside *u*'s block. View 3 shows Q1 with each node's delimiter below it, and picking two nodes names the step of the query that decides. **DTree 2.x** keeps two lists, Q1 and Q2: *u* reaches *v* exactly when *u* comes before *v* in both. **EulerTree** keeps Q1 alone with a closing cell after the subtree of every node with children (the Euler tour); view 3 shows Q1 as it grows, bracketed: `A[` opens the block of A, `]A` closes it. The plane is the same for all three: DTree 3.0 reads Q2 from the children right to left, EulerTree from its block ends.
|
|
36
|
+
- **Positions:** rational (fractions; a new cell takes the mediant of its neighbors) or integer (a new cell takes the midpoint of its neighbors' labels in [0, 2^62]).
|
|
37
|
+
|
|
38
|
+
The page remembers both choices.
|
|
39
|
+
|
|
40
|
+
On PyPI the Explorer is `triordinal-dtree-explorer`; it continues `dtree-explorer` (up to 1.3.3). The command is still `dtree-explorer`.
|
|
41
|
+
|
|
42
|
+
Every tree is computed by the published library, [triordinal-dtree](https://pypi.org/project/triordinal-dtree/) from [Triordinal](https://github.com/EnisOlgac/Triordinal) (formerly dtree-encoding); the Explorer only shows what it computes.
|
|
43
|
+
|
|
44
|
+
## Three ways to use it
|
|
45
|
+
|
|
46
|
+
**Online:** [dtree.digraphs.net](https://dtree.digraphs.net/), nothing to install.
|
|
47
|
+
|
|
48
|
+
**As a Python program**, offline, with the library installed on your machine:
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
pip install triordinal-dtree-explorer
|
|
52
|
+
dtree-explorer
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The command starts a small server on 127.0.0.1 and opens the page in your browser; stop it with Ctrl+C. It installs the matching triordinal-dtree. Options: `--port 8765`, `--no-browser`, `--save explorer.html` (write the page as one file).
|
|
56
|
+
|
|
57
|
+
**As a single file:** download `DTree-Explorer.html` from the [latest Triordinal release](https://github.com/EnisOlgac/Triordinal/releases/latest) and open it in a browser. It loads Python (Pyodide) from cdn.jsdelivr.net and triordinal-dtree from pypi.org, so it needs an internet connection.
|
|
58
|
+
|
|
59
|
+
## Input
|
|
60
|
+
|
|
61
|
+
One line per instruction; lines starting with `#` are comments.
|
|
62
|
+
|
|
63
|
+
| Line | Meaning |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `p: c1; c2` | c1 and c2 become the last children of p |
|
|
66
|
+
| `s > c1; c2` | c1 goes directly after its sibling s, then c2 after c1 |
|
|
67
|
+
| `s < c1; c2` | c1 and c2 go directly before s, in that order |
|
|
68
|
+
|
|
69
|
+
The examples include the trees of the paper: the introductory example, Figure 1, the generalized insertion of Section 4.1 (Case A, before; Case B, after) and Appendix A, whose three variants appear twice: once by the order of the input lines, once with `<` and `>`. Both give the same projections.
|
|
70
|
+
|
|
71
|
+
## Privacy
|
|
72
|
+
|
|
73
|
+
Your tree stays on your computer. Only the online copy at dtree.digraphs.net counts visits, with [GoatCounter](https://www.goatcounter.com/): no cookies, no personal data. The package and the release file count nothing.
|
|
74
|
+
|
|
75
|
+
## Building
|
|
76
|
+
|
|
77
|
+
The Explorer lives in `python/explorer` of the Triordinal repository and is built from the repository's own DList and DTree, so the page always matches the library of the same commit; nothing needs to be installed. `src/template.html` is the page, `dtree_explorer/bridge.py` the Python part it runs, `src/build.py` assembles `dtree_explorer/explorer.html` (package and release) and `site/index.html` (dtree.digraphs.net), with the examples from the repository's `examples/`. In `python/explorer`: `python src/build.py`, tests `python -m unittest discover -s tests`. The publish workflow rebuilds the page, publishes the package after DList and DTree, and attaches the page to the release as `DTree-Explorer.html`.
|
|
78
|
+
|
|
79
|
+
## Background
|
|
80
|
+
|
|
81
|
+
E. Olgac, "Topology and Structure of Directed Trees: An Incremental Encoding," IntechOpen, 2025. doi: [10.5772/intechopen.1013408](https://doi.org/10.5772/intechopen.1013408).
|
|
82
|
+
|
|
83
|
+
## Citation
|
|
84
|
+
|
|
85
|
+
E. Olgac, *DTree Explorer: Watching the Incremental Encoding of Directed Trees*, software, 2026. doi: [10.5281/zenodo.23701538](https://doi.org/10.5281/zenodo.23701538) (all versions). See `CITATION.cff`.
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
MIT. Design and concept: Enis Olgac. The Explorer was written with Claude (Anthropic).
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# DTree Explorer (triordinal-dtree-explorer)
|
|
2
|
+
|
|
3
|
+
Part of [Triordinal](https://github.com/EnisOlgac/Triordinal), next to DList and DTree, with the same version number. Versions up to 1.3.3 were published as `dtree-explorer` from [DTree-Explorer](https://github.com/EnisOlgac/DTree-Explorer) (archive: [doi:10.5281/zenodo.23701538](https://doi.org/10.5281/zenodo.23701538)).
|
|
4
|
+
|
|
5
|
+
Encode a directed tree with [DTree](https://github.com/EnisOlgac/Triordinal) and watch it happen, edge by edge. The Explorer draws the tree, places every node in the plane at its rank in Q1 and Q2, lists the projections with the positions the library stores, and answers reachability questions by clicking.
|
|
6
|
+
|
|
7
|
+
The card *Encoding*, below the tree description, offers two choices:
|
|
8
|
+
|
|
9
|
+
- **Lists:** **DTree 3.0** (the default) keeps one list, Q1, and the structure in the nodes: a node's block runs from its own cell to just before its *delimiter*, its next sibling or, for a last child, its parent's delimiter, and *u* reaches *v* exactly when *v* lies inside *u*'s block. View 3 shows Q1 with each node's delimiter below it, and picking two nodes names the step of the query that decides. **DTree 2.x** keeps two lists, Q1 and Q2: *u* reaches *v* exactly when *u* comes before *v* in both. **EulerTree** keeps Q1 alone with a closing cell after the subtree of every node with children (the Euler tour); view 3 shows Q1 as it grows, bracketed: `A[` opens the block of A, `]A` closes it. The plane is the same for all three: DTree 3.0 reads Q2 from the children right to left, EulerTree from its block ends.
|
|
10
|
+
- **Positions:** rational (fractions; a new cell takes the mediant of its neighbors) or integer (a new cell takes the midpoint of its neighbors' labels in [0, 2^62]).
|
|
11
|
+
|
|
12
|
+
The page remembers both choices.
|
|
13
|
+
|
|
14
|
+
On PyPI the Explorer is `triordinal-dtree-explorer`; it continues `dtree-explorer` (up to 1.3.3). The command is still `dtree-explorer`.
|
|
15
|
+
|
|
16
|
+
Every tree is computed by the published library, [triordinal-dtree](https://pypi.org/project/triordinal-dtree/) from [Triordinal](https://github.com/EnisOlgac/Triordinal) (formerly dtree-encoding); the Explorer only shows what it computes.
|
|
17
|
+
|
|
18
|
+
## Three ways to use it
|
|
19
|
+
|
|
20
|
+
**Online:** [dtree.digraphs.net](https://dtree.digraphs.net/), nothing to install.
|
|
21
|
+
|
|
22
|
+
**As a Python program**, offline, with the library installed on your machine:
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
pip install triordinal-dtree-explorer
|
|
26
|
+
dtree-explorer
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The command starts a small server on 127.0.0.1 and opens the page in your browser; stop it with Ctrl+C. It installs the matching triordinal-dtree. Options: `--port 8765`, `--no-browser`, `--save explorer.html` (write the page as one file).
|
|
30
|
+
|
|
31
|
+
**As a single file:** download `DTree-Explorer.html` from the [latest Triordinal release](https://github.com/EnisOlgac/Triordinal/releases/latest) and open it in a browser. It loads Python (Pyodide) from cdn.jsdelivr.net and triordinal-dtree from pypi.org, so it needs an internet connection.
|
|
32
|
+
|
|
33
|
+
## Input
|
|
34
|
+
|
|
35
|
+
One line per instruction; lines starting with `#` are comments.
|
|
36
|
+
|
|
37
|
+
| Line | Meaning |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `p: c1; c2` | c1 and c2 become the last children of p |
|
|
40
|
+
| `s > c1; c2` | c1 goes directly after its sibling s, then c2 after c1 |
|
|
41
|
+
| `s < c1; c2` | c1 and c2 go directly before s, in that order |
|
|
42
|
+
|
|
43
|
+
The examples include the trees of the paper: the introductory example, Figure 1, the generalized insertion of Section 4.1 (Case A, before; Case B, after) and Appendix A, whose three variants appear twice: once by the order of the input lines, once with `<` and `>`. Both give the same projections.
|
|
44
|
+
|
|
45
|
+
## Privacy
|
|
46
|
+
|
|
47
|
+
Your tree stays on your computer. Only the online copy at dtree.digraphs.net counts visits, with [GoatCounter](https://www.goatcounter.com/): no cookies, no personal data. The package and the release file count nothing.
|
|
48
|
+
|
|
49
|
+
## Building
|
|
50
|
+
|
|
51
|
+
The Explorer lives in `python/explorer` of the Triordinal repository and is built from the repository's own DList and DTree, so the page always matches the library of the same commit; nothing needs to be installed. `src/template.html` is the page, `dtree_explorer/bridge.py` the Python part it runs, `src/build.py` assembles `dtree_explorer/explorer.html` (package and release) and `site/index.html` (dtree.digraphs.net), with the examples from the repository's `examples/`. In `python/explorer`: `python src/build.py`, tests `python -m unittest discover -s tests`. The publish workflow rebuilds the page, publishes the package after DList and DTree, and attaches the page to the release as `DTree-Explorer.html`.
|
|
52
|
+
|
|
53
|
+
## Background
|
|
54
|
+
|
|
55
|
+
E. Olgac, "Topology and Structure of Directed Trees: An Incremental Encoding," IntechOpen, 2025. doi: [10.5772/intechopen.1013408](https://doi.org/10.5772/intechopen.1013408).
|
|
56
|
+
|
|
57
|
+
## Citation
|
|
58
|
+
|
|
59
|
+
E. Olgac, *DTree Explorer: Watching the Incremental Encoding of Directed Trees*, software, 2026. doi: [10.5281/zenodo.23701538](https://doi.org/10.5281/zenodo.23701538) (all versions). See `CITATION.cff`.
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
MIT. Design and concept: Enis Olgac. The Explorer was written with Claude (Anthropic).
|
|
@@ -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())
|
|
@@ -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
|
+
})
|