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("**************Prime 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 apply_bounds_to_tape(self, tape: Tape): left_edge = -self._offset_of_current right_edge = len(self._cells) - self._offset_of_current - 1 left = None if self._allow_slide_left else left_edge right = None if self._allow_slide_right else right_edge tape.set_assertion_bounds(left, right) tape.check_range_allowed(left_edge, right_edge)
def work(lines, fitas): number_of_lines = len(lines) '''valores de entrada que representam a turing machine de entrada''' input_alphabet = lines[0].split() tape_alphabet = lines[1] whitespace = lines[2] states = lines[3].split() initial_state = lines[4] final_states = lines[5].split() number_of_tapes = lines[6] transitions = [] '''laco que pegara as transicoes''' for i in range(7, number_of_lines): transitions.append(lines[i].split()) tape_list = [] #lista de fitas number_of_args = int(number_of_tapes) #+2 '''laco de repeticao que construira a lista de fitas''' for i in range(0, number_of_args): #2 if len(fitas) >= i: # caso tenha simbolos, ele coloca na fita tape_list.append(Tape(whitespace, tape_alphabet, list(fitas[i]))) else: # caso nao tenha, coloca simbolos que representam o branco tape_list.append(Tape(whitespace, tape_alphabet, [whitespace])) '''Instancia a turing machine''' tm = turing_machine(states, final_states, initial_state, transitions, whitespace, tape_list) '''executa a turing machine''' result = tm.run() if result[0] == 1: return True
def __init__(self): self.CNF = Configurator() self.ConfData = self.CNF.getConfigData() self.WL = WriterLog(self.ConfData['logfile']['filepath'], self.ConfData['logfile']['filename']) self.TP = Tape(self.ConfData['tape']['filepath'], self.ConfData['tape']['filename'], self.ConfData['tape']['separator']) self.TP.readInput()
def __init__(self, machine_config, tape_content): self.input_alphabet = machine_config[0] self.tape_alphabet = machine_config[1] self.blank_symbol = ''.join(machine_config[2]) self.states = machine_config[3] self.init_state = ''.join(machine_config[4]) self.final_states = machine_config[5] self.qnt_tapes = int(''.join(machine_config[6])) self.transictions = machine_config[7:] self.tape_content = tape_content self.tape = Tape(self.tape_content, self.blank_symbol)
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
def simulate(self, tape_input, print_configurations=False): self.state = self.start_state tape = Tape(tape_input, self.blank_symbol) while not self._final_state(): if print_configurations: tape.print_configuration(self.state) try: self._step(tape) except KeyError as error: print(error) return print("Turing Machine halted in an Accepting state")
def setUp(self): ctx = FakeContext() secret_key = ctx.generate_keys() tape = Tape() tape_indices = tape.generate_tape(2, ctx, secret_key) utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1) utils.one = Number.from_plaintext(1, ctx, secret_key, size=1) utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1) # Initial state of machine data_ptr = Number.from_plaintext(0, ctx, secret_key) instruction_ptr = Number.from_plaintext(0, ctx, secret_key) # Defines instructions inc_data_ptr = Number.from_plaintext(1, ctx, secret_key) inc_data_cell = Number.from_plaintext(2, ctx, secret_key) dec_data_ptr = Number.from_plaintext(3, ctx, secret_key) dec_data_cell = Number.from_plaintext(4, ctx, secret_key) mark_loop = Number.from_plaintext(5, ctx, secret_key) loop_back = Number.from_plaintext(6, ctx, secret_key) instruction_set = { "+":inc_data_cell, "-":dec_data_cell, ">":inc_data_ptr, "<":dec_data_ptr, "[":mark_loop, "]":loop_back } instructions, instruction_indices = VirtualMachine.compile("++[>+++<-]", instruction_set, ctx, secret_key) self.blind_machine = VirtualMachine( tape, tape_indices, instruction_indices, instruction_set, instructions, instruction_ptr, data_ptr ) self.context = ctx self.secret_key = secret_key self.tape = tape
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)
def run(): ctx = nufhe.Context() secret_key, cloud_key = ctx.make_key_pair() vm = ctx.make_virtual_machine(cloud_key) # Create tape # Create VM # Execute instruction # Get output tape encrypted # Decrypt tape to get execution results tape = Tape() # Create tape of size n n = 2 indices = [] # Encrypt indices before feeding into VM for x in range(n): tape.add_cell(Number.from_plaintext(0, ctx, secret_key)) indices.append(Number.from_plaintext(x, ctx, secret_key)) utils.logic = vm utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1) # Flag for conditions utils.one = Number.from_plaintext(1, ctx, secret_key, size=1) # A one utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1) # A zero utils.data_ptr = Number.from_plaintext(0, ctx, secret_key) # Cell to perform op on blind_machine = VirtualMachine(tape, indices) # Add 1 instruction """for x in range(3): inc_data_ptr = Number.from_plaintext(0, ctx, secret_key) inc_data_cell = Number.from_plaintext(1, ctx, secret_key) blind_machine.step(inc_data_ptr, inc_data_cell) """ #print(utils.one + utils.one) A = 129 B = 5 sum = Number.from_plaintext(A, ctx, secret_key) + Number.from_plaintext( B, ctx, secret_key) print(sum.decrypt(ctx, secret_key)) print(A, "+", B, "=", sum.decrypt(ctx, secret_key, decimal=True))
def run(code, tape_size=2): ctx = NUFHEContext() #ctx = FakeContext() secret_key = ctx.generate_keys() # Create tape with size of 2 tape = Tape() tape_indices = tape.generate_tape(tape_size, ctx, secret_key) utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1) utils.one = Number.from_plaintext(1, ctx, secret_key, size=1) utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1) # Initial state of machine data_ptr = Number.from_plaintext(0, ctx, secret_key) instruction_ptr = Number.from_plaintext(0, ctx, secret_key) # Defines instructions inc_data_ptr = Number.from_plaintext(1, ctx, secret_key) inc_data_cell = Number.from_plaintext(2, ctx, secret_key) dec_data_ptr = Number.from_plaintext(3, ctx, secret_key) dec_data_cell = Number.from_plaintext(4, ctx, secret_key) mark_loop = Number.from_plaintext(5, ctx, secret_key) loop_back = Number.from_plaintext(6, ctx, secret_key) instruction_set = { "+": inc_data_cell, "-": dec_data_cell, ">": inc_data_ptr, "<": dec_data_ptr, "[": mark_loop, "]": loop_back } instructions, instruction_indices = VirtualMachine.compile( code, instruction_set, ctx, secret_key) blind_machine = VirtualMachine(tape, tape_indices, instruction_indices, instruction_set, instructions, instruction_ptr, data_ptr) blind_machine.run() pprint.pprint(tape.decrypt_tape(secret_key))
def main2(): tape1 = Tape('101011', '01') tape2 = Tape('', '01') states = [ State('qCopy', StateType.Start), State('qReturn', StateType.Empty), State('qTest', StateType.Empty), State('qa', StateType.Accept), State('qr', StateType.Reject) ] transitions = [ TransitionTwoTape('qCopy', '$', '$', 'qCopy', '$', '$', Direction.Right, Direction.Right), TransitionTwoTape('qCopy', '0', '#', 'qCopy', '0', '0', Direction.Right, Direction.Right), TransitionTwoTape('qCopy', '1', '#', 'qCopy', '1', '1', Direction.Right, Direction.Right), TransitionTwoTape('qCopy', '#', '#', 'qReturn', '#', '#', Direction.Neutral, Direction.Left), TransitionTwoTape('qReturn', '#', '0', 'qReturn', '#', '0', Direction.Neutral, Direction.Left), TransitionTwoTape('qReturn', '#', '1', 'qReturn', '#', '1', Direction.Neutral, Direction.Left), TransitionTwoTape('qReturn', '#', '$', 'qTest', '#', '$', Direction.Left, Direction.Right), TransitionTwoTape('qTest', '0', '0', 'qTest', '0', '0', Direction.Left, Direction.Right), TransitionTwoTape('qTest', '1', '1', 'qTest', '1', '1', Direction.Left, Direction.Right), TransitionTwoTape('qTest', '$', '#', 'qa', '$', '#', Direction.Neutral, Direction.Neutral), TransitionTwoTape('qTest', '1', '0', 'qr', '1', '0', Direction.Neutral, Direction.Neutral), TransitionTwoTape('qTest', '0', '1', 'qr', '0', '1', Direction.Neutral, Direction.Neutral) ] tm = TuringMachine(states, transitions, tape1, tape2) print( "\nTwo-tape Turing machine recognizes whether a binary string is a palindrome." ) tm.process2() print("\nInput string:") print(tm.get_tape1()) if (tm.current_state.type == StateType.Accept): print('\nAccepting') if (tm.current_state.type == StateType.Reject): print('\nRejecting') pass
def __init__(self, data=None, tape_view=None, cells=[None], position=1): self.tape = Tape(cells, position) self.states = {} self.state = u'0' self.view = tape_view assert data is not None, \ "Action table data argument cannot be None" assert self.view is not None, \ "Tape view argument cannot be None" assert position >= 1 and position <= len(cells), \ "Position must be an existing cell position" for row in data: state = row[0] symbol = row[1] state_new = row[2] symbol_new = row[3] action = row[4] if self.states.get(state): self.states[state].update({ symbol: (state_new, symbol_new, action) }) else: self.states[state] = { symbol: (state_new, symbol_new, action) }
def __init__(self, initial): self.__acceptance = ["halt", "halt-accept"] self.__rejection = ["halt-reject"] self.__current = initial self.__tape = Tape() self.__status = {} self.__steps = 0
class Machine(object): def __init__(self, data=None, tape_view=None, cells=[None], position=1): self.tape = Tape(cells, position) self.states = {} self.state = u'0' self.view = tape_view assert data is not None, \ "Action table data argument cannot be None" assert self.view is not None, \ "Tape view argument cannot be None" assert position >= 1 and position <= len(cells), \ "Position must be an existing cell position" for row in data: state = row[0] symbol = row[1] state_new = row[2] symbol_new = row[3] action = row[4] if self.states.get(state): self.states[state].update({ symbol: (state_new, symbol_new, action) }) else: self.states[state] = { symbol: (state_new, symbol_new, action) } def run(self, step_delay=1): self.view.update(self.tape.display_string(), self.tape.position, self.state) time.sleep(step_delay) while self.state != u'h': transition = self.states.get(self.state).get(self.tape.get_symbol()) if transition != None: self.state = transition[0] self.tape.write(transition[1]) if transition[2] == u'>': self.tape.right() elif transition[2] == u'<': self.tape.left() self.view.update(self.tape.display_string(), self.tape.position, self.state) time.sleep(step_delay)
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
def random_matching_tape(self, ctx: AssertionCtx) -> Tape: for var in self._used_variables: if var not in ctx.bound_vars: ctx.bound_vars[var] = ctx.random_biased_byte() data: List[int] = [] for cell in self._cells: data.append(cell.random_matching(ctx)) tape = Tape(self._offset_of_current, data, False, True) self.apply_bounds_to_tape(tape) return tape
class TuringMachine: def __init__(self): self.CNF = Configurator() self.ConfData = self.CNF.getConfigData() self.WL = WriterLog(self.ConfData['logfile']['filepath'], self.ConfData['logfile']['filename']) self.TP = Tape(self.ConfData['tape']['filepath'], self.ConfData['tape']['filename'], self.ConfData['tape']['separator']) self.TP.readInput() def getConfigData(self): print(self.ConfData) def writeLog(self, message): self.WL.writeLog(message) def getInput(self): print(self.TP.getInput())
def __init__(self, machine, tape=None): """ Requires a machine instance, and defaults to the default tape is not supllied with one. """ self.machine = machine if tape is None: self.tape = Tape() else: self.tape = tape self.steps = 0
def __init__(self, nb_of_states=config.NB_OF_STATES, nb_of_symbols=config.NB_OF_SYMBOLS, init_state=0, init_tape_length=config.TOTAL_ENCODING_LENGTH): self.nb_of_states = nb_of_states self.nb_of_symbols = nb_of_symbols self.init_state = init_state self.current_state = init_state self.tape = Tape(nb_of_symbols, init_tape_length) # [old_state][symbon_read] => ( symbol_to_write, movement, new_state ) #self.action_table = [[ ( 0, '', 0 ) ] * nb_of_symbols ] * nb_of_states # Problem = works by reference self.action_table = [] for old_state in range(nb_of_states): self.action_table.append([]) for symbol_read in range(nb_of_symbols): self.action_table[old_state].append((0, '', 0))
def test_get_contents_and_index_shift(self): t = Tape() t.write(1) t.shift_left() tape_contents, index = t.get_contents_and_index() self.assertEqual(tape_contents, [0,1]) self.assertEqual(index, 0)
def __init__(self, initial_state, states, tapes=[Tape()], is_deterministic=True): self.tapes = tapes self.is_deterministic = is_deterministic self.states = dict() for state, transitions in states.items(): new_state = State(state, self, transitions) self.states[state] = new_state self.state = self.states[initial_state] self.traversed_transitions = []
def increment(word, verbose=False): tape = Tape(word, '|') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s1", "$", Direction.Right), Transition("s1", "|", "s1", "|", Direction.Right), Transition("s1", "#", "sf", "|", Direction.Neutral) ] return TuringMachine(states, transitions, tape, verbose)
def main(): (options, args) = parse_args() cardsFilePath = args[0] tape = Tape(options.defaultValue, options.tapeSize) maxIterations = options.maxIterations with open(cardsFilePath, "r") as handle: cards = json.load(handle) currentState = "start" iterationCount = 0 while (currentState != "halt") and (iterationCount < maxIterations): instructions = cards[currentState][tape.read()] tape.write(instructions["write"]) tape.move(instructions["move"]) currentState = instructions["next"] print currentState print tape.statusToString() iterationCount += 1 if currentState != "halt": print "maximum iterations exceeded!"
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 __init__(self, alphabet, initialstate, initialtape, finalstates, blank): '''Construct a Turing machine Args: alphabet (str): The alphabet initialstate (str): The name of the initial state initialtape (str): The initial contents of the state finalstates (List): A list of the names of the final states blank (str): The blank symbol for this TM ''' self.alphabet = alphabet self.initialstate = initialstate self.states = {} self.currentstate = self.initialstate self.tape = Tape(initialtape, blank) self.finalstates = finalstates
def run_diagnostic(states, start_state, iterations): tape = Tape() next_state = start_state for i in range(iterations): next_steps = states[next_state].eval(tape.mem_value) tape.mark_pos(next_steps[0]) tape.shift(next_steps[1]) next_state = next_steps[2] return tape
def __init__(self, tape="", blank_symbol=" ", initial_state="", final_states=None, transition_function=None): self.__tape = Tape(tape) self.__head_position = 0 self.__blank_symbol = blank_symbol self.__current_state = initial_state if transition_function == None: self.__transition_function = {} else: self.__transition_function = transition_function if final_states == None: self.__final_states = set() else: self.__final_states = set(final_states)
class System(object): def __init__(self, machine, tape=None): """ Requires a machine instance, and defaults to the default tape is not supllied with one. """ self.machine = machine if tape is None: self.tape = Tape() else: self.tape = tape self.steps = 0 def next(self): """ Allows the machine to proceed one step forward """ self.steps += 1 write_symbol, shift_right = self.machine.next(self.tape.read()) self.tape.write(write_symbol) if shift_right: self.tape.shift_right() else: self.tape.shift_left() def iterate_until_halt(self, max_steps=None): """ Iterates the machine until it halts. If max_step is supplied and reached before a halt occurs, DidNotHalt exception is raised. """ while True: try: self.next() except Halt: return self.steps if max_steps is not None and self.steps >= max_steps: raise DidNotHalt() def get_state_tape_contents_and_head_index(self): tape_contents, head_index = self.tape.get_contents_and_index() return self.machine.state, tape_contents, head_index
def main1(): print( "\nTuring machine recognizes whether or not the number of 0s is a power of 2." ) st = '0000000000000000000000' tape1 = Tape(st, '0x') print("\nInput string:") print(st) states = [ State('q1', StateType.Start), State('q2', StateType.Empty), State('q3', StateType.Empty), State('q4', StateType.Empty), State('q5', StateType.Empty), State('qa', StateType.Accept), State('qr', StateType.Reject) ] transitions = [ Transition('q1', '$', 'q1', '$', Direction.Right), Transition('q1', '0', 'q2', '#', Direction.Right), Transition('q1', '#', 'qr', '#', Direction.Right), Transition('q1', 'x', 'qr', 'x', Direction.Right), Transition('q2', 'x', 'q2', 'x', Direction.Right), Transition('q2', '#', 'qa', '#', Direction.Right), Transition('q2', '0', 'q3', 'x', Direction.Right), Transition('q3', 'x', 'q3', 'x', Direction.Right), Transition('q3', '#', 'q5', '#', Direction.Left), Transition('q3', '0', 'q4', '0', Direction.Right), Transition('q4', '0', 'q3', 'x', Direction.Right), Transition('q4', 'x', 'q4', 'x', Direction.Right), Transition('q4', '#', 'qr', '#', Direction.Right), Transition('q5', '#', 'q2', '#', Direction.Right), Transition('q5', '0', 'q5', '0', Direction.Left), Transition('q5', 'x', 'q5', 'x', Direction.Left) ] tm = TuringMachine(states, transitions, tape1) tm.process1() if (tm.current_state.type == StateType.Accept): print('\nAccepting') if (tm.current_state.type == StateType.Reject): print('\nRejecting') pass
def run(args: Args, io: Io) -> None: program = None try: load_start_time = time.time() source_file = SourceFile(args) code = parse.source(source_file, args) tape = Tape(0, [], True, False) program = Program(tape, code, io) program_start_time = time.time() logger.info('Took ' + str(round(program_start_time - load_start_time, 2)) + 's to load program') if args.prop_tests: run_property_tests(args, cast(Program, program)) else: run_normally(cast(Program, program)) io.reset() except (ProgramError, ParseError) as e: if args.expect_fail: return else: raise finally: if program: program_end_time = time.time() input_time = io.time_waiting_for_input() program_time = program_end_time - program_start_time - input_time logger.info('Took ' + str(round(program_time, 2)) + 's to run the program' + ' (plus ' + str(round(input_time, 2)) + 's waiting for input)') logger.info('Ran ' + str(program.emulated_ops) + ' virtual brainfuck operations') logger.info('Ran ' + str(program.real_ops) + ' real constant time operations') if not args.prop_tests: logger.info('Tape: ' + str(tape)) if args.expect_fail: error = UnexpectedSuccessError('Succeeded unexpectedly') if program: error.tape = program.tape raise error
def subtract(word, verbose=False): tape = Tape(word, '|&') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("s2", StateType.Empty), State("s3", StateType.Empty), State("s4", StateType.Empty), State("s5", StateType.Empty), State("s6", StateType.Empty), State("s7", StateType.Empty), State("s8", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s0", "$", Direction.Right), Transition("s0", "#", "sf", "#", Direction.Neutral), Transition("s0", "|", "s1", "|", Direction.Right), Transition("s1", "|", "s1", "|", Direction.Right), Transition("s1", "#", "s2", "#", Direction.Right), Transition("s2", "#", "s2", "#", Direction.Right), Transition("s2", "|", "s3", "|", Direction.Right), Transition("s3", "|", "s4", "|", Direction.Left), Transition("s3", "#", "s6", "#", Direction.Left), Transition("s4", "|", "s5", "#", Direction.Left), Transition("s5", "#", "s5", "#", Direction.Left), Transition("s5", "|", "s2", "#", Direction.Right), Transition("s5", "$", "s2", "$", Direction.Right), Transition("s6", "|", "s7", "#", Direction.Left), Transition("s7", "#", "s7", "#", Direction.Left), Transition("s7", "$", "sf", "$", Direction.Neutral), Transition("s7", "|", "s8", "#", Direction.Left), Transition("s8", "|", "s8", "|", Direction.Left), Transition("s8", "$", "sf", "$", Direction.Neutral) ] return TuringMachine(states, transitions, tape, verbose)
from turing_machine import TuringMachine from state import State, StateType from transition import Transition from direction import Direction from tape import Tape # Simple test to check whether the turing machine is working tape = Tape('|||', '|') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s1", "$", Direction.Right), Transition("s1", "|", "s1", "|", Direction.Right), Transition("s1", "#", "sf", "|", Direction.Neutral) ] tm = TuringMachine(states, transitions, tape) tm.process() print(tm.get_tape())
def mainloop(program,bracket_map): tape = Tape() pc = 0 while pc < len(program): code = program[pc] if code == ">": tape.advance() elif code == "<": tape.devance() elif code == "+": tape.inc() elif code == "-": tape.dec() elif code == ".": sys.stdout.write(chr(tape.get())) elif code == ",": tape.set(ord(sys.stdin.read(1))) elif code == "[" and tape.get() == 0: pc = bracket_map[pc] elif code == "]" and tape.get() != 0: pc = bracket_map[pc] pc += 1
def set_tape_in_TM(self, tape, blank): self.tape = Tape(tape, blank)
class TuringMachine: '''Class to represent a Turing machine''' def __init__(self, alphabet, initialstate, initialtape, finalstates, blank): '''Construct a Turing machine Args: alphabet (str): The alphabet initialstate (str): The name of the initial state initialtape (str): The initial contents of the state finalstates (List): A list of the names of the final states blank (str): The blank symbol for this TM ''' self.alphabet = alphabet self.initialstate = initialstate self.states = {} self.currentstate = self.initialstate self.tape = Tape(initialtape, blank) self.finalstates = finalstates self.halted = '' self.finaltape = '' def addstate(self, statename, state): '''Add a state to the TM Args: statename(str) : name of the state state(State) : the state ''' self.states[statename] = state def set_alphabet_in_TM(self,alphabet): self.alphabet = alphabet def set_tape_in_TM(self, tape, blank): self.tape = Tape(tape, blank) def set_initialstate(self, _state): self.initialstate = _state self.currentstate = str(self.initialstate) def set_finalstates(self, _final): self.finalstates.add(_final) # def set_alphabet(self, alphabet): # self.alphabet = alphabet # # def set_initialstate(self, initialstate): # self.initialstate = initialstate # # def add_finalstate(self, statename): # self.finalstates.append() def removestate(self, statename): '''Removes a state from the TM Args: statename(str) : name of the state ''' del self.states[statename] def getstate(self): '''Get the current state Returns: str: the name of the current state ''' return self.currentstate def gettape(self): '''Get the current tape as a string Returns: str: the current tape ''' return self.tape.gettape() def step(self): '''Executes one execution step on the TM Returns: bool: False if there was no transition defined, True otherwise ''' cursym = self.tape.getsym() state= self.states[self.currentstate] transition = state.get_transition(cursym) # print transition if transition is None: return False self.currentstate = transition.get_next_state() if (transition.get_next_direction() == "R"): self.tape.writeright(transition.get_write_sym()) else: self.tape.writeleft(transition.get_write_sym()) return True
def test_get_contents_and_index_blank(self): t = Tape() tape_contents, index = t.get_contents_and_index() self.assertEqual(tape_contents, [0]) self.assertEqual(index, 0)
class TuringMachine(object): """ TuringMachine(machine_config, tape_content) machine_config is a list of attributes of the Turing machine that must be like following: position 0: List of the input alphabet position 1: List of the tape alphabet position 2: Symbol that represents the blank space position 3: List of the states position 4: The initial state position 5: List of the final states position 6: Number of tapes (This Turing machine simulator currently accepts only single-tape machines) position 7 to forward: Transactions in a list format that must be like: position 0: Currently state position 1: Next state position 2: The symbol of tape in current position position 3: The New symbol of tape in current position position 4: The indication of movement (R to right, L to left and S to stay) tape_content is a String that represents the content on the tape at begin of Turing machine computing """ def __init__(self, machine_config, tape_content): self.input_alphabet = machine_config[0] self.tape_alphabet = machine_config[1] self.blank_symbol = ''.join(machine_config[2]) self.states = machine_config[3] self.init_state = ''.join(machine_config[4]) self.final_states = machine_config[5] self.qnt_tapes = int(''.join(machine_config[6])) self.transictions = machine_config[7:] self.tape_content = tape_content self.tape = Tape(self.tape_content, self.blank_symbol) def initialize_computing(self): """ initialize_computing() Initializes the Turing machine computing """ self.print_information() current_state = self.init_state queue = [self.tape] while queue: if current_state in self.final_states: print(self.tape.tape_content) print('Accept') exit(0) valid_transitions = self.valid_transitions(current_state) for transition in valid_transitions: current_state = self.aply_transaction(transition) def validate_input(self): """ validate_input() Input format validation returns 0 if the input format is valid or one of the following for invalid: 1 if has no one input alphabet detected 2 if has no one tape alphabet detected 3 if has no one blank symbol detected 4 if has no one states detected 5 if has no one init state detected 6 if has no one final state detected 7 if the quantity of tapes is different of 1 8 if has no one transition detected """ if self.input_alphabet == ['']: return 1 if self.tape_alphabet == ['']: return 2 if self.blank_symbol == '': return 3 if self.states == ['']: return 4 if self.init_state == '': return 5 if self.final_states == ['']: return 6 if self.qnt_tapes != 1: return 7 if self.transictions == []: return 8 for character in list(self.tape_content) if self.transictions == []: return return 0 def print_information(self): print('Input alphabet: ', self.input_alphabet) print('Tape alphabet: ', self.tape_alphabet) print('Blank symbol: ', self.blank_symbol) print('States: ', self.states) print('Initial state: ', self.init_state) print('Final states: ', self.final_states) print('Quantity of tapes', self.qnt_tapes) def aply_transaction(self, transition): self.tape.write(transition[3]) self.tape.move(transition[4]) return transition[1] def valid_transitions(self, state): valid_transitions = [] for transiction in self.transictions: if transiction[0] == state: if self.tape.read() == transiction[2]: valid_transitions.append(transiction) return valid_transitions
def __init__(self, screen): self.screen = screen self.tape = Tape()
from turing_machine import TuringMachine from state import State, StateType from transition import Transition from direction import Direction from tape import Tape tape = Tape('aaabbb', 'abxy') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("s2", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s0", "$", Direction.Right), Transition("s0", "a", "s1", "x", Direction.Right), Transition("s1", "a", "s1", "a", Direction.Right), Transition("s1", "b", "s2", "y", Direction.Left), Transition("s2", "a", "s2", "a", Direction.Left), Transition("s2", "x", "s0", "x", Direction.Right), Transition("s1", "y", "s1", "y", Direction.Right), Transition("s2", "y", "s2", "y", Direction.Left), Transition("s0", "y", "sf", "y", Direction.Neutral) ] tm = TuringMachine(states, transitions, tape) tm.process(verbose=True) print(tm.get_tape())
def test_all_blanks(self): t = Tape() t.shift_left() t.shift_left() t.shift_left() t.shift_left() self.assertEqual(t.read(), 0) t2 = Tape() t2.shift_right() t2.shift_right() t2.shift_right() t2.shift_right() self.assertEqual(t2.read(), 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()
def interpret(source): brackets = getBrackets(source) inv_brackets = {v:k for k, v in brackets.items()} t = Tape() ind = 0 while ind < len(source): if source[ind] == '>': t.right() ind += 1 elif source[ind] == '<': t.left() ind += 1 elif source[ind] == '+': t.inc() ind += 1 elif source[ind] == '-': t.dec() ind += 1 elif source[ind] == '.': sys.stdout.write(t.getChar()) ind += 1 elif source[ind] == ',': t.putChar() ind += 1 elif source[ind] == '[': if t.getNum() == 0: ind = brackets[ind] ind += 1 elif source[ind] == ']': ind = inv_brackets[ind]
def test_get_contents_and_index_write_shfit(self): t = Tape() t.write(1) t.shift_left() t.write(2) t.shift_left() t.shift_right() t.shift_right() t.shift_right() t.shift_right() t.write(3) t.shift_right() t.shift_left() t.shift_left() tape_contents, index = t.get_contents_and_index() self.assertEqual(tape_contents, [2,1,0,3]) self.assertEqual(index, 2)
def test_write(self): t = Tape() self.assertEqual(t.read(), 0) t.write(1) self.assertEqual(t.read(), 1)
class TuringMachine: '''Class to represent a Turing machine''' def __init__(self, alphabet, initialstate, initialtape, finalstates, blank): '''Construct a Turing machine Args: alphabet (str): The alphabet initialstate (str): The name of the initial state initialtape (str): The initial contents of the state finalstates (List): A list of the names of the final states blank (str): The blank symbol for this TM ''' self.alphabet = alphabet self.initialstate = initialstate self.states = {} self.currentstate = self.initialstate self.tape = Tape(initialtape, blank) self.finalstates = finalstates def addstate(self,statename, state): '''Add a state to the TM Args: statename(str) : name of the state state(State) : the state ''' self.states[statename] = state def getstate(self): '''Get the current state Returns: str: the name of the current state ''' return self.currentstate def gettape(self): '''Get the current tape as a string Returns: str: the current tape ''' return self.tape.gettape() def step(self): '''Executes one execution step on the TM Returns: bool: False if there was no transition defined, True otherwise ''' cursym = self.tape.getsym() state= self.states[self.currentstate] transition = state.get_transition(cursym) # print transition if transition is None: return False self.currentstate = transition.get_next_state() if (transition.get_next_direction() == "R"): self.tape.writeright(transition.get_write_sym()) else: self.tape.writeleft(transition.get_write_sym()) return True def runtohalt(self): '''Run the machine to completion. Prints an execution trace Returns: nothing ''' print "initial state=", self.currentstate print "initial tape=", self.gettape() print " " steps = 0 while self.step(): steps += 1 print "steps = ", steps print "state = ", self.currentstate print "tape = ", self.gettape() print " " if self.currentstate in self.finalstates: print "halted with answer yes" else: print "halted with answer no"
class Tapes: screen = None tape = None def __init__(self, screen): self.screen = screen self.tape = Tape() def on_draw(self): self.screen.fill((0, 0, 0)) pygame.draw.line(self.screen, (0, 0, 255), (40, 80), (120, 80)) pygame.draw.circle(self.screen, (255, 0, 0) if self.tape.play else (0, 0, 255), (40, 50), 30, 4) pygame.draw.circle(self.screen, (0, 255, 0) if self.tape.record else (0, 0, 255), (120, 50), 30, 2) def on_pygame_event(self, event): if event.type == pygame.KEYDOWN: if event.key == 113: # q self.tape.set_recording(True) elif event.key == 119: # w self.tape.set_playing(True) elif event.key == 101: # e None elif event.key == 114: # r None elif event.key == 273: # up self.tape.clear_tape() elif event.key == 274: # down None elif event.key == 275: # right None elif event.key == 276: # left self.tape.seek(0) elif event.key == 13: # enter self.tape.halt() elif event.key == 49: # 1 self.tape.set_track(1) elif event.key == 50: # 2 self.tape.set_track(2) elif event.key == 51: # 3 self.tape.set_track(3) elif event.key == 52: # 4 self.tape.set_track(4) def on_midi_event(self, midi_input_name, message): return
def test_initially_blank_head(self): t = Tape() self.assertEqual(t.read(), 0)
def test_different_blank_symbol(self): t = Tape(blank_symbol=None) self.assertEqual(t.read(), None) t.shift_left() t.shift_left() t.shift_left() t.shift_left() self.assertEqual(t.read(), None) t2 = Tape(blank_symbol=None) t2.shift_right() t2.shift_right() t2.shift_right() t2.shift_right() self.assertEqual(t2.read(), None)
#! /usr/bin/python # vbf.py - a tape-based visual brainfuck interpreter import sys, time from tape import Tape, Tapes, TapeError f = open(sys.argv[1]) program = [c for c in f.read() if c in "<>,.-+[]"] f.close() prog_tape = Tape(program, right_infinite=False) data_tape = Tape([0], 3) tapes = Tapes((prog_tape, data_tape)) PROG = 0 DATA = 1 STEP_TIME = 0.2 SEEK_TIME = 0.05 while 1: time.sleep(STEP_TIME) c = prog_tape.get() if c == "<": tapes.move_left(DATA) print 1 elif c == ">": tapes.move_right(DATA) elif c == ".":
class TuringMachine: def __init__(self): self.TransitionTable = [] self.tape1 = Tape() self.tape2 = Tape() self.tape3 = Tape() def __str__(self): """Makes the machine pretty to read.""" M = str(self.tape1) + "\n" + str(self.tape2) + "\n" + str(self.tape3) return M def lookup_transition(self, state, in2): """Searches for a transition in the table, can return None.""" for tuple in self.TransitionTable: if (tuple[0] == state and tuple[1] == in2): return tuple return None def set_head_on_transition(self, transition): """Sets the head of the tape on the given transition.""" index = self.TransitionTable.index(transition) index = index * 6 + 1 self.tape1.head = index def add_transition(self, state, in2, out2, mov2, next_state): """Adds a new transition to the machine's transition table.""" new_tuple = (state, in2, out2, mov2, next_state) # We check that the current state has a transition # for the desired inputs, if it does we overwrite it old_tuple = self.lookup_transition(state, in2) if old_tuple: old_tuple = new_tuple else: # If there is no transition for this state and inputs # we simply add it to the machine's transition table self.TransitionTable.append(new_tuple) def print_transition_table(self): """Prints all of the transitions in the Machine.""" for tuple in self.TransitionTable: print tuple def tape_setup(self, word, initial_state): """Prepares the Machine's tapes for execution.""" # Setting up the three tapes, we cheat here and # don't use the tape's movement and writing methods # for simplicity and efficiency. for transition in self.TransitionTable: for char in transition: self.tape1.tape.append(str(char)) self.tape1.tape.append(";") for char in word: self.tape2.tape.append(char) self.tape3.move("R") self.tape3.write(initial_state) def execute(self, word, initial_state, halt_state, verbose = False): """Executes the machine, prints if the word is Accepted or Crashes.""" self.tape_setup(word, initial_state) # Main Universal Turing Machine execution loop # while our tape3 (the state tape) isn't pointing to halt # we keep executing according to our transition table. # Do note that the machine can infinite loop if its # not programmed properly. while self.tape3.read() != halt_state: current_state = self.tape3.read() input2 = self.tape2.read() instruction = self.lookup_transition(current_state, input2) if instruction: output = instruction[2] movement = instruction[3] next_state = instruction[4] else: raise MachineException("CRASH") yield self self.tape2.write(output) self.set_head_on_transition(instruction) self.tape2.move(movement) self.tape3.write(next_state) yield self print "ACCEPT"
def test_write_shift(self): t = Tape() t.write(1) t.shift_left() self.assertEqual(t.read(), 0) t.shift_right() self.assertEqual(t.read(), 1) t.shift_right() self.assertEqual(t.read(), 0) t.write(2) t.shift_right() t.shift_left() self.assertEqual(t.read(), 2) t.shift_left() self.assertEqual(t.read(), 1)
def __init__(self): self.TransitionTable = [] self.tape1 = Tape() self.tape2 = Tape() self.tape3 = Tape()
def mainloop(program, bracket_map): pc = 0 tape = Tape() while pc < len(program): jitdriver.jit_merge_point(pc=pc, tape=tape, program=program,bracket_map=bracket_map) code = program[pc] if code == ">": tape.advance() elif code == "<": tape.devance() elif code == "+": tape.inc() elif code == "-": tape.dec() elif code == ".": # print os.write(1, chr(tape.get())) elif code == ",": # read from stdin tape.set(ord(os.read(0, 1)[0])) elif code == "[" and tape.get() == 0: # Skip forward to the matching ] pc = bracket_map[pc] elif code == "]" and tape.get() != 0: # Skip back to the matching [ pc = bracket_map[pc] pc += 1