In [50]:
%pylab inline
from collections import namedtuple
import scipy.misc
import os
import pydot
import re


Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
For more information, type 'help(pylab)'.

In [51]:
def find_between(s, pre, post=''):
    result = re.search(pre+'(.*)'+post, s)
    return result.group(1)

In [43]:
State = namedtuple('State', 'action DD CD DC CC')

In [22]:
TFT = [State('C', 1, 1, 0, 0), State('D', 1, 1, 0, 0)]

In [66]:
def parse_string_to_automata(string):
    list_of_states = []
    no_rubish = find_between(string, '\[', '\]')
    for i in no_rubish.split(','):
        state_strings = find_between(i, '/').split(' ')
        list_of_states.append(State(i.strip()[0], int(state_strings[0]), int(state_strings[1]), int(state_strings[2]), int(state_strings[3])))
    return list_of_states

In [67]:
parse_string_to_automata('[D/0 0 0 1, C/1 0 1 1]')


Out[67]:
[State(action='D', DD=0, CD=0, DC=0, CC=1),
 State(action='C', DD=1, CD=0, DC=1, CC=1)]

In [90]:
def paint_automata(list_of_states, title='', size=5):
    graph = pydot.Dot(graph_type='digraph')
    list_of_nodes = []
    #ad nodes
    for i, state in enumerate(list_of_states):
        if state.action == 'C':
            color = 'blue'
        if state.action == 'D':
            color = 'red'
        list_of_nodes.append(pydot.Node(str(i), style="filled", fillcolor=color))
    for i in list_of_nodes:
        graph.add_node(i)
    #add transitions
    for i, state in enumerate(list_of_states):
        graph.add_edge(pydot.Edge(i, state.DD, fontsize="10.0", label='DD'))
        graph.add_edge(pydot.Edge(i, state.DC, fontsize="10.0", label='DC'))
        graph.add_edge(pydot.Edge(i, state.CD, fontsize="10.0", label='CD'))
        graph.add_edge(pydot.Edge(i, state.CC, fontsize="10.0", label='CC'))
    graph.write_png('ex.png')
    plt.figure(figsize=(size, size))
    plt.xticks([],[])
    plt.yticks([],[])
    plt.imshow(scipy.misc.imread('ex.png'))
    plt.title(title)
    os.remove('ex.png')

In [91]:
def paint_from_string(string, size = 5, title = ''):
    
    paint_automata(parse_string_to_automata(string), title=string, size=size)

In [92]:
paint_from_string('[D/1 0 1 1, C/1 0 0 1]')



In [97]:
paint_from_string('[D/2 2 2 2, D/2 0 0 1, C/1 0 0 2]', size=8)



In [96]:
paint_from_string('[D/1 2 0 1, D/3 1 1 3, D/2 1 2 1, C/1 0 1 3]', size=10)



In [100]:
paint_from_string('[C/0 0 2 1, D/0 1 2 0, D/1 2 2 0]', size=10)



In [102]:
paint_from_string('[D/0 0 0 1, C/1 0 0 0]', size=7)



In [104]:
paint_from_string('[C/1 0 1 0, C/2 0 2 0, D/2 2 2 2]', size=10)



In [107]:
paint_from_string('[C/1 0 1 0, D/0 0 0 0]', size=10)



In [109]:
paint_from_string('[D/0 0 0 1, C/0 1 0 1]')



In [ ]: