Ejemplo n.º 1
0
def test_set_string_empty_tape_left_left_right_a():
    tape = Tape('B', ['a', 'b', 'X', 'B'], [])
    tape.move_left()
    tape.move_left()
    tape.move_right()
    tape.set_content('a')
    assert "(['B', 'a'])@1" == str(tape)
Ejemplo n.º 2
0
class TuringMachine(object):
    def __init__(self, machine_description_file):
        with open(machine_description_file) as input_file:
            init_string = input_file.read()
            split = init_string.split("111")
            machine_info = split[0]
            transitions = split[1]
            inputtape = split[2]
            split_machine = machine_info.split("1")
            print("**************Universal Turing Machine**************")
            print("\nUsing the following metadata:")
            print(machine_info)
            print("\nUsing the following transitions:")
            print(transitions)

            if len(split_machine) != 7:
                raise ValueError('Incorrect number of metadata fields')
            self.states = split_machine[0]
            self.tape_symbols = split_machine[1]
            self.input_symbols = split_machine[2]
            self.blank_symbol = split_machine[3]
            self.current_state = split_machine[4]
            self.accept_state = split_machine[5]
            self.reject_state = split_machine[6]

        self.transition_table = TransitionTable()

        print("\nTransition table: ")
        print("st1\tsym1\tst2\tsym2\tdir")

        if transitions:
            split_transitions = transitions.split("11")
            for transition in split_transitions:
                self.transition_table.add_transition(
                    Transition.create_from_string(transition))
        self.tape = Tape(inputtape.split("1"), self.blank_symbol)

    def run(self):
        count = 0
        while self.current_state != self.accept_state:
            if self.current_state == self.reject_state:
                print("\nTotal head moves: {}".format(count))
                print("Rejected")
                break
            count += 1
            current_symbol = self.tape.read()
            # print("state: {}, symbol: {}".format(self.current_state, current_symbol))
            transition = self.transition_table.get_transition(
                self.current_state, current_symbol)
            self.tape.write(transition.next_symbol)
            if transition.tape_motion == Direction.RIGHT:
                self.tape.move_right()
            elif transition.tape_motion == Direction.LEFT:
                self.tape.move_left()
            self.current_state = transition.next_state
        if self.current_state == self.accept_state:
            print("\nTotal head moves: {}".format(count))
            print("Accepted")
        return self.tape
Ejemplo n.º 3
0
def test_set_content_empty_tape_left_left_right():
    tape = Tape('B', ['a', 'b', 'X', 'B'], [])
    tape.move_left()
    tape.move_left()
    tape.move_right()
    tape.set_content('a')
    assert tape.get_content() == 'a'
    assert tape.position == 1
Ejemplo n.º 4
0
    class Machine():
        def __init__(self,blankchar="b"):
            """
            @purpose Initialise the Machine class used to keep track of states. The tape starts off with a blank cell.
            :param blankchar: The blank character representation to use.
            """
            self.states = {}
            self.transitions = {}
            self.starting = None
            self.tape = Tape(blankchar)
            self.halting_states = {}
            self.blankchar = blankchar

            self.current_step = 0
            self.current_state = self.starting
            self.current_read = None
            self.current_transition = None
            self.halted = False

        def get_num_states(self):
            # Returns the number of states currently in the machine
            return len(self.states)

        def is_halted(self):
            """
            @purpose Returns halted in boolean
            """
            return self.halted

        def halt(self):
            """
            @purpose Sets halt to True
            """
            self.halted = True

        def set_tape(self, tape):
            """
            @purpose Sets the tape to the initial tape
            :param tape: Takes in the initial tape
            :return:
            """
            self.tape.init_tape(tape)

        def set_blank_char(self, char):
            """
            @purpose Sets the blankchar to char
            :param char: Takes in character 'b'
            :return:
            """
            self.blankchar = char

        def get_tape(self):
            """
            @purpose Returns the whole tape
            """
            return self.tape.print_tape()

        def get_current_tape_head_pos(self):
            """
            @purpose Returns the current tape head position
            """
            return self.tape.get_head_pos()

        def set_starting(self, id):
            """
            @purpose Set the current state to the staring state
            :param id: ID of the state
            :return:
            """
            try:
                self.starting = self.states[id]
                if self.current_step == 0:
                    self.current_state = self.starting

            except KeyError:
                raise Exception("State does not exist.")

        def get_starting_state(self):
            """
            @purpose Returns the starting state
            """
            return self.starting

        def add_state(self, id, reference):
            """
            @purpose Prints the states image
            """
            try:
                print self.states[id]
                raise Exception("State already exists.")
            except KeyError:
                self.states[id] = reference
                print self.states

        def get_state(self, id):
            """
            @purpose Returns the state with the ID
            :param id: ID of the state
            """
            return self.states[id]

        def delete_state(self, id):
            """
            @purpose Deletes the state that was selected
            :param id: ID of the state that was clicked on
            :return:
            """
            del self.states[id]

        def get_num_states(self):
            """
            @purpose Returns the number of states
            """
            return len(self.states)

        def add_transition(self, origin, destination):
            #TODO: Transitions not needed for A3
            pass

        def delete_transition(self, origin, destination):
            #TODO: Transitions not needed for A3
            pass

        def modify_state(self,original_id,new_id):
            pass

        def reset_execution(self):
            # Resets the execution state of the turing machine
            self.current_step = 0
            self.current_read = None
            self.current_state = self.starting
            self.current_transition = None
            self.halted = False

        def execute(self):
            """
            @purpose When the "Execute" button is clicked, this will execute the Turing Machine by one step
            """
            if self.current_transition is not None:
                self.current_transition.execute_unhighlight()
            self.increment_step()
            self.current_read = self.tape.read()

            transitions = self.current_state.get_transition_seen(self.current_read)
            #print self.current_read

            print transitions
            if len(transitions) > 0:
                tran = random.choice(transitions)

                #for tran in transitions:
                self.current_transition = tran
                self.current_transition.execute_highlight()
                self.current_state = tran.get_end()
                self.write_current_pos(tran.get_write())
                move = tran.get_move()
                print tran.id, self.current_state.id
                if move == "L":
                    self.move_left()
                elif move == "R":
                    self.move_right()
                elif move == "N":
                    pass

                print(self.tape.head_pos, self.tape.tape)


            if len(transitions) == 0:
                # if no transition if defined for a particular symbol in a state, halts
                self.halt()

        def move_left(self):
            """
            @purpose Moves the machine head to the left, and extends the tape if necessary
            """
            self.tape.move_left()

        def move_right(self):
            """
            @purpose Moves the machine head to the right, and extends the tape if necessary
            """
            self.tape.move_right()



        def increment_step(self):
            """
            @purpose Maintains a counter of steps for a TM simulation
            """
            self.current_step += 1

        def write_current_pos(self, value):
            """
            @purpose Allows for writing data on the current position of the head
            :param value: The value to be written
            """
            return self.tape.write(value)

        def check_halt_answer(self):
            """
            @purpose Check whether the Turing Machine halts with a "Yes" or a "No".
            """
            print self.current_state.id
            if self.current_state.is_halt() is True:
                content= Label(text="Halted with answer YES")
                print "halted with answer yes"
            else:
                content= Label(text="Halted with answer NO")
                print "halted with answer no"

            self._popup = Popup(title="Execution Complete",
                            content=content,
                            size_hint=(0.3, 0.3))
            self._popup.open()
Ejemplo n.º 5
0
def test_get_content_of_non_empty_tape_at_end_with_head_moved_to_right():
    tape = Tape('B', ['a', 'b', 'X', 'B'], ['a', 'b'])
    tape.move_right()
    tape.move_right()
    assert tape.get_content() == 'B'