comparison TMDrawer.py @ 45:1804f09a7adb

Chapter 6, exercise 4, part 4. A Turing Machine drawer.
author Brian Neal <bgneal@gmail.com>
date Sat, 19 Jan 2013 14:17:12 -0600
parents
children
comparison
equal deleted inserted replaced
44:362d4ec7e794 45:1804f09a7adb
1 """Chapter 6, exercise 4 in Allen Downey's Think Complexity book.
2
3 The goal of this exercise is to implement a Turing machine.
4 See http://en.wikipedia.org/wiki/Turing_machine.
5
6 4. Write a class named TMDrawer that generates an image that represents the
7 state of the tape and the position and state of the head. For one example of
8 what that might look like, see
9 http://mathworld.wolfram.com/TuringMachine.html.
10
11 """
12 import matplotlib.pyplot as pyplot
13 import numpy
14
15 from CADrawer import Drawer
16
17
18 class TMDrawer(Drawer):
19 """Implementation of Drawer using matplotlib for Turing Machines.
20
21 We visualize the tape and machine head/state by drawing the tape state as
22 a row, then adding a row underneath that for the head & state. The tape head
23 is drawn as a solid square whose color represents the state.
24
25 """
26 def __init__(self, tape_colors, state_colors, cmap=None):
27 self.tape_colors = tape_colors
28 self.state_colors = state_colors
29 self.cmap = cmap if cmap else 'spectral'
30
31 def draw(self, tm, start=0, end=None):
32 """Draws the TM using pyplot.pcolor."""
33 tape = tm.get_array(start, end)
34 rows, cols = tape.shape
35
36 # create a new array that has twice as many rows
37 steps = rows
38 rows *= 2
39 a = numpy.zeros((rows, cols), dtype=numpy.int8)
40
41 # copy the tape state into the array at every other row
42 for i in xrange(steps):
43 for j in xrange(cols):
44 #a[n, j] = self.tape_colors[tape[i, j]]
45 c = self.tape_colors[tape[i, j]]
46 a[i * 2, j] = c
47
48 # copy the head position & state into every other row
49 n = 1
50 for pos, state in tm.history:
51 a[n, pos] = self.state_colors[state]
52 n += 2
53
54 # flipud puts the first row at the top;
55 pyplot.pcolor(numpy.flipud(a), cmap=self.cmap)
56 pyplot.axis([0, cols, 0, rows])
57 pyplot.colorbar()
58
59 # empty lists draw no ticks
60 pyplot.xticks([])
61 pyplot.yticks([])
62
63 def show(self):
64 """display the pseudocolor representation of the CA"""
65 pyplot.show()
66
67 def save(self, filename='tm.png'):
68 """save the pseudocolor representation of the TM in (filename)."""
69 pyplot.savefig(filename)
70