def __init__(self, init_energy_level=config.INIT_ENERGY_LEVEL, randomize=True): self.energy_level = init_energy_level self.turing_machine = TuringMachine() if randomize == True: self.turing_machine.randomize()
def test_updating(): s1 = State() s2 = State() t = Transition(s2, 'b', Direction.RIGHT) s1.add_transition('a', t) tm = TuringMachine("acd", s1, s2, s1) assert tm.tape == ['a', 'c', 'd', '_'] tm._read('a') assert tm.tape[0] == 'b' assert tm.current_state == s2
def test_tape_never_negative(): s1 = State() s2 = State() t = Transition(s2, 'b', Direction.LEFT) s1.add_transition('a', t) tm = TuringMachine("acd", s1, s2, s1) assert tm.tape == ['a', 'c', 'd', '_'] tm._read('a') assert tm.tape[0] == 'b' assert tm.current_state == s2 assert tm.tape_position == 0
class Cell: def __init__(self, init_energy_level=config.INIT_ENERGY_LEVEL, randomize=True): self.energy_level = init_energy_level self.turing_machine = TuringMachine() if randomize == True: self.turing_machine.randomize() def __del__(self): del self.energy_level del self.turing_machine def loseEnergy(self, energy_lose_rate=config.ENERGY_LOSS_RATE): energy_lost = energy_lose_rate * len( self.turing_machine.tape.tape ) * self.turing_machine.nb_of_states * self.turing_machine.nb_of_symbols energy_lost = min(energy_lost, self.energy_level) self.energy_level -= energy_lost return energy_lost def writeEnvironment(self, energy_level, food_level, distance): tape = self.turing_machine.tape index = config.OUTPUT_ENCODING_LENGTH # Output + Input + Rest of the tape energy_level_normalized = energy_level / config.ENERGY_LEVEL_VALUE_MAX energy_level_encoded = encode.encode2_8(energy_level_normalized) tape.writeArray(energy_level_encoded, index) index += config.ENERGY_LEVEL_ENCODING_LENGTH food_level_normalized = food_level / config.FOOD_LEVEL_VALUE_MAX food_level_encoded = encode.encode2_8(food_level_normalized) tape.writeArray(food_level_encoded, index) index += config.FOOD_LEVEL_ENCODING_LENGTH distance_normalized = distance / config.DISTANCE_VALUE_MAX distance_encoded = encode.encode2_8(distance_normalized) tape.writeArray(distance_encoded, index) def debug(self): print "Energy level: ", self.energy_level
def test_init(): s1 = State() s2 = State() tm = TuringMachine("ab", s1, s2, s1) assert tm.tape == ['a', 'b', '_'] assert tm.accept_state == s1 assert tm.reject_state == s2 assert tm.current_state == s1
def _read_file(file): with open(file, 'r') as f: #The first line should consist of the word 'state' and then an integer number_states = _parse_state_number(f.readline()) #The next number_states lines are states states, inital_state, accept_state, reject_state = _parse_states(number_states, f) #That is then followed by the input alphabet alphabet = _parse_alphabet(f.readline()) #Add the transitions to the states _parse_transitions(f, alphabet, states) #Add these states to the TM return TuringMachine("", accept_state, reject_state, inital_state, EMPTY_SYMBOL)
def main(): """Main method opens the input file, creates a turing machine with the program file, and then runs the turing machine on the lines in the input file""" infile = open(infilename) # Creates a turing machine with the instructions from the given file turing_machine = TuringMachine(programfilename) turing_machine.print_header() # for each line in the input file it will run the turing machine for line in infile: # Remove whitespace from line line = line.strip() # Convert line to a list tape = list(line) # Run the turing machine on the tape turing_machine.run(tape) turing_machine.print_footer() infile.close()
def main(): initial_state = "init", accepting_states = ["final"], transition_function = {("init","0"):("init", "1", "R"), ("init","1"):("init", "0", "R"), ("init"," "):("final"," ", "N"), } final_states = {"final"} tm = TuringMachine("010011 ", initial_state = initial_state, final_states = final_states, transition_function=transition_function) print("Input on Tape:{}\n".format(tm.get_tape())) while not tm.final(): tm.step() print("Result of the Turing machine calculation:") print(tm.get_tape())
def parseTuringMachine(self, infile): '''Parses a Turing machine from an XML file Args: infile(str): name of an XML input file Returns: A TuringMachine ''' ep = ET.parse(infile) tm = ep.getroot() # self.alphabet = tm.find("alphabet").text # self.initialtape = tm.find("initialtape").text # self.blank = tm.find("blank").attrib['char'] self.initialstate = tm.find("initialstate").attrib['name'] self.finalstates=set() fs=tm.findall("finalstates/finalstate") for state in fs: self.finalstates.add(state.attrib['name']) self.tm = TuringMachine(self.alphabet, self.initialstate, self.initialtape, self.finalstates, self.blank) states = tm.findall("states/state") for state in states: statename = state.attrib['name'] stateobj = State() transitions = state.findall("transition") for transition in transitions: stateobj.add_transition(transition.attrib['seensym'], transition.attrib['writesym'], transition.attrib['newstate'], transition.attrib['move']) self.tm.addstate(statename, stateobj) self.draw(infile)
from turingmachine import TuringMachine utm = TuringMachine() # s in out mov s utm.add_transition(0, "&", "&", "R", 1) # Default init transition utm.add_transition(1, "a", "a", "R", 1) utm.add_transition(1, "b", "a", "R", 1) utm.add_transition(1, "&", "&", "L", 'h') for step in utm.execute("ababababaaa", 0, 'h'): print step a = raw_input("Press any key to continue.")
def updateTM(self): self.tm = TuringMachine(self.alphabet, self.initialstate, self.initialtape, self.finalstates, self.blank)
class GeneralOptions(BoxLayout): set_state = False final_states = False add_transitions = False translation = ListProperty(None) alphabet = '' initialstate = '' initialtape = '' finalstates = set() blank = 'b' tm = TuringMachine(alphabet, initialstate, initialtape, finalstates, blank) nameCounter = 0 transitionCounter = 0 transitions = {} keyNum = 0 transInfo = [] ##This method will change the color of states, it uses negative indices. Just pass it the ID of the state that you # want changes and it will display it as a start/initial state! def change_state_color_to_initial(self,stateId): #increment the state ID for accessing list purposes colour_id = stateId + 1 + self.transitionCounter #define ds to equal the drawing space ds = self.drawing_space #check is valid if self.check_id_valid_for_accessing_ds(colour_id,ds) == True: if not self.initialstate: self.initialstate = colour_id ds.children[-colour_id].change_color_please("green") else: ds.children[-self.initialstate].change_color_please("white") ds.children[-colour_id].change_color_please("green") self.initialstate = colour_id ##This method will change the color of states, it uses negative indices. Just pass it the ID of the state that you # want changes and it will display it as a final/accepting state! def change_state_color_to_final(self,stateId): #increment the state ID for accessing list purposes colour_id = stateId + 1 + self.transitionCounter #define ds to equal the drawing space ds = self.drawing_space #check is valid if self.check_id_valid_for_accessing_ds(colour_id,ds) == True: ds.children[-colour_id].change_color_please("red") ##Checks that the state ID that was passed in is a valid ID and it is actually part of the list. If not no action # will be taken def check_id_valid_for_accessing_ds(self,colour_id,ds): #checks the length and makes sure that the requested state exists if len(ds.children) > 0 and colour_id <= len(ds.children)-self.transitionCounter: return True else: return False def get_state_rep_location(self,stateId): #increment the state ID for accessing list purposes colour_id = stateId + self.transitionCounter + 1 #define ds to equal the drawing space ds = self.drawing_space #check is valid if self.check_id_valid_for_accessing_ds(colour_id,ds) == True: final = (ds.children[-colour_id].get_local()) final.append(stateId) return final def add_state(self): state = State() self.tm.addstate(str(self.nameCounter), state) self.nameCounter += 1 def run_tm(self): '''Run the machine to completion. Prints an execution trace Returns: nothing ''' print "initial state=", self.tm.currentstate print "initial tape=", self.tm.gettape() print " " steps = 0 sb = self.parent.status_bar if sb.paused == True: self.step_tm() return while self.tm.step(): steps += 1 print "steps = ", steps print "state = ", self.tm.currentstate print "tape = ", self.tm.gettape() print " " if int(self.tm.currentstate) in self.tm.finalstates: self.halted = "halted with answer yes" else: self.halted = "halted with answer no" self.finaltape = self.tm.gettape() sb.finished(self.halted, self.finaltape) # This method will be called to step though a turing machine --- Still to implement def step_tm(self): #TODO : still need to write the method in the turingMachine.py and call it below. sb = self.parent.status_bar if self.tm.step() == True: sb.stepthrough(self.tm.currentstate, self.tm.gettape()) else: if int(self.tm.currentstate) in self.tm.finalstates: self.halted = "halted with answer yes" else: self.halted = "halted with answer no" sb.finished(self.tm.halted, self.tm.finaltape) # def clear(self, instance): # self.drawing_space.clear_widgets() def set_alphabet(self,alphabet): self.tm.set_alphabet_in_TM(alphabet) def set_tape(self,tape): self.tm.set_tape_in_TM(tape) def collect_trans_info(self,value,counter,current_state_name): self.transInfo.append(value) if counter == 4: self.parent.tool_box.tool_transition.draw_transition(current_state_name, self.transInfo, self.transitionCounter) self.tm.states[current_state_name].add_transition(self.transInfo[0],self.transInfo[1],self.transInfo[2],self.transInfo[3]) self.transInfo = [] #This class removes the last State to be made (Pops it if you think like a stack data structure) def remove(self, instance): ds = self.drawing_space if len(ds.children) > 0: self.tm.removestate(str(ds.children[0].stateName)) ds.remove_widget(ds.children[0]) self.nameCounter -= 1 def set_initialstate(self, instance, value): if value == 'down': self.set_state = True else: self.set_state = False def set_finalstates(self, instance, value): if value == 'down': self.final_states = True else: self.final_states = False def new_machine(self, instance): self.turing_creator.manager.current = 'titlescreen' def set_initialtape(self, instance): p = TapePopup() p.bind(on_dismiss=self.tape_callback) p.open() popup = AlphabetPopup() popup.bind(on_dismiss=self.alphabet_callback) popup.open() def tape_callback(self, instance): self.initialtape = instance.getInfo() self.tm.set_alphabet_in_TM(self.alphabet) self.tm.set_tape_in_TM(self.initialtape, self.blank) #HERE WE ADD IN CHARACTER TO THE TM depending on the tape input copyOfTape = "".join(set(self.initialtape)) copyOfTape = sorted(copyOfTape) copyOfAlphabet = sorted(self.alphabet) for x in copyOfTape: if x not in copyOfAlphabet: copyOfAlphabet.append(x) # we added a new character to the alphabet stringAlphabet = "".join(copyOfAlphabet) self.tm.set_alphabet_in_TM(stringAlphabet) return False def alphabet_callback(self, instance): self.alphabet = instance.getInfo() print self.alphabet return False def newTM(self): """ Resets the TM in general_options Args: None Returns: None """ #TODO WE need to check the user's input (No spaces or what ever) #TODO I've ran into a Kivy bug on clear_widgets() # Exception IndexError: 'list index out of range' in 'kivy.properties.observable_list_dispatch' ignored # Has something to do with the transitions existing after the state has been deleted self.alphabet = '' self.initialstate = '' self.initialtape = '' self.finalstates = set() self.blank = 'b' self.nameCounter = 0 self.transInfo = [] self.updateTM() self.transitionCounter = 0 self.transitions = {} self.keyNum = 0 self.drawing_space.delete_transitions() self.drawing_space.clear_widgets() def unselect_all(self): for child in self.drawing_space.children: child.unselect() def on_translation(self,instance,value): dsc = self.drawing_space.children for child in dsc: if child.selected: child.translate(*self.translation) def updateTM(self): self.tm = TuringMachine(self.alphabet, self.initialstate, self.initialtape, self.finalstates, self.blank) def test(self): print self.alphabet print self.tm.states print self.tm.gettape() def parseTuringMachine(self, infile): '''Parses a Turing machine from an XML file Args: infile(str): name of an XML input file Returns: A TuringMachine ''' ep = ET.parse(infile) tm = ep.getroot() # self.alphabet = tm.find("alphabet").text # self.initialtape = tm.find("initialtape").text # self.blank = tm.find("blank").attrib['char'] self.initialstate = tm.find("initialstate").attrib['name'] self.finalstates=set() fs=tm.findall("finalstates/finalstate") for state in fs: self.finalstates.add(state.attrib['name']) self.tm = TuringMachine(self.alphabet, self.initialstate, self.initialtape, self.finalstates, self.blank) states = tm.findall("states/state") for state in states: statename = state.attrib['name'] stateobj = State() transitions = state.findall("transition") for transition in transitions: stateobj.add_transition(transition.attrib['seensym'], transition.attrib['writesym'], transition.attrib['newstate'], transition.attrib['move']) self.tm.addstate(statename, stateobj) self.draw(infile) def draw(self, filename): """ Draws the states and transitions from an XML file Args: filename(str): name of an XML input file Returns: Nothing """ ds = self.drawing_space ep = ET.parse(filename) tm = ep.getroot() transInfo = [] states = tm.findall("states/state") print states # adding state objects first because they are used as location references for transitions for x in xrange(0,len(states)): sm = StateRep(width=48, height=48) coordinates = tm.findall("./ds_children/state_coordinates[@ID='%s']" % str(x)) (x,y) = (float(coordinates[0].attrib['x']), float( coordinates[0].attrib['y'])) sm.center = (x,y) ds.add_widget(sm) ds.children[0].set_state(self.nameCounter) self.nameCounter += 1 # now adding transition for state in states: statename = state.attrib['name'] transitions = state.findall("transition") for transition in transitions: transInfo.append(transition.attrib['seensym']) transInfo.append(transition.attrib['writesym']) transInfo.append(transition.attrib['newstate']) transInfo.append(transition.attrib['move']) self.parent.tool_box.tool_transition.draw_transition(statename, transInfo, self.transitionCounter) transInfo = []
def main(): options = parse_args() if options.explain: with open(options.explain) as f: program = json.load(f) print("==== \033[1mExpected tape input format:\033[0m ==== ") print(program.get('tape-format', '<not provided>')) print() print("==== \033[1mExpected tape output format:\033[0m ====") print(program.get('output-format', '<not provided>')) return program = Program.from_file(options.program) tape = [i for i in options.tape] if options.accepts: print( TuringMachine.accepts(program, tape, error_on_eot=not options.infinite, verbose=not options.quiet)) return machine = TuringMachine(program, tape, err_on_eot=not options.infinite, verbose=not options.quiet) if options.ensuretransitions: machine.ensure_transitions() print("Machine start!") print("Tape output (without blanks)") machine.print_tape_trimmed() if not options.quiet: print("\nBeginning simulation...") machine.run() print('\nFinished!') print("Tape output (without blanks)") machine.print_tape_trimmed()
def test_updating_tape(): q0, q1, qa, qr = create_example_from_spec() tm = TuringMachine("aab", qa, qr, q0) assert tm.begin() tm.new_tape("aba") assert tm.begin() is False
def test_example_spec_aba(): q0, q1, qa, qr = create_example_from_spec() tm = TuringMachine('aba', qa, qr, q0) assert tm.begin() == False
def test_example_spec_aab_manually(): q0, q1, qa, qr = create_example_from_spec() tm = TuringMachine('aab', qa, qr, q0) assert tm.tape == ['a', 'a', 'b', '_'] #tm.begin() tm._read('a') assert tm.tape_position == 1 assert tm.current_state == q0 tm._read('a') assert tm.tape_position == 2 assert tm.current_state == q0 tm._read('b') assert tm.tape_position == 3 assert tm.tape == ['a', 'a', 'b', '_'] assert tm.current_state == q1 tm._read('_') assert tm.tape_position == 2 assert tm.tape == ['a', 'a', 'b', 'b', '_'] assert tm.current_state == qa assert tm.accept()
def __init__(self): self._Turing = TuringMachine()
print("Invalid input string.") exit() initial_state = "q_0" final_states = ["q_acc", "q_rej"] # transition functions transition_function = { ("q_0", "a"): ("q_0", "a", "R"), # stay in q_0 ("q_0", "b"): ("q_1", "b", "R"), # transition to q_1 when 'b' is encountered ("q_0", "*"): ("q_rej", "*", "L"), # no 'b's found and we reached the end. Reject and halt. ("q_1", "a"): ("q_1", "a", "R"), # stay in q_1 ("q_1", "b"): ("q_acc", "b", "R"), # encountered second 'b'! Accept and halt. ("q_1", "*"): ("q_rej", "*", "L") # only 1 'b' found. Reject and halt. } turing = TuringMachine(alphabet, input_string, "*", initial_state, final_states, transition_function) # step through Turing machine until a final state is reached. while not turing.final_state(): turing.step() if turing.current_state == "q_acc": print(f"String {input_string} is accepted") else: print(f"String {input_string} is rejected")