-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbusybeaver.py
266 lines (215 loc) · 7.81 KB
/
busybeaver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
Calculates the Busy Beaver Sigma function, naively.
"""
import collections
import itertools
import sys
def log(string, stream=sys.stdout):
stream.write(string)
stream.flush()
def zero():
# Used for pickling
return 0
class Tape(object):
def __init__(self, position=0, default_factory=zero):
self.data = collections.defaultdict(default_factory)
self._position = position
self.leftmost = min(0, position)
self.rightmost = max(0, position)
self.shifts = 0
def __eq__(self, other):
return (self._position == other._position
and self.leftmost == other.leftmost
and self.rightmost == other.rightmost
and self.shifts == other.shifts
and self.data.items() == other.data.items())
@property
def position(self):
return self._position
@position.setter
def position(self, value):
self.shifts += abs(self._position - value)
self._position = value
self._update_extremes()
def _update_extremes(self):
self.leftmost = min(self.leftmost, self.position)
self.rightmost = max(self.rightmost, self.position)
def read(self):
return self.data[self.position]
def write(self, value):
self.data[self.position] = value
def left(self):
self.position -= 1
def right(self):
self.position += 1
def values(self):
for key in sorted(self.data.keys()):
yield self.data[key]
def __str__(self):
separator = " "
s = ""
for index in range(self.leftmost, self.rightmost+1):
s += "%s%s" % (self.data[index], separator)
return s[:-1]
def __repr__(self):
items = 3
extract = [v for n,v in enumerate(self.values()) if n<items]
extra = ""
if len(self.data) > items:
extra = "... %d more" % len(self.data)-items
return "<Tape: position=%d%s%s%s%s>" % (self.position,
" values=[" if len(extract)>0 else "",
", ".join(map(repr, extract)), extra,
"]" if len(extract)>0 else "")
class TuringMachine(object):
def __init__(self, state=0, transition=None):
"""A Universal Turing machine.
Args:
transition: A dictionary of transitions between states. It should
be a dictionary with (current state, symbol read) keys
and (symbol to write, move left (-1) or right (1),
next state) values.
"""
self.state = state
self.tape = Tape()
self.transition = transition
def __eq__(self, other):
return (self.state == other.state
and self.tape == other.tape
and self.transition == other.transition)
def __repr__(self):
return "<TuringMachine: state=%s tape=%s>" % (
self.state, repr(self.tape))
def __str__(self):
return "%s %s" % (self.state, str(self.tape))
def step(self):
"""Perform one computation step."""
# Read symbol at current tape position
symbol = self.tape.read()
# Look up action based on the current state and the read symbol
symbol, move, state = self.transition[(self.state, symbol)]
# Perform these actions
self.tape.write(symbol)
self.tape.position += move
self.state = state
def run(self, steps=None):
"""Runs the machine an unlimited or given number of steps.
Args:
steps: If None, run indefinitely. If a positive number, run for
that number of steps.
Raises:
KeyError: The given state was not found. Effectively means to halt.
"""
if steps is None:
while True:
self.step()
else:
for n in range(steps):
self.step()
class BusyBeaver(TuringMachine):
def __init__(self, transition):
super(BusyBeaver, self).__init__(transition=transition)
def ones(self):
"""Returns number of ones in the tape."""
return sum(self.tape.values())
def show(machine):
log("\n")
log(" ones: %d\n" % machine.ones())
log(" steps: %d\n" % machine.tape.shifts)
log(" tape: %s\n" % machine.tape)
format_state = lambda s: chr(ord("A") + s)
format_move = lambda n: "L" if n==-1 else "R"
format_next = lambda n: format_state(n) if n!="Z" else n
def fmt(n,w,m):
return "%s%s%s" % (format_next(n), w, format_move(m))
it = iter(sorted(machine.transition.items()))
try:
while True:
(state, symbol), (write, move, next) = it.next()
a = fmt(next, write, move)
(state2, symbol), (write, move, next) = it.next()
assert state==state2, "Not a binary Busy Beaver?"
b = fmt(next, write, move)
log(" %s: %s %s\n" % (format_state(state), a, b))
except StopIteration:
pass
def binary_machines(n):
"""The number of possible n-state, binary Turing machines."""
return (4*(n+1))**(2*n)
def enum_instructions(states):
"""Yields all possible transitions for an n-state machine."""
for symbol in [0, 1]:
for move in [-1, 1]:
for state in ["Z"] + list(range(states)):
yield (symbol, move, state)
def enum_transitions(states):
"""Generate all possible transition functions."""
for i in itertools.product(enum_instructions(states), repeat=states*2):
trans = {}
n=0
if len(i)>states:
for state in range(states):
for symbol in [0, 1]:
trans[(state, symbol)] = i[n]
n += 1
yield trans
def plot_bbs(states=2, maxsteps=108):
import matplotlib.pyplot as plt
class Data(object):
def __init__(self, width):
self.data = []
self.line = []
self.width = width
def add(self, result):
if len(self.line) < self.width:
self.line.append(result)
else:
self.data.append(self.line)
self.line = []
def finish(self):
self.data.append(self.line)
self.line = []
data = Data()
for num, tran in enumerate(enum_transitions(states), 1):
candidate = BusyBeaver(transition=tran)
log("\r%d / %d" % (num, binary_machines(states)))
try:
candidate.run(maxsteps)
# Did not halt
data.add(0)
except KeyError:
# By definition, halts
data.add(candidate.tape.shifts)
log("\n")
data.finish()
fig, ax = plt.subplots()
im = ax.imshow(data.data, interpolation="none")
plt.show()
def sigma(states, verbose=True):
champion = BusyBeaver({})
champion_ones = champion.ones()
count = binary_machines(states)
for num, tran in enumerate(enum_transitions(states), 1):
candidate = BusyBeaver(transition=tran)
try:
if verbose and (num % 1111) == 0:
log("%.2f%% %d / %d\r" % (100.0*num/count, num, count))
candidate.run(107+1) # cheating: op>S(3) => op = 1+S(3)
# above S from http://www.drb.insel.de/~heiner/BB/
continue # Did not halt
except KeyError:
# By definition, halts
pass
if candidate.ones() > champion_ones:
champion = candidate
champion_ones = champion.ones()
if verbose:
log("%.2f%% %d / %d\r" % (100.0*num/count, num, count))
show(champion)
if verbose:
log("%d-state machines enumerated: %d of %d\n" % (states, num, count))
return champion_ones
if __name__ == "__main__":
#plotsigma()
for n in range(0,5):
log("Sigma(%d) = %s\n" % (n, str(sigma(n))))