inets-kernel 0.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.
- inets_kernel/__init__.py +6 -0
- inets_kernel/__main__.py +5 -0
- inets_kernel/install.py +46 -0
- inets_kernel/kernel.py +44 -0
- inets_kernel/kernelspec/kernel.json +6 -0
- inets_kernel/session.py +316 -0
- inets_kernel-0.1.0.dist-info/METADATA +101 -0
- inets_kernel-0.1.0.dist-info/RECORD +11 -0
- inets_kernel-0.1.0.dist-info/WHEEL +5 -0
- inets_kernel-0.1.0.dist-info/licenses/LICENSE +21 -0
- inets_kernel-0.1.0.dist-info/top_level.txt +1 -0
inets_kernel/__init__.py
ADDED
|
@@ -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"
|
inets_kernel/__main__.py
ADDED
inets_kernel/install.py
ADDED
|
@@ -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()
|
inets_kernel/kernel.py
ADDED
|
@@ -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"}
|
inets_kernel/session.py
ADDED
|
@@ -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,11 @@
|
|
|
1
|
+
inets_kernel/__init__.py,sha256=8-diivWkLKHlWsl3WKTAMn5dbtp1CNyZzXt3tmEXjXo,265
|
|
2
|
+
inets_kernel/__main__.py,sha256=vF2KG8xFgAkOPhOwJMNjhARiV5uS_NHLADYwWNT6pKc,132
|
|
3
|
+
inets_kernel/install.py,sha256=9DsehVHwYgdr02EBovH8k0b0wV7FgePpGEyFv7i3VBE,1983
|
|
4
|
+
inets_kernel/kernel.py,sha256=c3rGNuiWd_8BvR3qvaQphJqvIuut6aM440dEXUsJ_1E,2011
|
|
5
|
+
inets_kernel/session.py,sha256=dA5FQjBn5nFHYpm-fkYd_hUHfNckMqFt3VPVI8LZj00,13871
|
|
6
|
+
inets_kernel/kernelspec/kernel.json,sha256=p7HJ0zhrqVe53S-yj82H-u-6WJfyuGYcPnDWi7oqub0,165
|
|
7
|
+
inets_kernel-0.1.0.dist-info/licenses/LICENSE,sha256=Vzy7mnHAKp6AW0KTFgOB2IYUV9VQINIKXK4Pcjoj6fo,1068
|
|
8
|
+
inets_kernel-0.1.0.dist-info/METADATA,sha256=M91rQrH2Y-qSy7n32qabTIID_ge8sC5IXxclAbt8BbE,3452
|
|
9
|
+
inets_kernel-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
inets_kernel-0.1.0.dist-info/top_level.txt,sha256=V0aPtMce-w1tcX3qCdTGO88L0EAAM43PzEsGr6J3oCM,13
|
|
11
|
+
inets_kernel-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
inets_kernel
|