turing-sim 1.0.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.
turing/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """Single-tape Turing machine simulator."""
2
+
3
+ from .definition import BLANK_SYMBOL, Definition, Transition, read_definition
4
+ from .exceptions import (
5
+ ConfigurationError,
6
+ InputAlphabetError,
7
+ StepLimitExceededError,
8
+ TapeAlphabetError,
9
+ TuringMachineError,
10
+ UndefinedTransitionError,
11
+ )
12
+ from .state import State
13
+ from .transition_function import TransitionFunction
14
+ from .turing_machine import Snapshot, TuringMachine
15
+
16
+ __version__ = "1.0.0"
17
+
18
+ __all__ = [
19
+ "BLANK_SYMBOL",
20
+ "ConfigurationError",
21
+ "Definition",
22
+ "InputAlphabetError",
23
+ "Snapshot",
24
+ "State",
25
+ "StepLimitExceededError",
26
+ "TapeAlphabetError",
27
+ "Transition",
28
+ "TransitionFunction",
29
+ "TuringMachine",
30
+ "TuringMachineError",
31
+ "UndefinedTransitionError",
32
+ "read_definition",
33
+ ]
turing/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
turing/browser.py ADDED
@@ -0,0 +1,53 @@
1
+ """Entry point for the web demo, which runs the package on Pyodide."""
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from .definition import parse_yaml
7
+ from .exceptions import TuringMachineError
8
+ from .turing_machine import DEFAULT_MAX_STEPS, Snapshot, TuringMachine
9
+
10
+ MAX_BROWSER_STEPS = 5_000
11
+
12
+
13
+ def _snapshot_to_dict(snapshot: Snapshot) -> dict[str, Any]:
14
+ return {
15
+ "step": snapshot.step,
16
+ "state": snapshot.state,
17
+ "tape": list(snapshot.tape),
18
+ "head": snapshot.head,
19
+ "read": snapshot.read,
20
+ "written": snapshot.written,
21
+ "direction": snapshot.direction,
22
+ }
23
+
24
+
25
+ def simulate(definition: str, word: str, max_steps: int = DEFAULT_MAX_STEPS) -> str:
26
+ """Run a YAML machine on a word and return the run as JSON.
27
+
28
+ Steps computed before an error (e.g. the step limit) are still included.
29
+ """
30
+ response: dict[str, Any] = {
31
+ "name": "",
32
+ "description": "",
33
+ "deterministic": True,
34
+ "snapshots": [],
35
+ "result": None,
36
+ "accepted": False,
37
+ "error": None,
38
+ }
39
+ try:
40
+ machine = TuringMachine.from_definition(parse_yaml(definition))
41
+ response.update(
42
+ name=machine.name,
43
+ description=machine.description,
44
+ deterministic=machine.is_deterministic,
45
+ )
46
+ snapshots = response["snapshots"]
47
+ for snapshot in machine.steps(word, max_steps=min(max_steps, MAX_BROWSER_STEPS)):
48
+ snapshots.append(_snapshot_to_dict(snapshot))
49
+ response["result"] = machine.tape_to_str(snapshots[-1]["tape"])
50
+ response["accepted"] = True
51
+ except TuringMachineError as error:
52
+ response["error"] = str(error)
53
+ return json.dumps(response)
turing/cli.py ADDED
@@ -0,0 +1,70 @@
1
+ import argparse
2
+
3
+ from rich.console import Console
4
+
5
+ from . import __version__
6
+ from .exceptions import TuringMachineError
7
+ from .render import animate, print_trace
8
+ from .turing_machine import DEFAULT_MAX_STEPS, TuringMachine
9
+
10
+
11
+ def build_parser() -> argparse.ArgumentParser:
12
+ parser = argparse.ArgumentParser(
13
+ prog="turing", description="Run a Turing machine on an input word."
14
+ )
15
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
16
+ parser.add_argument("tape", type=str, help="input word written on the tape")
17
+ parser.add_argument(
18
+ "-c",
19
+ "--config",
20
+ type=str,
21
+ required=True,
22
+ help="machine definition file (.yaml, or legacy .txt format)",
23
+ )
24
+ parser.add_argument(
25
+ "-s",
26
+ "--max-steps",
27
+ type=int,
28
+ default=DEFAULT_MAX_STEPS,
29
+ help=f"maximum number of steps before giving up (default: {DEFAULT_MAX_STEPS})",
30
+ )
31
+ view = parser.add_mutually_exclusive_group()
32
+ view.add_argument(
33
+ "-t", "--trace", action="store_true", help="print every step of the run as a table"
34
+ )
35
+ view.add_argument(
36
+ "-a", "--animate", action="store_true", help="animate the run in the terminal"
37
+ )
38
+ parser.add_argument(
39
+ "-d",
40
+ "--delay",
41
+ type=float,
42
+ default=0.2,
43
+ help="pause between animation frames in seconds (default: 0.2)",
44
+ )
45
+ return parser
46
+
47
+
48
+ def main(argv: list[str] | None = None) -> int:
49
+ args = build_parser().parse_args(argv)
50
+ console = Console(highlight=False)
51
+ errors = Console(stderr=True, highlight=False)
52
+
53
+ try:
54
+ machine = TuringMachine.from_file(args.config)
55
+ if args.trace or args.animate:
56
+ snapshots = machine.steps(args.tape, max_steps=args.max_steps)
57
+ if args.trace:
58
+ last = print_trace(console, snapshots)
59
+ else:
60
+ last = animate(console, snapshots, args.delay)
61
+ result = machine.tape_to_str(list(last.tape))
62
+ console.print(f"\n[bold]Result:[/] {result} [dim]({last.step} steps)[/]")
63
+ if not machine.is_deterministic:
64
+ console.print("[dim]Nondeterministic machine: shortest accepting computation.[/]")
65
+ else:
66
+ print(machine.tape_to_str(machine.start(args.tape, max_steps=args.max_steps)))
67
+ except TuringMachineError as error:
68
+ errors.print(f"[bold red]Error:[/] {error}")
69
+ return 1
70
+ return 0
turing/definition.py ADDED
@@ -0,0 +1,188 @@
1
+ """Parsers for the YAML format and the old six-line text format."""
2
+
3
+ from collections.abc import Iterable
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any, NamedTuple
7
+
8
+ import yaml
9
+
10
+ from .exceptions import ConfigurationError
11
+
12
+ BLANK_SYMBOL = "X"
13
+
14
+ DIRECTIONS = ("-1", "0", "1")
15
+
16
+ DIRECTION_ALIASES = {"L": "-1", "S": "0", "R": "1", "-1": "-1", "0": "0", "1": "1"}
17
+
18
+ YAML_KEYS = {
19
+ "name",
20
+ "description",
21
+ "states",
22
+ "input_alphabet",
23
+ "tape_alphabet",
24
+ "initial_state",
25
+ "final_states",
26
+ "transitions",
27
+ }
28
+ REQUIRED_YAML_KEYS = {"input_alphabet", "initial_state", "final_states", "transitions"}
29
+
30
+
31
+ class Transition(NamedTuple):
32
+ state: str
33
+ read: str
34
+ next_state: str
35
+ write: str
36
+ direction: str
37
+
38
+
39
+ @dataclass
40
+ class Definition:
41
+ """Parsed but not yet validated machine description."""
42
+
43
+ states: list[str]
44
+ input_alphabet: list[str]
45
+ tape_alphabet: list[str]
46
+ initial_state: str
47
+ final_states: list[str]
48
+ transitions: list[Transition]
49
+ name: str = ""
50
+ description: str = ""
51
+
52
+
53
+ def read_definition(path: str | Path) -> Definition:
54
+ """Files ending in .yaml/.yml are YAML, anything else uses the old format."""
55
+ path = Path(path)
56
+ try:
57
+ text = path.read_text(encoding="utf-8")
58
+ except OSError as error:
59
+ raise ConfigurationError(f"Cannot read configuration file: {path}") from error
60
+ if path.suffix.lower() in (".yaml", ".yml"):
61
+ return parse_yaml(text)
62
+ return parse_legacy(text)
63
+
64
+
65
+ def _unique(items: Iterable[str]) -> list[str]:
66
+ return list(dict.fromkeys(items))
67
+
68
+
69
+ def _symbol(value: Any, where: str) -> str:
70
+ if isinstance(value, bool):
71
+ raise ConfigurationError(
72
+ f"{where}: {value!r} was read as a boolean, put it in quotes (e.g. 'yes')"
73
+ )
74
+ if isinstance(value, (list, dict)) or value is None or str(value) == "":
75
+ raise ConfigurationError(f"{where}: expected a single value, got {value!r}")
76
+ return str(value)
77
+
78
+
79
+ def _symbol_list(value: Any, where: str) -> list[str]:
80
+ if value is None:
81
+ return []
82
+ if not isinstance(value, list):
83
+ value = [value]
84
+ return [_symbol(item, where) for item in value]
85
+
86
+
87
+ def parse_yaml(text: str) -> Definition:
88
+ """See the README for the format. `states` and `tape_alphabet` are derived
89
+ from the transitions when they are not given.
90
+ """
91
+ try:
92
+ data = yaml.safe_load(text)
93
+ except yaml.YAMLError as error:
94
+ raise ConfigurationError(f"Invalid YAML: {error}") from None
95
+ if not isinstance(data, dict):
96
+ raise ConfigurationError("YAML definition must be a mapping")
97
+ unknown = sorted(set(map(str, data)) - YAML_KEYS)
98
+ if unknown:
99
+ raise ConfigurationError(f"Unknown keys in definition: {unknown}")
100
+ missing = sorted(REQUIRED_YAML_KEYS - set(data))
101
+ if missing:
102
+ raise ConfigurationError(f"Missing keys in definition: {missing}")
103
+
104
+ rules = data["transitions"]
105
+ if not isinstance(rules, dict):
106
+ raise ConfigurationError("'transitions' must map states to {symbol: rule}")
107
+ transitions = []
108
+ for raw_state, by_symbol in rules.items():
109
+ state = _symbol(raw_state, "transitions")
110
+ if not isinstance(by_symbol, dict):
111
+ raise ConfigurationError(f"Transitions of state {state} must map symbols to rules")
112
+ for raw_read, value in by_symbol.items():
113
+ read = _symbol(raw_read, f"transitions.{state}")
114
+ where = f"transitions.{state}.{read}"
115
+ rules = (
116
+ value
117
+ if isinstance(value, list) and value and isinstance(value[0], list)
118
+ else [value]
119
+ )
120
+ for rule in rules:
121
+ if not isinstance(rule, list) or len(rule) != 3:
122
+ raise ConfigurationError(
123
+ f"{where}: expected [next_state, write, direction] or a list of such rules"
124
+ )
125
+ next_state, write, raw_direction = (_symbol(item, where) for item in rule)
126
+ direction = DIRECTION_ALIASES.get(raw_direction.upper(), raw_direction)
127
+ transitions.append(Transition(state, read, next_state, write, direction))
128
+
129
+ initial_state = _symbol(data["initial_state"], "initial_state")
130
+ final_states = _symbol_list(data["final_states"], "final_states")
131
+ input_alphabet = _symbol_list(data["input_alphabet"], "input_alphabet")
132
+
133
+ if "states" in data:
134
+ states = _symbol_list(data["states"], "states")
135
+ else:
136
+ states = _unique(
137
+ [initial_state, *final_states]
138
+ + [s for t in transitions for s in (t.state, t.next_state)]
139
+ )
140
+ if "tape_alphabet" in data:
141
+ tape_alphabet = _symbol_list(data["tape_alphabet"], "tape_alphabet")
142
+ else:
143
+ tape_alphabet = _unique(
144
+ [*input_alphabet, BLANK_SYMBOL] + [s for t in transitions for s in (t.read, t.write)]
145
+ )
146
+
147
+ return Definition(
148
+ states=states,
149
+ input_alphabet=input_alphabet,
150
+ tape_alphabet=tape_alphabet,
151
+ initial_state=initial_state,
152
+ final_states=final_states,
153
+ transitions=transitions,
154
+ name=str(data.get("name") or ""),
155
+ description=str(data.get("description") or "").strip(),
156
+ )
157
+
158
+
159
+ def parse_legacy(text: str) -> Definition:
160
+ """Old format: six lines, items separated by ';', rules like ((q0,a)->(q1,b,1))."""
161
+ lines = [line.strip() for line in text.splitlines()]
162
+ if len(lines) < 6:
163
+ raise ConfigurationError(
164
+ "Configuration file must have 6 lines: states, input alphabet, "
165
+ "tape alphabet, initial state, final states, transitions"
166
+ )
167
+
168
+ def split(line: str) -> list[str]:
169
+ return [item.strip() for item in line.split(";") if item.strip()]
170
+
171
+ transitions = []
172
+ for rule in split(lines[5]):
173
+ try:
174
+ source, target = rule.translate(str.maketrans("", "", "()")).split("->")
175
+ state, read = (part.strip() for part in source.split(","))
176
+ next_state, write, direction = (part.strip() for part in target.split(","))
177
+ except ValueError:
178
+ raise ConfigurationError(f"Malformed transition: {rule!r}") from None
179
+ transitions.append(Transition(state, read, next_state, write, direction))
180
+
181
+ return Definition(
182
+ states=split(lines[0]),
183
+ input_alphabet=split(lines[1]),
184
+ tape_alphabet=split(lines[2]),
185
+ initial_state=lines[3],
186
+ final_states=split(lines[4]),
187
+ transitions=transitions,
188
+ )
turing/exceptions.py ADDED
@@ -0,0 +1,22 @@
1
+ class TuringMachineError(Exception):
2
+ """Base class of all errors raised by this package."""
3
+
4
+
5
+ class InputAlphabetError(TuringMachineError):
6
+ """The input word contains a symbol outside the input alphabet."""
7
+
8
+
9
+ class TapeAlphabetError(TuringMachineError):
10
+ """A transition writes a symbol outside the tape alphabet."""
11
+
12
+
13
+ class UndefinedTransitionError(TuringMachineError):
14
+ """No rule for the current state and symbol (or every branch got stuck)."""
15
+
16
+
17
+ class StepLimitExceededError(TuringMachineError):
18
+ """The machine did not halt within the step limit."""
19
+
20
+
21
+ class ConfigurationError(TuringMachineError):
22
+ """The machine definition is invalid."""
turing/py.typed ADDED
File without changes
turing/render.py ADDED
@@ -0,0 +1,92 @@
1
+ """Trace table and animation for the CLI (uses rich)."""
2
+
3
+ import time
4
+ from collections.abc import Iterable
5
+
6
+ from rich.console import Console, Group
7
+ from rich.live import Live
8
+ from rich.panel import Panel
9
+ from rich.table import Table
10
+ from rich.text import Text
11
+
12
+ from .definition import BLANK_SYMBOL
13
+ from .turing_machine import Snapshot
14
+
15
+ MOVES = {"-1": "L", "0": "S", "1": "R"}
16
+
17
+
18
+ def visible_cells(snapshot: Snapshot) -> tuple[list[str], int]:
19
+ """Tape cells padded so that the head is inside, and the head index."""
20
+ cells = list(snapshot.tape)
21
+ head = snapshot.head
22
+ if head < 0:
23
+ cells = [BLANK_SYMBOL] * -head + cells
24
+ head = 0
25
+ elif head >= len(cells):
26
+ cells += [BLANK_SYMBOL] * (head - len(cells) + 1)
27
+ return cells, head
28
+
29
+
30
+ def render_tape(snapshot: Snapshot) -> Text:
31
+ cells, head = visible_cells(snapshot)
32
+ text = Text()
33
+ for index, cell in enumerate(cells):
34
+ if index == head:
35
+ style = "bold black on bright_yellow"
36
+ elif cell == BLANK_SYMBOL:
37
+ style = "dim"
38
+ else:
39
+ style = "bold"
40
+ text.append(f"[{cell}]" if index == head else f" {cell} ", style=style)
41
+ return text
42
+
43
+
44
+ def render_transition(snapshot: Snapshot) -> Text:
45
+ """Last transition as read/written move, e.g. 1/0 L."""
46
+ if snapshot.read is None or snapshot.written is None or snapshot.direction is None:
47
+ return Text("start", style="dim")
48
+ return Text.assemble(
49
+ (snapshot.read, "cyan"),
50
+ ("/", "dim"),
51
+ (snapshot.written, "cyan"),
52
+ " ",
53
+ (MOVES[snapshot.direction], "magenta"),
54
+ )
55
+
56
+
57
+ def print_trace(console: Console, snapshots: Iterable[Snapshot]) -> Snapshot:
58
+ table = Table(box=None, header_style="bold", pad_edge=False)
59
+ table.add_column("step", justify="right", style="dim")
60
+ table.add_column("state", style="green")
61
+ table.add_column("transition")
62
+ table.add_column("tape", no_wrap=True)
63
+ last = None
64
+ try:
65
+ for last in snapshots:
66
+ table.add_row(str(last.step), last.state, render_transition(last), render_tape(last))
67
+ finally:
68
+ if table.row_count:
69
+ console.print(table)
70
+ assert last is not None
71
+ return last
72
+
73
+
74
+ def render_frame(snapshot: Snapshot) -> Panel:
75
+ header = Text.assemble(
76
+ ("step ", "dim"),
77
+ (f"{snapshot.step} ", "bold"),
78
+ ("state ", "dim"),
79
+ (f"{snapshot.state} ", "bold green"),
80
+ render_transition(snapshot),
81
+ )
82
+ return Panel(Group(header, Text(), render_tape(snapshot)), title="Turing machine", expand=False)
83
+
84
+
85
+ def animate(console: Console, snapshots: Iterable[Snapshot], delay: float) -> Snapshot:
86
+ last = None
87
+ with Live(console=console, auto_refresh=False, transient=False) as live:
88
+ for last in snapshots:
89
+ live.update(render_frame(last), refresh=True)
90
+ time.sleep(delay)
91
+ assert last is not None
92
+ return last
turing/state.py ADDED
@@ -0,0 +1,19 @@
1
+ from .exceptions import ConfigurationError
2
+ from .transition_function import TransitionFunction
3
+
4
+
5
+ class State:
6
+ def __init__(self, name: str) -> None:
7
+ self.name = name
8
+ self.transitions: dict[str, list[TransitionFunction]] = {}
9
+
10
+ def add_rule(self, symbol: str, rule: TransitionFunction) -> None:
11
+ """Several different rules for one symbol make the machine nondeterministic."""
12
+ rules = self.transitions.setdefault(symbol, [])
13
+ if any(existing.as_tuple() == rule.as_tuple() for existing in rules):
14
+ raise ConfigurationError(f"Duplicate transition for ({self.name}, {symbol})")
15
+ rules.append(rule)
16
+
17
+ @property
18
+ def is_deterministic(self) -> bool:
19
+ return all(len(rules) <= 1 for rules in self.transitions.values())
@@ -0,0 +1,8 @@
1
+ class TransitionFunction:
2
+ def __init__(self, next_state: str, write: str, direction: str) -> None:
3
+ self.next_state = next_state
4
+ self.write = write
5
+ self.direction = direction
6
+
7
+ def as_tuple(self) -> tuple[str, str, str]:
8
+ return self.next_state, self.write, self.direction
@@ -0,0 +1,272 @@
1
+ from collections import deque
2
+ from collections.abc import Iterable, Iterator
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ from .definition import BLANK_SYMBOL, DIRECTIONS, Definition, Transition, read_definition
7
+ from .exceptions import (
8
+ ConfigurationError,
9
+ InputAlphabetError,
10
+ StepLimitExceededError,
11
+ TapeAlphabetError,
12
+ UndefinedTransitionError,
13
+ )
14
+ from .state import State
15
+ from .transition_function import TransitionFunction
16
+
17
+ DEFAULT_MAX_STEPS = 10_000
18
+ DEFAULT_MAX_CONFIGURATIONS = 100_000
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Snapshot:
23
+ """Machine configuration after `step` transitions.
24
+
25
+ `tape` holds only the visited cells, so `head` can be -1 or len(tape) right
26
+ after the head moves onto a new blank cell. `read`, `written` and
27
+ `direction` describe the last transition and are None for step 0.
28
+ """
29
+
30
+ step: int
31
+ state: str
32
+ tape: tuple[str, ...]
33
+ head: int
34
+ read: str | None = None
35
+ written: str | None = None
36
+ direction: str | None = None
37
+
38
+
39
+ class TuringMachine:
40
+ def __init__(
41
+ self,
42
+ states: Iterable[str],
43
+ input_alphabet: list[str],
44
+ tape_alphabet: list[str],
45
+ initial_state: str,
46
+ final_states: list[str],
47
+ transitions: Iterable[Transition],
48
+ name: str = "",
49
+ description: str = "",
50
+ ) -> None:
51
+ """Raises ConfigurationError if the definition is inconsistent."""
52
+ self.states = {state: State(state) for state in states}
53
+ self.input_alphabet = input_alphabet
54
+ self.tape_alphabet = tape_alphabet
55
+ self.initial_state = initial_state
56
+ self.final_states = final_states
57
+ self.name = name
58
+ self.description = description
59
+ self._validate()
60
+ for transition in transitions:
61
+ self._add_transition(transition)
62
+
63
+ def _validate(self) -> None:
64
+ if not self.states:
65
+ raise ConfigurationError("No states defined")
66
+ if BLANK_SYMBOL not in self.tape_alphabet:
67
+ raise ConfigurationError(
68
+ f"Tape alphabet must contain the blank symbol '{BLANK_SYMBOL}'"
69
+ )
70
+ if BLANK_SYMBOL in self.input_alphabet:
71
+ raise ConfigurationError(
72
+ f"Input alphabet must not contain the blank symbol '{BLANK_SYMBOL}'"
73
+ )
74
+ missing = [c for c in self.input_alphabet if c not in self.tape_alphabet]
75
+ if missing:
76
+ raise ConfigurationError(f"Input symbols missing from the tape alphabet: {missing}")
77
+ if self.initial_state not in self.states:
78
+ raise ConfigurationError(f"Unknown initial state: {self.initial_state}")
79
+ unknown = [s for s in self.final_states if s not in self.states]
80
+ if unknown:
81
+ raise ConfigurationError(f"Unknown final states: {unknown}")
82
+
83
+ def _add_transition(self, transition: Transition) -> None:
84
+ state, read, next_state, write, direction = transition
85
+ if state not in self.states:
86
+ raise ConfigurationError(f"Unknown state in transition: {state}")
87
+ if next_state not in self.states:
88
+ raise ConfigurationError(f"Unknown state in transition: {next_state}")
89
+ if read not in self.tape_alphabet:
90
+ raise ConfigurationError(f"Transition reads a symbol outside the tape alphabet: {read}")
91
+ if direction not in DIRECTIONS:
92
+ raise ConfigurationError(
93
+ f"Invalid direction {direction!r}, expected one of {DIRECTIONS}"
94
+ )
95
+ self.states[state].add_rule(read, TransitionFunction(next_state, write, direction))
96
+
97
+ @classmethod
98
+ def from_definition(cls, definition: Definition) -> "TuringMachine":
99
+ return cls(
100
+ definition.states,
101
+ definition.input_alphabet,
102
+ definition.tape_alphabet,
103
+ definition.initial_state,
104
+ definition.final_states,
105
+ definition.transitions,
106
+ definition.name,
107
+ definition.description,
108
+ )
109
+
110
+ @classmethod
111
+ def from_file(cls, path: str | Path) -> "TuringMachine":
112
+ """Load a machine from a .yaml/.yml file or a file in the old text format."""
113
+ return cls.from_definition(read_definition(path))
114
+
115
+ @staticmethod
116
+ def tape_to_str(tape: list[str]) -> str:
117
+ return "".join(char for char in tape if char != BLANK_SYMBOL)
118
+
119
+ @property
120
+ def is_deterministic(self) -> bool:
121
+ return all(state.is_deterministic for state in self.states.values())
122
+
123
+ def steps(
124
+ self,
125
+ word: str,
126
+ initial_state: str | None = None,
127
+ max_steps: int = DEFAULT_MAX_STEPS,
128
+ ) -> Iterator[Snapshot]:
129
+ """Yield the configuration before the first step and after each step.
130
+
131
+ For a nondeterministic machine this is the path returned by search().
132
+ """
133
+ if not self.is_deterministic:
134
+ yield from self.search(word, initial_state, max_steps)
135
+ return
136
+
137
+ snapshot = self._initial_snapshot(word, initial_state)
138
+ yield snapshot
139
+ if snapshot.state in self.final_states:
140
+ return
141
+
142
+ for step in range(1, max_steps + 1):
143
+ tape, head = self._prepare_tape(snapshot)
144
+ rule = self.get_rule(tape[head], snapshot.state)
145
+ snapshot = self._apply(rule, snapshot.state, tape, head, step)
146
+ yield snapshot
147
+ if snapshot.state in self.final_states:
148
+ return
149
+ raise StepLimitExceededError(f"Machine did not halt within {max_steps} steps")
150
+
151
+ def search(
152
+ self,
153
+ word: str,
154
+ initial_state: str | None = None,
155
+ max_steps: int = DEFAULT_MAX_STEPS,
156
+ max_configurations: int = DEFAULT_MAX_CONFIGURATIONS,
157
+ ) -> list[Snapshot]:
158
+ """BFS over all branches; returns the shortest path to a final state.
159
+
160
+ Raises UndefinedTransitionError when every branch gets stuck and
161
+ StepLimitExceededError when one of the limits is hit first.
162
+ """
163
+ start = self._initial_snapshot(word, initial_state)
164
+ if start.state in self.final_states:
165
+ return [start]
166
+
167
+ parents: dict[tuple[str, tuple[str, ...], int], Snapshot | None] = {_key(start): None}
168
+ frontier = [start]
169
+ for step in range(1, max_steps + 1):
170
+ next_frontier = []
171
+ for snapshot in frontier:
172
+ tape, head = self._prepare_tape(snapshot)
173
+ for rule in self.get_rules(tape[head], snapshot.state):
174
+ child = self._apply(rule, snapshot.state, list(tape), head, step)
175
+ if _key(child) in parents:
176
+ continue
177
+ parents[_key(child)] = snapshot
178
+ if child.state in self.final_states:
179
+ return _path(child, parents)
180
+ if len(parents) > max_configurations:
181
+ raise StepLimitExceededError(
182
+ f"Explored more than {max_configurations} configurations "
183
+ "without reaching a final state"
184
+ )
185
+ next_frontier.append(child)
186
+ if not next_frontier:
187
+ raise UndefinedTransitionError(
188
+ "No computation branch reached a final state (input rejected)"
189
+ )
190
+ frontier = next_frontier
191
+ raise StepLimitExceededError(f"No branch reached a final state within {max_steps} steps")
192
+
193
+ def _initial_snapshot(self, word: str, initial_state: str | None) -> Snapshot:
194
+ self.check_input(word)
195
+ state = initial_state if initial_state is not None else self.initial_state
196
+ return Snapshot(0, state, tuple(word), 0)
197
+
198
+ def _prepare_tape(self, snapshot: Snapshot) -> tuple[list[str], int]:
199
+ tape = list(snapshot.tape)
200
+ self.pad_right(tape, snapshot.head)
201
+ head = self.pad_left(tape, snapshot.head)
202
+ return tape, head
203
+
204
+ def _apply(
205
+ self, rule: TransitionFunction, state: str, tape: list[str], head: int, step: int
206
+ ) -> Snapshot:
207
+ read = tape[head]
208
+ if rule.write not in self.tape_alphabet:
209
+ raise TapeAlphabetError(f"Cannot write symbol outside tape alphabet: {rule.write!r}")
210
+ tape[head] = rule.write
211
+ if rule.next_state not in self.final_states:
212
+ head += int(rule.direction)
213
+ return Snapshot(step, rule.next_state, tuple(tape), head, read, rule.write, rule.direction)
214
+
215
+ def start(
216
+ self,
217
+ word: str,
218
+ initial_state: str | None = None,
219
+ max_steps: int = DEFAULT_MAX_STEPS,
220
+ ) -> list[str]:
221
+ """Run until the machine halts and return the final tape."""
222
+ last = deque(self.steps(word, initial_state, max_steps), maxlen=1)[0]
223
+ return list(last.tape)
224
+
225
+ @staticmethod
226
+ def pad_right(tape: list[str], i: int) -> None:
227
+ if i == len(tape):
228
+ tape.append(BLANK_SYMBOL)
229
+ if i > len(tape):
230
+ raise IndexError("Head position is outside the tape")
231
+
232
+ @staticmethod
233
+ def pad_left(tape: list[str], i: int) -> int:
234
+ if i == -1:
235
+ tape.insert(0, BLANK_SYMBOL)
236
+ return 0
237
+ return i
238
+
239
+ def check_input(self, word: str) -> None:
240
+ for char in word:
241
+ if char not in self.input_alphabet:
242
+ raise InputAlphabetError(f"Input symbol outside the input alphabet: {char!r}")
243
+
244
+ def get_rule(self, symbol: str, state: str) -> TransitionFunction:
245
+ rules = self.get_rules(symbol, state)
246
+ if not rules:
247
+ raise UndefinedTransitionError(f"No transition defined for ({state}, {symbol})")
248
+ if len(rules) > 1:
249
+ raise UndefinedTransitionError(
250
+ f"Several transitions defined for ({state}, {symbol}); "
251
+ "use search() for nondeterministic machines"
252
+ )
253
+ return rules[0]
254
+
255
+ def get_rules(self, symbol: str, state: str) -> list[TransitionFunction]:
256
+ found = self.states.get(state)
257
+ return found.transitions.get(symbol, []) if found else []
258
+
259
+
260
+ def _key(snapshot: Snapshot) -> tuple[str, tuple[str, ...], int]:
261
+ return snapshot.state, snapshot.tape, snapshot.head
262
+
263
+
264
+ def _path(
265
+ last: Snapshot, parents: dict[tuple[str, tuple[str, ...], int], Snapshot | None]
266
+ ) -> list[Snapshot]:
267
+ path = [last]
268
+ parent = parents[_key(last)]
269
+ while parent is not None:
270
+ path.append(parent)
271
+ parent = parents[_key(parent)]
272
+ return path[::-1]
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: turing-sim
3
+ Version: 1.0.0
4
+ Summary: Turing machine simulator with step-by-step tracing, YAML definitions and nondeterminism
5
+ Author: Franciszek Wozniak
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://gitlab.com/lorax0/turingmachine
8
+ Project-URL: Source, https://gitlab.com/lorax0/turingmachine
9
+ Project-URL: Issues, https://gitlab.com/lorax0/turingmachine/-/issues
10
+ Project-URL: Documentation, https://lorax0.gitlab.io/turingmachine/api/
11
+ Project-URL: Changelog, https://gitlab.com/lorax0/turingmachine/-/blob/main/CHANGELOG.md
12
+ Keywords: turing-machine,automata,simulator,computability
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Education
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3.15
25
+ Classifier: Operating System :: OS Independent
26
+ Classifier: Topic :: Education
27
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.10
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Requires-Dist: pyyaml>=6
33
+ Requires-Dist: rich>=13
34
+ Provides-Extra: dev
35
+ Requires-Dist: build; extra == "dev"
36
+ Requires-Dist: mypy; extra == "dev"
37
+ Requires-Dist: types-PyYAML; extra == "dev"
38
+ Requires-Dist: pytest; extra == "dev"
39
+ Requires-Dist: pytest-cov; extra == "dev"
40
+ Requires-Dist: ruff; extra == "dev"
41
+ Requires-Dist: pdoc; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # Turing Machine Simulator
45
+
46
+ [![pipeline](https://gitlab.com/lorax0/turingmachine/badges/main/pipeline.svg)](https://gitlab.com/lorax0/turingmachine/-/pipelines)
47
+ [![coverage](https://gitlab.com/lorax0/turingmachine/badges/main/coverage.svg)](https://gitlab.com/lorax0/turingmachine/-/pipelines)
48
+ ![python](https://img.shields.io/badge/python-3.10%E2%80%933.15-blue)
49
+ [![license](https://img.shields.io/badge/license-MIT-green)](https://gitlab.com/lorax0/turingmachine/-/blob/main/LICENSE)
50
+
51
+ Single-tape Turing machine simulator. Machines are written in YAML and can be run from the
52
+ command line, step by step, or in the browser. Nondeterministic machines are supported too.
53
+
54
+ It started as a university assignment and was later rewritten as a standalone project.
55
+
56
+ **Web demo:** https://lorax0.gitlab.io/turingmachine/
57
+
58
+ ![Animation of the binary addition machine](https://gitlab.com/lorax0/turingmachine/-/raw/main/assets/demo.gif)
59
+
60
+ ## Installation
61
+
62
+ ```bash
63
+ pip install git+https://gitlab.com/lorax0/turingmachine.git
64
+ ```
65
+
66
+ Python 3.10 or newer.
67
+
68
+ ## Usage
69
+
70
+ ```console
71
+ $ turing -c examples/binary_addition.yaml 101+11
72
+ 1000
73
+
74
+ $ turing -c examples/binary_palindrome.yaml 10101
75
+ 1
76
+
77
+ $ turing -c examples/anbn.yaml --trace aabb
78
+ $ turing -c examples/busy_beaver_3.yaml --animate ""
79
+ ```
80
+
81
+ | Option | Description |
82
+ |-------------------|------------------------------------------------|
83
+ | `tape` | input word (`""` for an empty tape) |
84
+ | `-c, --config` | machine definition file |
85
+ | `-t, --trace` | print every step as a table |
86
+ | `-a, --animate` | animate the run |
87
+ | `-d, --delay` | delay between animation frames (default 0.2 s) |
88
+ | `-s, --max-steps` | step limit (default 10000) |
89
+
90
+ On error the message goes to stderr and the exit code is 1.
91
+
92
+ ![Trace of the binary increment machine](https://gitlab.com/lorax0/turingmachine/-/raw/main/assets/trace.svg)
93
+
94
+ ## Machine format
95
+
96
+ ```yaml
97
+ name: Binary increment
98
+ description: Adds 1 to a binary number.
99
+
100
+ input_alphabet: [0, 1]
101
+ initial_state: q0
102
+ final_states: [qf]
103
+
104
+ transitions:
105
+ q0: # go to the end of the number
106
+ 0: [q0, 0, R]
107
+ 1: [q0, 1, R]
108
+ X: [q1, X, L]
109
+ q1: # add 1 and carry to the left
110
+ 0: [qf, 1, S]
111
+ 1: [q1, 0, L]
112
+ X: [qf, 1, S]
113
+ ```
114
+
115
+ Each rule is `symbol: [next_state, write, direction]`, where direction is `L`, `R` or `S`
116
+ (stay). `X` is the blank symbol and the tape is unbounded in both directions.
117
+
118
+ - The machine halts when it enters a final state. A missing rule is an error.
119
+ - `states` and `tape_alphabet` can be omitted; they are taken from the transitions.
120
+ - Unknown keys are rejected, so a typo like `final_state` is reported.
121
+ - A symbol with several rules makes the machine nondeterministic, e.g.
122
+ `a: [[guess, a, R], [upper, A, R]]`. The input is accepted if any branch reaches a final state.
123
+ The simulator does a breadth-first search and shows the shortest accepting run.
124
+
125
+ The old text format from the original assignment (six lines, rules like `((q0,0)->(q0,0,1))`)
126
+ still works for files not ending in `.yaml`.
127
+
128
+ ## Examples
129
+
130
+ | File | Input | Output | |
131
+ |--------------------------|----------|--------------------|-------------------------------------|
132
+ | `binary_increment.yaml` | `1011` | `1100` | add 1 |
133
+ | `binary_negation.yaml` | `1011` | `0100` | flip bits |
134
+ | `binary_addition.yaml` | `101+11` | `1000` | add two numbers |
135
+ | `unary_doubling.yaml` | `aaa` | `aaaaaa` | aⁿ -> a²ⁿ |
136
+ | `binary_palindrome.yaml` | `10101` | `1` / `0` | palindrome check |
137
+ | `anbn.yaml` | `aabb` | `1` / `0` | aⁿbⁿ check |
138
+ | `repeated_word.yaml` | `abab` | `1` / rejected | ww check, nondeterministic |
139
+ | `busy_beaver_3.yaml` | empty | `111111` | 3-state busy beaver |
140
+ | `infinite_loop.yaml` | `1` | step limit error | never halts |
141
+
142
+ Each example is tested against a plain Python implementation on all short inputs
143
+ (`tests/test_examples.py`).
144
+
145
+ ## Web demo
146
+
147
+ The demo page loads the package with [Pyodide](https://pyodide.org) and runs it in the browser,
148
+ so there is no backend and the simulator is not duplicated in JavaScript. You can edit the YAML,
149
+ run it and step through the result.
150
+
151
+ [![Web demo](https://gitlab.com/lorax0/turingmachine/-/raw/main/assets/web-demo.png)](https://lorax0.gitlab.io/turingmachine/)
152
+
153
+ ## Python API
154
+
155
+ ```python
156
+ from turing import TuringMachine
157
+
158
+ machine = TuringMachine.from_file("examples/binary_addition.yaml")
159
+ print(machine.tape_to_str(machine.start("101+11"))) # 1000
160
+
161
+ for snapshot in machine.steps("1+1"):
162
+ print(snapshot.step, snapshot.state, "".join(snapshot.tape), snapshot.head)
163
+
164
+ ww = TuringMachine.from_file("examples/repeated_word.yaml")
165
+ path = ww.search("abab") # shortest accepting run
166
+ ```
167
+
168
+ Errors inherit from `turing.TuringMachineError`.
169
+
170
+ ## Development
171
+
172
+ ```bash
173
+ pip install -e ".[dev]"
174
+ pytest --cov
175
+ mypy
176
+ ruff check . && ruff format .
177
+ ```
178
+
179
+ `python scripts/build_site.py` builds the web demo into `public/`
180
+ (`python -m http.server -d public` to try it locally). `python scripts/screenshot.py` and
181
+ `python scripts/demo_gif.py` regenerate the images in `assets/` (the GIF needs ImageMagick).
182
+
183
+ GitLab CI runs the linters and tests (Python 3.10 to 3.15), builds the package, deploys the
184
+ demo and the [API docs](https://lorax0.gitlab.io/turingmachine/api/) to Pages, and publishes to
185
+ PyPI (manual job on version tags). See [CONTRIBUTING.md](CONTRIBUTING.md).
186
+
187
+ ## License
188
+
189
+ [MIT](https://gitlab.com/lorax0/turingmachine/-/blob/main/LICENSE)
@@ -0,0 +1,17 @@
1
+ turing/__init__.py,sha256=Xbs2PtaqMmdMO5cFEo9TmwV7Wdi2X3hXcVe7MYNisgw,791
2
+ turing/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83
3
+ turing/browser.py,sha256=f9dUf18lWzfM8LrR6CvDQcjvbpE5JqGRz3oFEFw9K3U,1713
4
+ turing/cli.py,sha256=tkqSaJFQ8WnOj5Zrmjy5gnPinhOPGZnkIrwByccXRSM,2473
5
+ turing/definition.py,sha256=PNBij0DaE1zC0uSJeM6mPNGzRE8o-kAb0oMGWgrrXfY,6520
6
+ turing/exceptions.py,sha256=1iVvhNGqLH2bSsA0PSGZCnvLMjCYagnmdJHdLV5UzxE,665
7
+ turing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ turing/render.py,sha256=58mgtHAO6q8_qvzB-Bhe6X0Kk4MPGM_73Aq0hvZsMuY,2923
9
+ turing/state.py,sha256=V2jVIt4dY5_O9gefkEPCOgfpNBRATbiDo4Cw7niYtpo,786
10
+ turing/transition_function.py,sha256=MJpahsjXGRSUAvkn3hVrwEe6U4jv4d8QRd7yenZj2KI,310
11
+ turing/turing_machine.py,sha256=GmEFHEDlI6taspRT1c5qcxqQWNvV9yhDbnf0Xeey3Rg,10475
12
+ turing_sim-1.0.0.dist-info/licenses/LICENSE,sha256=LNYJEdwWNcxf6Eb11TmrxJl42nSm2ncmOk4MawvTBn8,1075
13
+ turing_sim-1.0.0.dist-info/METADATA,sha256=VncbBYhmCR4sSA05pb-zH0wkpvENHT4QtMgeX9hUmRc,7768
14
+ turing_sim-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ turing_sim-1.0.0.dist-info/entry_points.txt,sha256=htjxGp3-TtBqbGDx1Li9PcoQn682mQQ8JVyr43LfHrM,43
16
+ turing_sim-1.0.0.dist-info/top_level.txt,sha256=6nJNvBCS_BjyWV437qab8ZxoxuWfQUy8R9ahJSVpeeE,7
17
+ turing_sim-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ turing = turing.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Franciszek Wozniak
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
+ turing