def test_one_rule_no_tape(self):
     tm = TuringMachine("q4 -> q3")
     assert tm.mconf == "q4" # Default starting state is the first m-conf
     tm.move()
     assert tm.mconf == "q3"
     with raises(TMLocked):
         tm.move()
Exemple #2
0
 def test_two_rules_no_tape(self):
     tm = TuringMachine("a -> b\nb None -> R c\n")
     assert tm.mconf == "a"
     tm.move()
     assert tm.mconf == "b"
     assert tm.scan() == "None"
     tm.move()
     assert tm.mconf == "c"
     with raises(TMLocked):
         tm.move()
 def test_zero_one_zero_one(self):
     tm = TuringMachine(
         "a -> P0 R b\n"
         "b -> P1 R a\n"
     )
     for unused in range(40):
         assert tm.mconf == "a"
         tm.move()
         assert tm.mconf == "b"
         tm.move()
     tape = tm.tape
     assert len(tape) == 80
     for idx in range(80):
         assert tape[idx] == str(idx % 2)
 def test_two_rules_no_tape(self):
     tm = TuringMachine("a -> b\nb None -> R c\n")
     assert tm.mconf == "a"
     tm.move()
     assert tm.mconf == "b"
     assert tm.scan() == "None"
     tm.move()
     assert tm.mconf == "c"
     with raises(TMLocked):
         tm.move()
Exemple #5
0
 def test_one_rule_no_tape(self):
     tm = TuringMachine("q4 -> q3")
     assert tm.mconf == "q4"  # Default starting state is the first m-conf
     tm.move()
     assert tm.mconf == "q3"
     with raises(TMLocked):
         tm.move()
Exemple #6
0
 def test_zero_one_zero_one(self):
     tm = TuringMachine("a -> P0 R b\n" "b -> P1 R a\n")
     for unused in range(40):
         assert tm.mconf == "a"
         tm.move()
         assert tm.mconf == "b"
         tm.move()
     tape = tm.tape
     assert len(tape) == 80
     for idx in range(80):
         assert tape[idx] == str(idx % 2)
Exemple #7
0
from transitions import Transition
from transitions import Direction
from turing import TuringMachine

t0 = Transition("0", ("0", "0", "0"), "2", ("1", "4", "7"), [Direction.RIGHT, Direction.RIGHT, Direction.RIGHT])
t2 = Transition("2", ("0", "0", "0"), "3", ("2", "5", "8"), [Direction.RIGHT, Direction.RIGHT, Direction.RIGHT])
t3 = Transition("3", ("0", "0", "0"), "4", ("3", "6", "9"), [Direction.RIGHT, Direction.RIGHT, Direction.RIGHT])
t4 = Transition("4", ("2", "5", "8"), "4", ("3", "6", "9"), [Direction.RIGHT, Direction.RIGHT, Direction.RIGHT])

t0.toggle_start()
t4.toggle_accept()

states = ["0", "2", "3", "4"]
transitions = [t0, t2, t3, t4]
initial_state = "0"
accept_state = "4"
reject_state = None
initial_tape = [['0','0','0'], ['0','0','0'], ['0','0','0']]

tm = TuringMachine(states, transitions, initial_state, accept_state, reject_state, initial_tape)

print("Tansitions....")
tm.print_transitions()
print("Initial tapes...")
tm.print_tapes()
tm.execute()
print("Final tapes...")
tm.print_tapes()
Exemple #8
0
    while input_machine_string != '1' or flag_first_iteration:
        flag_first_iteration = False
        tape_for_check_even = input_machine_string + '_'
        initial_state_for_check_even = 'q0'
        final_states_for_check_even = {'q2'}

        transition_function_for_check_even = {
            ('q0', '1'): ('q1', '_', 'R'),
            ('q1', '1'): ('q0', '_', 'R'),
            ('q1', '_'): ('q3', '_', 'R'),
            ('q0', '_'): ('q2', '_', 'R'),
        }
        # ---------------------------------

        check_even_turing_machine = TuringMachine(
            tape_for_check_even, initial_state_for_check_even,
            final_states_for_check_even, transition_function_for_check_even)
        even_flag = True
        while not check_even_turing_machine.final():
            if time.time() - check_even_turing_machine.time > 0.1:
                even_flag = False
                break
            check_even_turing_machine.step()
        if even_flag:
            tape_for_divide = input_machine_string + '_'
            initial_state_for_divide = 'q0'
            final_states_for_divide = {'q4'}

            transition_function_for_divide = {
                ('q0', '1'): ('q1', 'y', 'R'),
                ('q1', '1'): ('q1', '1', 'R'),
Exemple #9
0
#!/usr/bin/python

from parser import rules
from turing import TuringMachine, Tape, Program
from customErrors import NotValidTokenException, UnreacheableTransitionException

print("Welcome to this Turing machine little project\n")
print(rules["DESCRIPTION"])
string = raw_input("please enter the string:  ")
tape = Tape(string)
program = Program(rules)
machine = TuringMachine(program)

try:
    success = machine.run(tape)
    if success:
        print("The string is valid for this program!")
    else:
        print("The string is not valid for this program")
except NotValidTokenException as e:
    print(e.message)
except UnreacheableTransitionException as e:
    print(e.message)
Exemple #10
0
a = "a"
q0 = "q₀"
q1 = "q₁"
q2 = "q₂"
q3 = "q₃"
q4 = "q₄"
q5 = "q₅"
qf = "qf"
blank = "b̸"

tape = [a] * args.a + [blank] + [a] * args.b

transitions = {(q0, a, a, 1, q0),
               (q0, blank, blank, 1, q1),
               (q1, a, a, 1, q2),
               (q1, blank, blank, 0, q2),
               (q2, blank, blank, -1, q3),
               (q2, a, a, 1, q2),
               (q3, a, blank, -1, q4),
               (q3, blank, blank, -1, q5),
               (q4, a, a, -1, q4),
               (q4, blank, a, -1, q5),
               (q5, a, a, -1, q5),
               (q5, blank, blank, 1, qf)}

machine = TuringMachine(tape, transitions, q0, {qf})
machine.run()
output = machine.output()
print(len(output[0]))
def ajax_simulate():
    tm = TuringMachine(request.form["machine"])
    for el in range(3000):
        tm.move()
    return str(tm.tape)
Exemple #12
0
from turing import TuringMachine

#  Example configuration ----------
tape = '01_'
initial_state = 'q0'
final_states = {'q1'}

transition_function = {
    ('q0', '0'): ('q0', '1', 'R'),
    ('q0', '1'): ('q0', '0', 'R'),
    ('q0', '_'): ('q1', '_', 'N')
}
# ---------------------------------

turing_machine = TuringMachine(tape, initial_state, final_states,
                               transition_function)

print("initial tape: " + turing_machine.get_tape())

while not turing_machine.final():
    turing_machine.step()

print("final tape: " + turing_machine.get_tape())
delta[(3, '1', 'b')] = (3, '1', '1', 'R', 'R')

delta[(4, 'b', '$')] = (5, 'b', '$', 'L', 'R')
delta[(4, 'b', '0')] = (4, 'b', '0', 'S', 'L')
delta[(4, 'b', '1')] = (4, 'b', '1', 'S', 'L')

delta[(5, 'b', '0')] = (6, '0', '0', 'S', 'R')
delta[(5, 'b', '1')] = (6, '1', '1', 'S', 'R')
delta[(5, '0', '0')] = (6, '0', '0', 'S', 'R')
delta[(5, '0', '1')] = (6, '1', '1', 'S', 'R')
delta[(5, '1', '0')] = (6, '0', '0', 'S', 'R')
delta[(5, '1', '1')] = (6, '1', '1', 'S', 'R')

delta[(6, '0', 'b')] = (1, '0', '0', 'S', 'S')
delta[(6, '1', 'b')] = (1, '1', '0', 'S', 'S')
delta[(6, '0', '0')] = (5, '0', '0', 'L', 'S')
delta[(6, '1', '0')] = (5, '1', '0', 'L', 'S')
delta[(6, '0', '1')] = (5, '0', '1', 'L', 'S')
delta[(6, '1', '1')] = (5, '1', '1', 'L', 'S')

alphabet = TuringMachine.BINARY
alphabet.add("$")

tm = TuringMachine(num_states=7,
                   transitions=delta,
                   start=q_0,
                   accept=q_a,
                   reject=q_r,
                   alphabet=alphabet)

tm.run(test_tape)
Exemple #14
0
    def test_turing_first_example(self):
        tm1 = TuringMachine(  # On p. 233 of his article
            "b None -> P0  R c\n"
            "c None ->   R   e\n"
            "e None -> P1  R f\n"
            "f None ->   R   b\n")
        tm2 = TuringMachine(  # On p. 234 of his article, the same idea
            "b None ->   P0   b\n"
            "     0 -> R R P1 b\n"
            "     1 -> R R P0 b\n")
        assert tm1.mconf == tm2.mconf == "b"
        assert tm1.index == tm2.index == 0
        tm1.move()  # Syncronizing them
        tm2.move()
        for idx in range(50):
            assert tm2.mconf == "b"

            assert tm1.index == 2 * idx + 1
            tm1.move()
            assert tm1.index == 2 * idx + 2
            tm1.move()
            assert tm1.index == 2 * idx + 3

            assert tm2.index == 2 * idx
            tm2.move()
            assert tm2.index == 2 * idx + 2

            assert tm1.tape == tm2.tape

        tape = tm1.tape
        tape_length = abs(max(tm1.tape) - min(tm1.tape))
        assert tape_length == 100
        for idx in range(100):
            if idx % 2 == 0:
                assert tape[idx] == str(idx // 2 % 2)
            else:
                assert idx not in tape  # "None"
Exemple #15
0
        ('q4', 'x'): ('q4', 'x', 'R'),
        ('q4', 'a'): ('q3', 'x', 'R'),
        ('q3', '_'): ('q5', '_', 'L'),
        ('q5', 'a'): ('q5', 'a', 'L'),
        ('q5', 'x'): ('q5', 'x', 'L'),
        ('q5', '_'): ('q2', '_', 'R'),
        ('q2', '_'): ('q6', '_', 'R'),
        ('q1', '_'): ('q7', '_', 'R'),
        ('q1', 'x'): ('q7', 'x', 'R'),
        ('q4', '_'): ('q7', '_', 'R'),
    }
    # ---------------------------------

    turing_machine = TuringMachine(
        tape,
        initial_state,
        final_states,
        transition_function
    )


    while not turing_machine.final() and time.time() - turing_machine.time < 0.1:
        turing_machine.step()

    accepted_tape = '_'
    for i in range(1, len(input_string)):
        accepted_tape += 'x'

    if turing_machine.get_tape() == accepted_tape:
        print("ALLOWED")
    else:
        print("REJECTED")
    def test_turing_first_example(self):
        tm1 = TuringMachine( # On p. 233 of his article
            "b None -> P0  R c\n"
            "c None ->   R   e\n"
            "e None -> P1  R f\n"
            "f None ->   R   b\n"
        )
        tm2 = TuringMachine( # On p. 234 of his article, the same idea
            "b None ->   P0   b\n"
            "     0 -> R R P1 b\n"
            "     1 -> R R P0 b\n"
        )
        assert tm1.mconf == tm2.mconf == "b"
        assert tm1.index == tm2.index == 0
        tm1.move() # Syncronizing them
        tm2.move()
        for idx in range(50):
            assert tm2.mconf == "b"

            assert tm1.index == 2 * idx + 1
            tm1.move()
            assert tm1.index == 2 * idx + 2
            tm1.move()
            assert tm1.index == 2 * idx + 3

            assert tm2.index == 2 * idx
            tm2.move()
            assert tm2.index == 2 * idx + 2

            assert tm1.tape == tm2.tape

        tape = tm1.tape
        tape_length = abs(max(tm1.tape) - min(tm1.tape))
        assert tape_length == 100
        for idx in range(100):
            if idx % 2 == 0:
                assert tape[idx] == str(idx // 2 % 2)
            else:
                assert idx not in tape # "None"
def ajax_simulate():
    tm = TuringMachine(request.form["machine"])
    for el in range(3000):
      tm.move()
    return str(tm.tape)
def main():

    DESCRIPTION = (
        'TM Specification is a bit restrictive, for simpler implementation.\n'
        '\n'
        'List of symbols in the alphabet is provided on the first line,\n'
        'separated by spaces. Next come all state + input combinations\n'
        'for the turing machine, as space-separated 5-tuples:\n'
        '\n'
        '   state_from input_from state_to input_to direction\n'
        '\n'
        '(direction must be one of left, right, halt_accept, halt_reject, or noop). States and\n'
        'symbols must be alphanumericunderscore strings. Whatever symbol\n'
        'comes first on the alphabet line is used as the "default" symbol,\n'
        'populating the non-input portions of the initial tape, and the\n'
        'first state_from from the first TM rule is used as the start\n'
        'state for the Turing Machine. All state-symbol pairs should have\n'
        'specified rules. \n'
        '\n'
        'There is one special character, *, which fills in as\n'
        'input_from representing all inputs. This should be disjoint with all other\n'
        'rules. This is used to make the description of s3 in the example\n'
        'below more terse\n'
        '\n'
        '\n'
        'Example Turing Machine Spec File, for a binary-alphabet turing\n'
        'machine that either prints 3 1\'s and then halts, or just halts,\n'
        'depending on whether the first input symbol is 0 or 1:\n'
        '\n'
        'zero one\n'
        's0 zero s0 zero halt_accept\n'
        's0 one s1 one right\n'
        's1 zero s2 one right\n'
        's1 one s2 one right\n'
        's2 * s2 one halt_accept\n'
        '\n'
        '\n')

    ap = argparse.ArgumentParser(description=DESCRIPTION,
                                 formatter_class=argparse.RawTextHelpFormatter)

    ap.add_argument(
        'tm_spec_file',
        help=
        'File specifying the turing machine, according to a specific format.')
    ap.add_argument(
        'input_string_file',
        help=
        'File specifying the input to the turing machine, in the turing machine '
        'language.')

    args = ap.parse_args()

    tm_spec_lines = []
    with open(args.tm_spec_file, 'r') as tm_spec_file:
        tm_spec_lines = ''.join(l for l in tm_spec_file)
        tm_spec_lines = tm_spec_lines.split('\n')

    input_string = ''
    with open(args.input_string_file, 'r') as input_string_file:
        input_string = [l for l in input_string_file]
        assert len(input_string) == 1
        input_string = input_string[0]

    alphabet, rules = TuringMachine.parse_tm_spec_lines(tm_spec_lines)
    input_list = TuringMachine.parse_input_string(input_string,
                                                  alphabet_check=alphabet)

    tm = TuringMachine(alphabet, rules)

    accept, tape, num_steps = tm.simulate(input_list)

    print 'Accepted: %s' % repr(accept)
    print 'Num steps: %d' % num_steps
    print 'Tape state:'
    tape.print_tape()
Exemple #19
0
from turing import TuringMachine

initial_state = 'init'

accepting_states = ['final']

transition_function = {
    ('init', '0'): ('init', '1', 'R'),
    ('init', '1'): ('init', '0', 'R'),
    ('init', ' '): ('final', ' ', 'N'),
}
final_states = {'final'}

t = TuringMachine('010011 ',
                  inital_state='init',
                  final_states=final_states,
                  transition_function=transition_function)

print('Input on Tape:\n' + t.get_tape())

while not t.final():
    t.step()
print('Result of Turning Machine Calculation:')
print(t.get_tape())