inets-kernel 0.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 N. E. Davis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: inets-kernel
3
+ Version: 0.1.0
4
+ Summary: A Jupyter kernel for interaction nets: write a table of rules, draw a net, and watch it reduce
5
+ Author: N. E. Davis
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/sigilante/inets
8
+ Keywords: interaction nets,jupyter,kernel
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Framework :: Jupyter
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: inets>=0.1.0
17
+ Requires-Dist: ipykernel>=6
18
+ Requires-Dist: jupyter_client>=7
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Requires-Dist: nbclient; extra == "test"
22
+ Requires-Dist: nbformat; extra == "test"
23
+ Dynamic: license-file
24
+
25
+ # inets-kernel
26
+
27
+ A Jupyter kernel for interaction nets, built on [inets](https://github.com/sigilante/inets).
28
+ Write a table of rules, draw a net, and watch it reduce.
29
+
30
+ ```sh
31
+ pip install inets-kernel
32
+ python -m inets_kernel.install --sys-prefix # into this Python environment; or --user
33
+ jupyter lab
34
+ ```
35
+
36
+ Choose "Interaction nets" for a notebook. `jupyter kernelspec uninstall inets` removes the
37
+ kernel again. The pictures need Graphviz's `dot` program; without it a cell shows the
38
+ Graphviz text instead.
39
+
40
+ ## A cell is one of three things
41
+
42
+ **A net.** Equations between ports, written as the right-hand side of a rule is:
43
+
44
+ ```
45
+ con (a b) = dup (era era)
46
+ ```
47
+
48
+ `con (a b)` is a node and stands for its principal port. A name that is not an agent is a
49
+ wire if it occurs twice and a free port if it occurs once. An agent with a parameter takes
50
+ it after its name, as in `atom 3`. The net is drawn, reduced by the current schedule, and
51
+ drawn again, with why it stopped and what it cost. The kernel starts with the table of the
52
+ symmetric interaction combinators (`con`, `dup`, `era`).
53
+
54
+ **A table.** Lines beginning `agent` or `rule` are added to the current table, in
55
+ [the format of `inets`](https://github.com/sigilante/inets/blob/master/src/inets/system.py),
56
+ and the table is checked:
57
+
58
+ ```
59
+ agent zero +
60
+ agent succ + -
61
+ agent add - - +
62
+
63
+ rule add (y r) >< zero
64
+ => r = y
65
+ count add
66
+ ```
67
+
68
+ **Commands**, one to a line:
69
+
70
+ | Command | Does |
71
+ |---|---|
72
+ | `%system NAME` | start from a bundled table (`combinators`, `ski`, `lazy`), or `new` for none |
73
+ | `%table`, `%check`, `%rules` | show the current table; check it; list its rules, marking those that are not local |
74
+ | `%schedule HOW` | `stack` (the default), `queue`, `random`, `rounds`, or `need PORT`: by need for the free port named PORT (default `out`), in a table with signs |
75
+ | `%cap N` | stop a run after N interactions (default 10000) |
76
+ | `%trace on` / `off` | with `rounds`, draw the net after each round, up to twelve |
77
+ | `%ski TERM [--rounds \| --lazy]` | reduce a term of S, K and I in prefix form, by need unless said |
78
+ | `%demo` | one term, K I Ω, reduced three ways |
79
+ | `%help` | this list |
80
+
81
+ A net of more than 80 nodes is described, not drawn.
82
+
83
+ ## Notebooks
84
+
85
+ Three are in [`notebooks/`](https://github.com/sigilante/inets/tree/master/notebooks) of the
86
+ repository: the three rules of the combinators; a system of your own, for adding numbers;
87
+ and one term reaching three ends.
88
+
89
+ ## Tests
90
+
91
+ ```sh
92
+ pip install -e '.[test]' # in kernel/, with inets installed
93
+ pytest
94
+ ```
95
+
96
+ The tests run what a cell means without Jupyter, and one notebook through the kernel
97
+ itself.
98
+
99
+ ## Licence
100
+
101
+ MIT.
@@ -0,0 +1,77 @@
1
+ # inets-kernel
2
+
3
+ A Jupyter kernel for interaction nets, built on [inets](https://github.com/sigilante/inets).
4
+ Write a table of rules, draw a net, and watch it reduce.
5
+
6
+ ```sh
7
+ pip install inets-kernel
8
+ python -m inets_kernel.install --sys-prefix # into this Python environment; or --user
9
+ jupyter lab
10
+ ```
11
+
12
+ Choose "Interaction nets" for a notebook. `jupyter kernelspec uninstall inets` removes the
13
+ kernel again. The pictures need Graphviz's `dot` program; without it a cell shows the
14
+ Graphviz text instead.
15
+
16
+ ## A cell is one of three things
17
+
18
+ **A net.** Equations between ports, written as the right-hand side of a rule is:
19
+
20
+ ```
21
+ con (a b) = dup (era era)
22
+ ```
23
+
24
+ `con (a b)` is a node and stands for its principal port. A name that is not an agent is a
25
+ wire if it occurs twice and a free port if it occurs once. An agent with a parameter takes
26
+ it after its name, as in `atom 3`. The net is drawn, reduced by the current schedule, and
27
+ drawn again, with why it stopped and what it cost. The kernel starts with the table of the
28
+ symmetric interaction combinators (`con`, `dup`, `era`).
29
+
30
+ **A table.** Lines beginning `agent` or `rule` are added to the current table, in
31
+ [the format of `inets`](https://github.com/sigilante/inets/blob/master/src/inets/system.py),
32
+ and the table is checked:
33
+
34
+ ```
35
+ agent zero +
36
+ agent succ + -
37
+ agent add - - +
38
+
39
+ rule add (y r) >< zero
40
+ => r = y
41
+ count add
42
+ ```
43
+
44
+ **Commands**, one to a line:
45
+
46
+ | Command | Does |
47
+ |---|---|
48
+ | `%system NAME` | start from a bundled table (`combinators`, `ski`, `lazy`), or `new` for none |
49
+ | `%table`, `%check`, `%rules` | show the current table; check it; list its rules, marking those that are not local |
50
+ | `%schedule HOW` | `stack` (the default), `queue`, `random`, `rounds`, or `need PORT`: by need for the free port named PORT (default `out`), in a table with signs |
51
+ | `%cap N` | stop a run after N interactions (default 10000) |
52
+ | `%trace on` / `off` | with `rounds`, draw the net after each round, up to twelve |
53
+ | `%ski TERM [--rounds \| --lazy]` | reduce a term of S, K and I in prefix form, by need unless said |
54
+ | `%demo` | one term, K I Ω, reduced three ways |
55
+ | `%help` | this list |
56
+
57
+ A net of more than 80 nodes is described, not drawn.
58
+
59
+ ## Notebooks
60
+
61
+ Three are in [`notebooks/`](https://github.com/sigilante/inets/tree/master/notebooks) of the
62
+ repository: the three rules of the combinators; a system of your own, for adding numbers;
63
+ and one term reaching three ends.
64
+
65
+ ## Tests
66
+
67
+ ```sh
68
+ pip install -e '.[test]' # in kernel/, with inets installed
69
+ pytest
70
+ ```
71
+
72
+ The tests run what a cell means without Jupyter, and one notebook through the kernel
73
+ itself.
74
+
75
+ ## Licence
76
+
77
+ MIT.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "inets-kernel"
7
+ version = "0.1.0"
8
+ description = "A Jupyter kernel for interaction nets: write a table of rules, draw a net, and watch it reduce"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "N. E. Davis" }]
14
+ keywords = ["interaction nets", "jupyter", "kernel"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Framework :: Jupyter",
18
+ "Intended Audience :: Education",
19
+ "Programming Language :: Python :: 3",
20
+ ]
21
+ dependencies = ["inets>=0.1.0", "ipykernel>=6", "jupyter_client>=7"]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest", "nbclient", "nbformat"]
25
+
26
+ [project.urls]
27
+ Repository = "https://github.com/sigilante/inets"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+ [tool.setuptools.package-data]
33
+ "inets_kernel" = ["kernelspec/*.json"]
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+ pythonpath = ["src", "../src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """A Jupyter kernel for interaction nets, built on :mod:`inets`.
2
+
3
+ Install the kernel into Jupyter with ``python -m inets_kernel.install``, then choose
4
+ "Interaction nets" for a notebook. What a cell means is in :mod:`inets_kernel.session`.
5
+ """
6
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ from ipykernel.kernelapp import IPKernelApp
2
+
3
+ from .kernel import InetsKernel
4
+
5
+ IPKernelApp.launch_instance(kernel_class=InetsKernel)
@@ -0,0 +1,46 @@
1
+ """``python -m inets_kernel.install`` puts the kernel where Jupyter looks for kernels, so
2
+ that "Interaction nets" can be chosen for a notebook.
3
+
4
+ python -m inets_kernel.install [--user | --sys-prefix | --prefix PATH]
5
+
6
+ The default is Jupyter's own choice, which may need rights to write system directories;
7
+ ``--sys-prefix`` installs into the current Python environment and ``--user`` into the
8
+ user's Jupyter directory. ``jupyter kernelspec uninstall inets`` removes it.
9
+ """
10
+ import argparse
11
+ import json
12
+ import sys
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ from jupyter_client.kernelspec import KernelSpecManager
17
+
18
+ KERNEL_NAME = "inets"
19
+ SPEC = Path(__file__).parent / "kernelspec" / "kernel.json"
20
+
21
+
22
+ def install(user=False, prefix=None):
23
+ """Installs the kernel's description and returns where it went. The description
24
+ names the Python that is running this, so the kernel starts in the same environment."""
25
+ spec = json.loads(SPEC.read_text())
26
+ spec["argv"][0] = sys.executable
27
+ with tempfile.TemporaryDirectory() as directory:
28
+ target = Path(directory) / KERNEL_NAME
29
+ target.mkdir()
30
+ (target / "kernel.json").write_text(json.dumps(spec, indent=2))
31
+ return KernelSpecManager().install_kernel_spec(str(target), kernel_name=KERNEL_NAME, user=user, prefix=prefix)
32
+
33
+
34
+ def main(argv=None):
35
+ parser = argparse.ArgumentParser(description="Install the Interaction nets kernel for Jupyter")
36
+ where = parser.add_mutually_exclusive_group()
37
+ where.add_argument("--user", action="store_true", help="install into the user's Jupyter directory")
38
+ where.add_argument("--sys-prefix", action="store_true", help="install into this Python environment")
39
+ where.add_argument("--prefix", default=None, help="install under this directory")
40
+ args = parser.parse_args(argv)
41
+ prefix = sys.prefix if args.sys_prefix else args.prefix
42
+ print("installed the kernel in", install(user=args.user, prefix=prefix))
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,44 @@
1
+ """The Jupyter side: hands each cell to a :class:`~inets_kernel.session.Session` and
2
+ sends back what it returns."""
3
+ from ipykernel.kernelbase import Kernel
4
+
5
+ from . import __version__
6
+ from .session import Session
7
+
8
+
9
+ class InetsKernel(Kernel):
10
+ implementation = "inets"
11
+ implementation_version = __version__
12
+ language = "inets"
13
+ language_version = "0.1"
14
+ language_info = {"name": "inets", "file_extension": ".inet", "mimetype": "text/plain", "pygments_lexer": "text"}
15
+ banner = "Interaction nets. Try: con (a b) = dup (era era) or %help"
16
+
17
+ def __init__(self, **kwargs):
18
+ super().__init__(**kwargs)
19
+ self.cells = Session()
20
+
21
+ async def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False,
22
+ *, cell_meta=None, cell_id=None):
23
+ error = None
24
+ try:
25
+ outputs = self.cells.execute(code)
26
+ except Exception as e: # a fault of the kernel's own: say so, and keep going
27
+ outputs, error = [], f"{type(e).__name__}: {e}"
28
+ for o in outputs:
29
+ if o.kind == "error":
30
+ error = o.data
31
+ elif not silent and o.kind == "svg":
32
+ self.send_response(self.iopub_socket, "display_data",
33
+ {"data": {"image/svg+xml": o.data, "text/plain": "(a picture of the net)"}, "metadata": {}})
34
+ elif not silent:
35
+ self.send_response(self.iopub_socket, "stream", {"name": "stdout", "text": o.data + "\n"})
36
+ if error is not None:
37
+ reply = {"ename": "Error", "evalue": error, "traceback": [error]}
38
+ if not silent:
39
+ self.send_response(self.iopub_socket, "error", reply)
40
+ return {"status": "error", "execution_count": self.execution_count, **reply}
41
+ return {"status": "ok", "execution_count": self.execution_count, "payload": [], "user_expressions": {}}
42
+
43
+ def do_is_complete(self, code):
44
+ return {"status": "complete"}
@@ -0,0 +1,6 @@
1
+ {
2
+ "argv": ["python", "-m", "inets_kernel", "-f", "{connection_file}"],
3
+ "display_name": "Interaction nets",
4
+ "language": "inets",
5
+ "interrupt_mode": "signal"
6
+ }
@@ -0,0 +1,316 @@
1
+ """What a cell means. No Jupyter here: a :class:`Session` takes a cell's text and returns
2
+ a list of outputs, so it can be tested and used on its own.
3
+
4
+ A cell is one of three things.
5
+
6
+ **A table.** Lines beginning ``agent`` or ``rule`` (with a rule's ``=>``, ``count`` and
7
+ ``flag`` lines) are added to the current table, in the format of :mod:`inets.system`. The
8
+ table is then checked.
9
+
10
+ **A net.** Equations between ports, written as the right-hand side of a rule is::
11
+
12
+ con (a b) = dup (era era)
13
+
14
+ ``con (a b)`` is a node and stands for its principal port. A name that is not an agent is a
15
+ wire if it occurs twice and a free port if it occurs once. An agent with a parameter takes
16
+ it after its name: ``atom 3``. Equations are separated by ``;`` or new lines. The net is
17
+ drawn, reduced by the current schedule, and drawn again, with why it stopped and what it
18
+ cost.
19
+
20
+ **Commands**, one to a line, beginning ``%``:
21
+
22
+ %system NAME start from a bundled table (combinators, ski, lazy), or `new` for none
23
+ %table show the current table
24
+ %check check it
25
+ %rules list its rules, marking those that are not local
26
+ %schedule HOW stack (default), queue, random, rounds, or `need PORT`: by need for
27
+ the free port named PORT (default out), in a table with signs
28
+ %cap N stop a run after N interactions (default 10000)
29
+ %trace on|off with `rounds`, draw the net before each round (off by default)
30
+ %ski TERM [--rounds | --lazy]
31
+ reduce a term of S, K and I in prefix form, by need unless said
32
+ %demo one term, K I Ω, reduced three ways
33
+ %help this list
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import contextlib
38
+ import io
39
+ import shutil
40
+ import subprocess
41
+ from dataclasses import dataclass
42
+
43
+ import inets
44
+ from inets import ski
45
+ from inets.system import BUNDLED, tokens
46
+
47
+ HELP = __doc__.split("**Commands**")[1].split("\n\n", 1)[1].rstrip('"\n ')
48
+ SCHEDULES = ("stack", "queue", "random", "rounds", "need")
49
+ DRAW_UP_TO = 80 # nodes: larger nets are described, not drawn
50
+ FRAMES = 12 # the most rounds drawn by %trace
51
+
52
+
53
+ @dataclass
54
+ class Output:
55
+ """One thing a cell shows: ``kind`` is ``"text"``, ``"svg"`` or ``"error"``."""
56
+ kind: str
57
+ data: str
58
+
59
+
60
+ class CellError(Exception):
61
+ """A cell that cannot be carried out."""
62
+
63
+
64
+ def _svg(dot):
65
+ """Graphviz text as SVG, or None if there is no `dot` program."""
66
+ program = shutil.which("dot")
67
+ if not program:
68
+ return None
69
+ try:
70
+ r = subprocess.run([program, "-Tsvg"], input=dot, capture_output=True, text=True, timeout=30)
71
+ except (OSError, subprocess.TimeoutExpired):
72
+ return None
73
+ return r.stdout[r.stdout.index("<svg"):] if r.returncode == 0 and "<svg" in r.stdout else None
74
+
75
+
76
+ class Session:
77
+ def __init__(self):
78
+ self.text = ""
79
+ self.system = inets.System.parse("")
80
+ self.schedule, self.wanted = "stack", "out"
81
+ self.cap, self.trace = 10000, False
82
+ self.use("combinators")
83
+
84
+ def use(self, name):
85
+ if name == "new":
86
+ self.text = ""
87
+ elif name in BUNDLED and name != "ivm":
88
+ from importlib import resources
89
+ self.text = resources.files("inets.systems").joinpath(name + ".rules").read_text(encoding="utf-8")
90
+ else:
91
+ raise CellError(f"no table {name}: there are combinators, ski, lazy, and `new`")
92
+ self.system = inets.System.parse(self.text, name)
93
+
94
+ # --- a cell -----------------------------------------------------------------------
95
+
96
+ def execute(self, code):
97
+ """The outputs of a cell. An error ends the cell, and is the last output."""
98
+ out = []
99
+ try:
100
+ lines = code.split("\n")
101
+ rest = []
102
+ for line in lines:
103
+ if line.strip().startswith("%"):
104
+ out.extend(self.command(line.strip()))
105
+ else:
106
+ rest.append(line)
107
+ body = "\n".join(rest)
108
+ plain = "\n".join(l.split("#", 1)[0] for l in rest).strip()
109
+ if plain:
110
+ first = plain.split()[0]
111
+ out.extend(self.table(body) if first in ("agent", "rule") else self.net(plain))
112
+ except (CellError, inets.Error) as e:
113
+ out.append(Output("error", str(e)))
114
+ return out
115
+
116
+ # --- commands ---------------------------------------------------------------------
117
+
118
+ def command(self, line):
119
+ word, _, rest = line[1:].partition(" ")
120
+ rest = rest.strip()
121
+ if word == "help":
122
+ return [Output("text", HELP)]
123
+ if word == "system":
124
+ self.use(rest or "combinators")
125
+ return [Output("text", self.describe())]
126
+ if word == "table":
127
+ return [Output("text", self.text.strip() or "(no agents or rules yet)")]
128
+ if word == "check":
129
+ return [Output("text", self.describe())]
130
+ if word == "rules":
131
+ return [Output("text", "\n".join(
132
+ f"{r.count or '?':<11} {r}" + (f" [not local: {', '.join(r.not_local)}]" if r.not_local else "")
133
+ for r in self.system.rules) or "(no rules yet)")]
134
+ if word == "schedule":
135
+ how, _, port = rest.partition(" ")
136
+ if how not in SCHEDULES:
137
+ raise CellError("a schedule is one of: " + ", ".join(SCHEDULES))
138
+ self.schedule, self.wanted = how, port.strip() or "out"
139
+ return [Output("text", f"schedule: {how}" + (f", for the free port {self.wanted}" if how == "need" else ""))]
140
+ if word == "cap":
141
+ if not rest.isdigit() or int(rest) < 1:
142
+ raise CellError("%cap takes a whole number of interactions")
143
+ self.cap = int(rest)
144
+ return [Output("text", f"a run stops after {self.cap} interactions")]
145
+ if word == "trace":
146
+ if rest not in ("on", "off"):
147
+ raise CellError("%trace on, or %trace off")
148
+ self.trace = rest == "on"
149
+ return [Output("text", f"trace: {rest}")]
150
+ if word == "ski":
151
+ return self.ski(rest)
152
+ if word == "demo":
153
+ from inets.__main__ import demo
154
+ text = io.StringIO()
155
+ with contextlib.redirect_stdout(text):
156
+ demo()
157
+ return [Output("text", text.getvalue().rstrip())]
158
+ raise CellError(f"no command %{word}: see %help")
159
+
160
+ def describe(self):
161
+ problems = self.system.check()
162
+ head = (f"{len(self.system.agents)} agents, {len(self.system.rules)} rules, "
163
+ f"{'with' if self.system.signed else 'without'} signs; {len(problems)} problems")
164
+ return "\n".join([head] + [" " + p for p in problems])
165
+
166
+ # --- a table ----------------------------------------------------------------------
167
+
168
+ def table(self, body):
169
+ text = (self.text.rstrip() + "\n\n" if self.text.strip() else "") + body.strip() + "\n"
170
+ system = inets.System.parse(text, "cell") # a table that cannot be read changes nothing
171
+ self.text, self.system = text, system
172
+ return [Output("text", self.describe())]
173
+
174
+ # --- a net ------------------------------------------------------------------------
175
+
176
+ def build(self, text):
177
+ """A net from equations: ``(net, {free port's name: port})``."""
178
+ net = inets.Net(self.system, inets.Library())
179
+ agents = self.system.agents
180
+ seen, count = {}, {}
181
+
182
+ def meet(name, port):
183
+ count[name] = count.get(name, 0) + 1
184
+ if count[name] > 2:
185
+ raise CellError(f"the wire {name} has more than two ends")
186
+ if name in seen:
187
+ net.wire(seen.pop(name), port)
188
+ else:
189
+ seen[name] = port
190
+
191
+ def term(toks):
192
+ head = toks.pop(0)
193
+ if head in ("(", ")", "=", ";"):
194
+ raise CellError(f"expected a node or a wire, not {head}")
195
+ if head not in agents:
196
+ return head
197
+ agent = agents[head]
198
+ param = None
199
+ if agent.param:
200
+ if not toks:
201
+ raise CellError(f"{head} takes a parameter")
202
+ word = toks.pop(0)
203
+ param = int(word) if word.isdigit() else word
204
+ n = net.add_node(head, param)
205
+ if agent.arity:
206
+ if not toks or toks.pop(0) != "(":
207
+ raise CellError(f"{head} needs its {agent.arity} ports in brackets")
208
+ i = 0
209
+ while toks and toks[0] != ")":
210
+ i += 1
211
+ if i > agent.arity:
212
+ raise CellError(f"{head} has {agent.arity} auxiliary ports")
213
+ kid = term(toks)
214
+ if isinstance(kid, str):
215
+ meet(kid, inets.Port(n, i))
216
+ else:
217
+ net.wire(inets.Port(n, i), kid)
218
+ if not toks or i != agent.arity:
219
+ raise CellError(f"{head} has {agent.arity} auxiliary ports")
220
+ toks.pop(0)
221
+ return inets.Port(n, 0)
222
+
223
+ for equation in text.replace("\n", ";").split(";"):
224
+ if not equation.strip():
225
+ continue
226
+ toks = tokens(equation)
227
+ a = term(toks)
228
+ if not toks or toks.pop(0) != "=":
229
+ raise CellError("an equation is PORT = PORT: " + equation.strip())
230
+ b = term(toks)
231
+ if toks:
232
+ raise CellError("unexpected " + toks[0] + " in: " + equation.strip())
233
+ if isinstance(a, str) and isinstance(b, str):
234
+ raise CellError(f"{a} = {b} joins two wires: write one name for both")
235
+ if isinstance(a, str):
236
+ meet(a, b)
237
+ elif isinstance(b, str):
238
+ meet(b, a)
239
+ else:
240
+ net.wire(a, b)
241
+ free = {}
242
+ for name, port in seen.items():
243
+ free[name] = net.free()
244
+ net.wire(free[name], port)
245
+ return net, free
246
+
247
+ def picture(self, net, free, title):
248
+ names = {port: name for name, port in free.items()}
249
+ if len(net.kind) > DRAW_UP_TO:
250
+ return [Output("text", f"{title}: {len(net.kind)} nodes (too many to draw)")]
251
+ svg = _svg(net.dot(names))
252
+ if svg is None:
253
+ return [Output("text", f"{title} (no `dot` program was found, so here is the Graphviz text):\n{net.dot(names)}")]
254
+ return [Output("text", title + ":"), Output("svg", svg)]
255
+
256
+ @staticmethod
257
+ def says(result):
258
+ extra = f", in {result.rounds} rounds, the widest of {result.widest}" if result.rounds else ""
259
+ counts = ", ".join(f"{k} {v}" for k, v in sorted(result.counts.items()))
260
+ why = {"normal": "no active pair is left", "wanted": "the value wanted is there",
261
+ "interactions": "the cap was reached"}[result.reason]
262
+ return (f"stopped: {why} ({result.reason}); {result.interactions} interactions{extra}; "
263
+ f"{result.active_left} active pairs left" + (f"; {counts}" if counts else ""))
264
+
265
+ def net(self, text):
266
+ if not self.system.agents:
267
+ raise CellError("there is no table yet: define agents and rules, or use %system")
268
+ net, free = self.build(text)
269
+ out = self.picture(net, free, "the net")
270
+ if self.schedule == "rounds" and self.trace:
271
+ result, frames = None, 0
272
+ total = inets.Result("normal")
273
+ while True:
274
+ result = net.reduce_in_rounds(max_interactions=1) if net.active() else None
275
+ if result is None:
276
+ break
277
+ # One round at a time: a cap of 1 lets exactly one round run.
278
+ frames += 1
279
+ total.interactions += result.interactions
280
+ total.rounds += 1
281
+ total.widest = max(total.widest, result.widest)
282
+ for k, v in result.counts.items():
283
+ total.counts[k] = total.counts.get(k, 0) + v
284
+ if frames <= FRAMES:
285
+ out += self.picture(net, free, f"after round {frames}")
286
+ if total.interactions >= self.cap:
287
+ total.reason = "interactions"
288
+ break
289
+ total.active_left = len(net.active())
290
+ out.append(Output("text", self.says(total)))
291
+ return out
292
+ if self.schedule == "rounds":
293
+ result = net.reduce_in_rounds(max_interactions=self.cap)
294
+ elif self.schedule == "need":
295
+ if self.wanted not in free:
296
+ raise CellError(f"by need wants a free port named {self.wanted}: the net's free ports are "
297
+ + (", ".join(sorted(free)) or "none"))
298
+ result = net.reduce_by_need(free[self.wanted], max_interactions=self.cap)
299
+ else:
300
+ result = net.reduce(order=self.schedule, max_interactions=self.cap)
301
+ out.append(Output("text", self.says(result)))
302
+ out += self.picture(net, free, "what is left")
303
+ return out
304
+
305
+ # --- S, K and I -------------------------------------------------------------------
306
+
307
+ def ski(self, rest):
308
+ words = rest.split()
309
+ flags = [w for w in words if w.startswith("--")]
310
+ terms = [w for w in words if not w.startswith("--")]
311
+ if len(terms) != 1 or any(f not in ("--rounds", "--lazy") for f in flags) or len(flags) > 1:
312
+ raise CellError("%ski TERM [--rounds | --lazy]")
313
+ schedule = "rounds" if "--rounds" in flags else "lazy" if "--lazy" in flags else "need"
314
+ run = ski.run(terms[0], schedule=schedule, max_interactions=self.cap)
315
+ answer = ski.show(run.term) if run.result.finished else "no answer: the cap was reached"
316
+ return [Output("text", f"{answer}\n{self.says(run.result)}")]
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: inets-kernel
3
+ Version: 0.1.0
4
+ Summary: A Jupyter kernel for interaction nets: write a table of rules, draw a net, and watch it reduce
5
+ Author: N. E. Davis
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/sigilante/inets
8
+ Keywords: interaction nets,jupyter,kernel
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Framework :: Jupyter
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: inets>=0.1.0
17
+ Requires-Dist: ipykernel>=6
18
+ Requires-Dist: jupyter_client>=7
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Requires-Dist: nbclient; extra == "test"
22
+ Requires-Dist: nbformat; extra == "test"
23
+ Dynamic: license-file
24
+
25
+ # inets-kernel
26
+
27
+ A Jupyter kernel for interaction nets, built on [inets](https://github.com/sigilante/inets).
28
+ Write a table of rules, draw a net, and watch it reduce.
29
+
30
+ ```sh
31
+ pip install inets-kernel
32
+ python -m inets_kernel.install --sys-prefix # into this Python environment; or --user
33
+ jupyter lab
34
+ ```
35
+
36
+ Choose "Interaction nets" for a notebook. `jupyter kernelspec uninstall inets` removes the
37
+ kernel again. The pictures need Graphviz's `dot` program; without it a cell shows the
38
+ Graphviz text instead.
39
+
40
+ ## A cell is one of three things
41
+
42
+ **A net.** Equations between ports, written as the right-hand side of a rule is:
43
+
44
+ ```
45
+ con (a b) = dup (era era)
46
+ ```
47
+
48
+ `con (a b)` is a node and stands for its principal port. A name that is not an agent is a
49
+ wire if it occurs twice and a free port if it occurs once. An agent with a parameter takes
50
+ it after its name, as in `atom 3`. The net is drawn, reduced by the current schedule, and
51
+ drawn again, with why it stopped and what it cost. The kernel starts with the table of the
52
+ symmetric interaction combinators (`con`, `dup`, `era`).
53
+
54
+ **A table.** Lines beginning `agent` or `rule` are added to the current table, in
55
+ [the format of `inets`](https://github.com/sigilante/inets/blob/master/src/inets/system.py),
56
+ and the table is checked:
57
+
58
+ ```
59
+ agent zero +
60
+ agent succ + -
61
+ agent add - - +
62
+
63
+ rule add (y r) >< zero
64
+ => r = y
65
+ count add
66
+ ```
67
+
68
+ **Commands**, one to a line:
69
+
70
+ | Command | Does |
71
+ |---|---|
72
+ | `%system NAME` | start from a bundled table (`combinators`, `ski`, `lazy`), or `new` for none |
73
+ | `%table`, `%check`, `%rules` | show the current table; check it; list its rules, marking those that are not local |
74
+ | `%schedule HOW` | `stack` (the default), `queue`, `random`, `rounds`, or `need PORT`: by need for the free port named PORT (default `out`), in a table with signs |
75
+ | `%cap N` | stop a run after N interactions (default 10000) |
76
+ | `%trace on` / `off` | with `rounds`, draw the net after each round, up to twelve |
77
+ | `%ski TERM [--rounds \| --lazy]` | reduce a term of S, K and I in prefix form, by need unless said |
78
+ | `%demo` | one term, K I Ω, reduced three ways |
79
+ | `%help` | this list |
80
+
81
+ A net of more than 80 nodes is described, not drawn.
82
+
83
+ ## Notebooks
84
+
85
+ Three are in [`notebooks/`](https://github.com/sigilante/inets/tree/master/notebooks) of the
86
+ repository: the three rules of the combinators; a system of your own, for adding numbers;
87
+ and one term reaching three ends.
88
+
89
+ ## Tests
90
+
91
+ ```sh
92
+ pip install -e '.[test]' # in kernel/, with inets installed
93
+ pytest
94
+ ```
95
+
96
+ The tests run what a cell means without Jupyter, and one notebook through the kernel
97
+ itself.
98
+
99
+ ## Licence
100
+
101
+ MIT.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/inets_kernel/__init__.py
5
+ src/inets_kernel/__main__.py
6
+ src/inets_kernel/install.py
7
+ src/inets_kernel/kernel.py
8
+ src/inets_kernel/session.py
9
+ src/inets_kernel.egg-info/PKG-INFO
10
+ src/inets_kernel.egg-info/SOURCES.txt
11
+ src/inets_kernel.egg-info/dependency_links.txt
12
+ src/inets_kernel.egg-info/requires.txt
13
+ src/inets_kernel.egg-info/top_level.txt
14
+ src/inets_kernel/kernelspec/kernel.json
15
+ tests/test_kernel.py
16
+ tests/test_session.py
@@ -0,0 +1,8 @@
1
+ inets>=0.1.0
2
+ ipykernel>=6
3
+ jupyter_client>=7
4
+
5
+ [test]
6
+ pytest
7
+ nbclient
8
+ nbformat
@@ -0,0 +1 @@
1
+ inets_kernel
@@ -0,0 +1,27 @@
1
+ """The kernel itself, through Jupyter: installed into a temporary directory and given a
2
+ small notebook to run."""
3
+ import os
4
+ import sys
5
+
6
+ import pytest
7
+
8
+ nbclient = pytest.importorskip("nbclient")
9
+ nbformat = pytest.importorskip("nbformat")
10
+
11
+
12
+ def test_a_notebook_runs_through_the_kernel(tmp_path, monkeypatch):
13
+ import inets_kernel.install
14
+ inets_kernel.install.install(prefix=str(tmp_path))
15
+ monkeypatch.setenv("JUPYTER_PATH", str(tmp_path / "share" / "jupyter"))
16
+ here = os.path.dirname(os.path.abspath(__file__))
17
+ paths = [os.path.join(here, "..", "src"), os.path.join(here, "..", "..", "src")]
18
+ monkeypatch.setenv("PYTHONPATH", os.pathsep.join(paths + [os.environ.get("PYTHONPATH", "")]))
19
+ cells = ["con (a b) = dup (era era)", "%schedule sideways", "%ski ``KI```SII``SII"]
20
+ nb = nbformat.v4.new_notebook(cells=[nbformat.v4.new_code_cell(c) for c in cells])
21
+ nbclient.NotebookClient(nb, kernel_name="inets", timeout=60, allow_errors=True).execute()
22
+ first, second, third = (c.outputs for c in nb.cells)
23
+ text = "".join(o.get("text", "") for o in first if o.output_type == "stream")
24
+ assert "3 interactions" in text and "commute 1, erase 2" in text
25
+ assert [o.output_type for o in second] == ["error"] and "a schedule is one of" in second[0].evalue
26
+ assert "".join(o.get("text", "") for o in third).startswith("I\n")
27
+ assert sys.executable in (tmp_path / "share" / "jupyter" / "kernels" / "inets" / "kernel.json").read_text()
@@ -0,0 +1,111 @@
1
+ import shutil
2
+
3
+ import pytest
4
+
5
+ from inets_kernel.session import Session
6
+
7
+
8
+ def texts(outputs):
9
+ return "\n".join(o.data for o in outputs if o.kind == "text")
10
+
11
+
12
+ def kinds(outputs):
13
+ return [o.kind for o in outputs]
14
+
15
+
16
+ def test_a_net_is_drawn_reduced_and_drawn_again():
17
+ s = Session()
18
+ out = s.execute("con (a b) = dup (era era)")
19
+ assert "error" not in kinds(out)
20
+ assert "stopped: no active pair is left (normal); 3 interactions" in texts(out)
21
+ assert "commute 1, erase 2" in texts(out)
22
+ if shutil.which("dot"):
23
+ assert kinds(out).count("svg") == 2 and all(o.data.startswith("<svg") for o in out if o.kind == "svg")
24
+ else:
25
+ assert "Graphviz text" in texts(out)
26
+
27
+
28
+ def test_free_ports_are_the_names_used_once():
29
+ s = Session()
30
+ net, free = s.build("con (a b) = con (c d)")
31
+ assert sorted(free) == ["a", "b", "c", "d"]
32
+ net.reduce()
33
+ assert net.link[free["a"]] == free["c"] and net.link[free["b"]] == free["d"]
34
+
35
+
36
+ def test_a_table_can_be_written_cell_by_cell():
37
+ s = Session()
38
+ assert "0 agents" in texts(s.execute("%system new"))
39
+ out = s.execute("agent zero +\nagent succ + -\nagent add - - +")
40
+ assert "3 agents, 0 rules, with signs; 2 problems" in texts(out)
41
+ out = s.execute("rule add (y r) >< zero\n => r = y\n count add\n\n"
42
+ "rule add (y r) >< succ (x)\n => r = succ (s); x = add (y s)\n count add")
43
+ assert "3 agents, 2 rules, with signs; 0 problems" in texts(out)
44
+ out = s.execute("%schedule rounds\nsucc (succ (zero)) = add (succ (zero) out)") # 2 + 1
45
+ assert "3 interactions, in 3 rounds" in texts(out) and "error" not in kinds(out)
46
+ net, free = s.build("succ (succ (zero)) = add (succ (zero) out)")
47
+ net.reduce()
48
+ n, depth = net.link[free["out"]].node, 0
49
+ while net.kind[n] == "succ":
50
+ n, depth = net.link[(n, 1)].node, depth + 1
51
+ assert (net.kind[n], depth) == ("zero", 3)
52
+
53
+
54
+ def test_a_table_that_cannot_be_read_changes_nothing():
55
+ s = Session()
56
+ before = s.text
57
+ out = s.execute("agent broken")
58
+ assert kinds(out) == ["error"] and s.text == before
59
+
60
+
61
+ @pytest.mark.parametrize("cell,phrase", [
62
+ ("con (a b) = con (a a)", "more than two ends"),
63
+ ("con (a) = era", "2 auxiliary ports"),
64
+ ("a = b", "joins two wires"),
65
+ ("con (a b) era", "an equation is"),
66
+ ("%nonsense", "no command"),
67
+ ("%schedule sideways", "a schedule is one of"),
68
+ ("%system ivm", "no table ivm"),
69
+ ("%cap many", "whole number"),
70
+ ("%schedule need\ncon (out b) = era", "needs a table with signs"),
71
+ ])
72
+ def test_mistakes_are_reported_in_words(cell, phrase):
73
+ out = Session().execute(cell)
74
+ assert out[-1].kind == "error" and phrase in out[-1].data
75
+
76
+
77
+ def test_by_need_wants_its_port():
78
+ s = Session()
79
+ s.execute("%system ski")
80
+ out = s.execute("%schedule need\nS = app (K r)")
81
+ assert out[-1].kind == "error" and "free port named out" in out[-1].data
82
+ out = s.execute("%schedule need\nI = app (K out)")
83
+ assert "the value wanted is there (wanted)" in texts(out)
84
+
85
+
86
+ def test_trace_draws_each_round_and_adds_up():
87
+ s = Session()
88
+ s.execute("%schedule rounds\n%trace on")
89
+ out = s.execute("con (con (era era) con (era era)) = dup (era era)")
90
+ assert "after round 1" in texts(out)
91
+ plain = Session()
92
+ plain.execute("%schedule rounds")
93
+ untraced = texts(plain.execute("con (con (era era) con (era era)) = dup (era era)"))
94
+ assert untraced.split("stopped")[1].split("\n")[0] == texts(out).split("stopped")[1].split("\n")[0]
95
+
96
+
97
+ def test_the_cap_stops_a_run():
98
+ s = Session()
99
+ out = s.execute("%cap 50\n%ski ```SII``SII --rounds")
100
+ assert "no answer: the cap was reached" in texts(out)
101
+ assert "I\n" in texts(s.execute("%ski ``KI```SII``SII")) + "\n"
102
+ assert texts(s.execute("%ski ``KI```SII``SII --lazy")).startswith("I")
103
+
104
+
105
+ def test_commands_that_show_things():
106
+ s = Session()
107
+ assert "%schedule HOW" in texts(s.execute("%help"))
108
+ assert "agent con 2" in texts(s.execute("%table"))
109
+ assert "commute" in texts(s.execute("%rules"))
110
+ assert "0 problems" in texts(s.execute("%check"))
111
+ assert "One term, K I" in texts(s.execute("%demo"))