def testCheckWords(self): a = Automaton() a.txtToAutomaton("media/automata/eq1.txt") wordlist = [["0", "1", "0", "0"], ["0"], ["0", "1", "0", "1"]] self.assertDictEqual( { 'accepted': [['0', '1', '0', '0']], 'rejected': [['0'], ['0', '1', '0', '1']] }, a.checkWords(wordlist))
def testCheckEquivalence_equal(self): a1 = Automaton() a1.txtToAutomaton("media/automata/eq1.txt") a2 = Automaton() a2.txtToAutomaton("media/automata/eq2.txt") self.assertTrue(a1.checkEquivalence(a2))
def testCheckEquivalence_noEqual(self): a1 = Automaton() a1.txtToAutomaton("media/automata/eq1.txt") a2 = Automaton() a2.txtToAutomaton("media/automata/nfa.txt") self.assertFalse(a1.checkEquivalence(a2))
def testTxtToAutomaton(self): automaton = Automaton() automaton.txtToAutomaton("media/automata/eq1.txt") self.assertEqual('EQ1', automaton.name) self.assertListEqual(automaton.alphabet, ['0', '1']) self.assertListEqual(automaton.states, ['q0', 'q1', 'q2']) self.assertEqual(automaton.startState, "q0") self.assertListEqual(automaton.finalStates, ['q2']) self.assertListEqual( automaton.tFunction, [['q0', '0', 'q0'], ['q0', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1'], ['q1', '0', 'q1'], ['q1', '1', 'q2']])
def __generate_automaton__(self): automaton = Automaton( alphabet=self.__arrOfAlphaAuto, states=[Vertice(state) for state in self.__arrState], nmbOfStates=self.__nmbOfStates, initial_state=Vertice(self.__start), final_states=[Vertice(state) for state in self.__ends]) for transition in self.__matrixOfLines: automaton.add_transition( Aresta(vertice_inicio=Vertice(transition[0]), vertice_fim=Vertice(transition[2]), id=transition[1])) return automaton
def testNfaToDfa(self): nfa = Automaton() nfa.txtToAutomaton("media/automata/nfa.txt") dfa = nfa.nfaToDfa() self.assertEqual('EQ1', dfa.name) self.assertListEqual(dfa.alphabet, ['0', '1']) self.assertListEqual(dfa.states, ['A', 'A_B', 'A_B_C']) self.assertEqual(dfa.startState, "A") self.assertListEqual(dfa.finalStates, ['A_B_C']) self.assertListEqual( dfa.tFunction, [['A', '0', 'A_B'], ['A', '1', 'A'], ['A_B', '0', 'A_B_C'], ['A_B', '1', 'A'], ['A_B_C', '0', 'A_B_C'], ['A_B_C', '1', 'A']])
def testMinAutomaton(self): a = Automaton() a.txtToAutomaton("media/automata/minimal/dfa.txt") a = a.minAutomaton() self.assertEqual('EQ1', a.name) self.assertListEqual(a.alphabet, ['a', 'b']) self.assertListEqual(a.states, ['q0', 'q1', 'q2_q3', 'q4_q5']) self.assertEqual(a.startState, "q0") self.assertListEqual(a.finalStates, ['q0', 'q4_q5']) self.assertListEqual( a.tFunction, [['q0', 'a', 'q2_q3'], ['q0', 'b', 'q1'], ['q1', 'a', 'q1'], ['q1', 'b', 'q0'], ['q2_q3', 'a', 'q4_q5'], ['q2_q3', 'b', 'q4_q5'], ['q4_q5', 'a', 'q2_q3'], ['q4_q5', 'b', 'q2_q3']])
def testRemoveUnreachableStates(self): a = Automaton() a.txtToAutomaton("media/automata/uselessState.txt") a.removeUnreachableStates() self.assertEqual('EQ1', a.name) self.assertListEqual(a.alphabet, ['0', '1']) self.assertListEqual(a.states, ['q0', 'q1', 'q2']) self.assertEqual(a.startState, "q0") self.assertListEqual(a.finalStates, ['q2']) self.assertListEqual( a.tFunction, [['q0', '0', 'q0'], ['q0', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1'], ['q1', '0', 'q1'], ['q1', '1', 'q2']])
def testConvertDFAToTtf(self): a = Automaton() a.txtToAutomaton("media/automata/noTotal.txt") a.convertDFAToTtf() self.assertEqual('A', a.name) self.assertListEqual(a.alphabet, ['a', 'b']) self.assertListEqual(a.states, ['q0', 'q1', 'q2', 'qf', '&&']) self.assertEqual(a.startState, "q0") self.assertListEqual(a.finalStates, ['qf']) self.assertListEqual( a.tFunction, [['q0', 'a', 'q1'], ['q0', 'b', 'q0'], ['q1', 'a', 'q2'], ['q1', 'b', '&&'], ['q2', 'a', 'qf'], ['q2', 'b', '&&'], ['qf', 'a', '&&'], ['qf', 'b', '&&'], ['&&', 'a', '&&'], ['&&', 'b', '&&']])
def afneToAFN(self): self.compute_e_closures() d = dict() F = set() for state in self.Q: # Definindo d' d[state] = [] for symbol in self.sigma: temp = [] for reachable in self.e_closure_table[state]: # Definindo F' (aproveitando o loop pelos e_closure) if reachable in self.F: F.add(state) for trans in self.delta[reachable]: if trans[0] == symbol: temp.append(self.e_closure_table[trans[1]]) break tempset = set().union(*temp) if tempset: d[state].append((symbol, tempset)) F = list(F) return Automaton(self.sigma, self.Q, d, self.ini, F)
class PushDownAutomaton(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.Automaton = Automaton() # Creating a Input_String class instance self.Strings = Input_Strings() # A attribute to remeber the def_path self.def_path = '' # A attribute to remeber if the automaton was opened self.automaton_open = False self.setWindowTitle("Pushdown Automaton") self.resize(640, 480) self.mainMenu = self.menuBar() self.fileMenu = self.mainMenu.addMenu("File") self.fileMenu.addAction("Open Automaton", self.open_automaton_action) self.fileMenu.addAction("View Automaton", self.view_automaton_action) self.helpMenu = self.mainMenu.addMenu("Help") self.helpMenu.addAction("User Manual", self.user_manual_action) self.inputStringLabel = QLabel(self) self.inputStringLabel.setGeometry(20, 40, 111, 16) self.inputStringLabel.setText("Input String") self.inputStringLineEdit = QLineEdit(self) self.inputStringLineEdit.setGeometry(20, 60, 231, 20) self.addToListPushButton = QPushButton(self) self.addToListPushButton.setGeometry(80, 90, 111, 23) self.addToListPushButton.setText("Add to List") self.addToListPushButton.clicked.connect(self.add_to_list_clicked) self.inputStringListLabel = QLabel(self) self.inputStringListLabel.setGeometry(20, 125, 111, 16) self.inputStringListLabel.setText("Input String List") self.inputStringListWidget = QListWidget(self) self.inputStringListWidget.setGeometry(20, 145, 231, 260) self.runStringPushButton = QPushButton(self) self.runStringPushButton.setGeometry(80, 415, 111, 23) self.runStringPushButton.setText("Run String") self.runStringPushButton.clicked.connect(self.run_string_clicked) self.outputLabel = QLabel(self) self.outputLabel.setGeometry(300, 40, 47, 16) self.outputLabel.setText("Output") self.sequencesLabel = QLabel(self) self.sequencesLabel.setGeometry(390, 40, 51, 16) self.sequencesLabel.setText("Sequences") self.sequencesSpinBox = QSpinBox(self) self.sequencesSpinBox.setGeometry(450, 37, 42, 20) self.sequencesSpinBox.setMinimum(1) #access value with self.sequencesSpinBox.value self.displayPathsCheckBox = QCheckBox(self) self.displayPathsCheckBox.setGeometry(530, 40, 101, 17) self.displayPathsCheckBox.setText("Display Paths") #access true or false with self.displayPathsCheckBox.checked self.outputPlainTextEdit = QPlainTextEdit(self) self.outputPlainTextEdit.setGeometry(300, 60, 311, 346) self.quitRunningStringPushButton = QPushButton(self) self.quitRunningStringPushButton.setGeometry(335, 415, 111, 23) self.quitRunningStringPushButton.setText("Quit Running String") self.quitRunningStringPushButton.clicked.connect(self.quit_running_string_clicked) self.closeAutomatonPushButton = QPushButton(self) self.closeAutomatonPushButton.setGeometry(465, 415, 111, 23) self.closeAutomatonPushButton.setText("Close Automaton") self.closeAutomatonPushButton.clicked.connect(self.close_automaton_clicked) # Style for status label text self.styleError = 'font: 15pt Arial; color: maroon' self.styleNormal = 'font:15pt Arial; color: white' self.statusBar = self.statusBar() self.statusLabel = QLabel("application status messages will go here (when something completes, etc.)") self.statusLabel.setStyleSheet(self.styleNormal) self.statusBar.addPermanentWidget(self.statusLabel) self.show() def parseConfigFile(self): #TODO: handle the values from the config file at the start of execution return def parseInputStringFile(self, file_path): # If the input string widget is empty add the input strings to the widget if self.inputStringListWidget.count() == 0: # Loading the string into the Strings attribute input_strings self.Strings.load(file_path) for string in self.Strings.input_strings: # Add the string to the widget self.inputStringListWidget.addItem(string) else: # If there are already string in the widget do nothing # strings have already been parsed. pass return # A method to update the input string widget def update_input_string_widget(self): self.inputStringListWidget.clear() for string in self.Strings.input_strings: self.inputStringListWidget.addItem(string) def open_automaton_action(self): self.outputPlainTextEdit.setPlainText("Open Automaton Clicked") # Save the location of the def file self.def_path = 'pda.def' #self.def_path = 'invalid_pda.def' # Check if the defintion file is valid valid_def = Validate_Def_File(self.def_path) if valid_def.def_valid == True: # Load the Automaton self.Automaton.load(self.def_path) # Set def path to the status bar self.statusLabel.setText(self.def_path) # Now parse config file self.parseConfigFile() # Now parse the input strings self.parseInputStringFile(self.def_path) else: error_list = [] error_list = valid_def.is_invalid_def() for item in error_list: self.outputPlainTextEdit.appendPlainText(item) return def view_automaton_action(self): self.outputPlainTextEdit.setPlainText("View Automaton Clicked") file = open(self.def_path, 'r') for line in file: self.outputPlainTextEdit.appendPlainText(line) return def user_manual_action(self): QMessageBox.about(self, 'User Manual', 'Help List Goes here') return def add_to_list_clicked(self): # If the user just clicks add string if(self.inputStringLineEdit.text() == ''): return if self.Strings.is_duplicate(self.inputStringLineEdit.text()) == True: status = self.inputStringLineEdit.text() + ' is a duplicate string' self.statusLabel.setText(status) self.statusLabel.setStyleSheet(self.styleError) self.inputStringLineEdit.clear() return if self.Strings.validate(self.Automaton.Input_Alpha.alphabet, self.inputStringLineEdit.text()) == True: self.Strings.add_input_string(self.Automaton.Input_Alpha.alphabet, self.inputStringLineEdit.text()) self.update_input_string_widget() # Make new string the selected string self.inputStringListWidget.setCurrentRow((self.inputStringListWidget.count() - 1)) self.inputStringLineEdit.clear() self.statusLabel.setStyleSheet(self.styleNormal) self.statusLabel.setText('') else: status = self.inputStringLineEdit.text() + ' is not a valid string' self.statusLabel.setText(status) self.statusLabel.setStyleSheet(self.styleError) self.update_input_string_widget() self.inputStringLineEdit.clear() return def run_string_clicked(self): self.outputPlainTextEdit.setPlainText("Run String Button Clicked") self.statusLabel.setText('Running on string: aba') self.outputPlainTextEdit.appendPlainText('[s0]aba') self.outputPlainTextEdit.appendPlainText('[s1]ba') return def quit_running_string_clicked(self): self.outputPlainTextEdit.clear() self.outputPlainTextEdit.setPlainText("Quit Running String Button Clicked") return def close_automaton_clicked(self): self.outputPlainTextEdit.clear() self.inputStringListWidget.clear() self.statusLabel.clear() self.outputPlainTextEdit.setPlainText("Close Automaton Button Clicked") return
def initUI(self): self.Automaton = Automaton() # Creating a Input_String class instance self.Strings = Input_Strings() # A attribute to remeber the def_path self.def_path = '' # A attribute to remeber if the automaton was opened self.automaton_open = False self.setWindowTitle("Pushdown Automaton") self.resize(640, 480) self.mainMenu = self.menuBar() self.fileMenu = self.mainMenu.addMenu("File") self.fileMenu.addAction("Open Automaton", self.open_automaton_action) self.fileMenu.addAction("View Automaton", self.view_automaton_action) self.helpMenu = self.mainMenu.addMenu("Help") self.helpMenu.addAction("User Manual", self.user_manual_action) self.inputStringLabel = QLabel(self) self.inputStringLabel.setGeometry(20, 40, 111, 16) self.inputStringLabel.setText("Input String") self.inputStringLineEdit = QLineEdit(self) self.inputStringLineEdit.setGeometry(20, 60, 231, 20) self.addToListPushButton = QPushButton(self) self.addToListPushButton.setGeometry(80, 90, 111, 23) self.addToListPushButton.setText("Add to List") self.addToListPushButton.clicked.connect(self.add_to_list_clicked) self.inputStringListLabel = QLabel(self) self.inputStringListLabel.setGeometry(20, 125, 111, 16) self.inputStringListLabel.setText("Input String List") self.inputStringListWidget = QListWidget(self) self.inputStringListWidget.setGeometry(20, 145, 231, 260) self.runStringPushButton = QPushButton(self) self.runStringPushButton.setGeometry(80, 415, 111, 23) self.runStringPushButton.setText("Run String") self.runStringPushButton.clicked.connect(self.run_string_clicked) self.outputLabel = QLabel(self) self.outputLabel.setGeometry(300, 40, 47, 16) self.outputLabel.setText("Output") self.sequencesLabel = QLabel(self) self.sequencesLabel.setGeometry(390, 40, 51, 16) self.sequencesLabel.setText("Sequences") self.sequencesSpinBox = QSpinBox(self) self.sequencesSpinBox.setGeometry(450, 37, 42, 20) self.sequencesSpinBox.setMinimum(1) #access value with self.sequencesSpinBox.value self.displayPathsCheckBox = QCheckBox(self) self.displayPathsCheckBox.setGeometry(530, 40, 101, 17) self.displayPathsCheckBox.setText("Display Paths") #access true or false with self.displayPathsCheckBox.checked self.outputPlainTextEdit = QPlainTextEdit(self) self.outputPlainTextEdit.setGeometry(300, 60, 311, 346) self.quitRunningStringPushButton = QPushButton(self) self.quitRunningStringPushButton.setGeometry(335, 415, 111, 23) self.quitRunningStringPushButton.setText("Quit Running String") self.quitRunningStringPushButton.clicked.connect(self.quit_running_string_clicked) self.closeAutomatonPushButton = QPushButton(self) self.closeAutomatonPushButton.setGeometry(465, 415, 111, 23) self.closeAutomatonPushButton.setText("Close Automaton") self.closeAutomatonPushButton.clicked.connect(self.close_automaton_clicked) # Style for status label text self.styleError = 'font: 15pt Arial; color: maroon' self.styleNormal = 'font:15pt Arial; color: white' self.statusBar = self.statusBar() self.statusLabel = QLabel("application status messages will go here (when something completes, etc.)") self.statusLabel.setStyleSheet(self.styleNormal) self.statusBar.addPermanentWidget(self.statusLabel) self.show()
def test_vivos_nao_deterministico(self): from Automaton import Automaton at = Automaton() at.set_alphabet(("a","b","c")) at.set_states(("S","A","B","C","F")) a = at.set_initial_state("S") at.set_final_states(("S","F")) at.add_transition("S","a","A") at.add_transition("S","b","B") at.add_transition("S","b","F") at.add_transition("S","c","S") at.add_transition("S","c","F") at.add_transition("A","a","S") at.add_transition("A","a","F") at.add_transition("A","b","C") at.add_transition("A","c","A") at.add_transition("B","a","A") at.add_transition("B","c","S") at.add_transition("B","c","B") at.add_transition("B","c","F") at.add_transition("C","a","S") at.add_transition("C","a","F") at.add_transition("C","c","A") at.add_transition("C","c","C") self.finite_automaton = at.determinizar() alcancaveis = self.finite_automaton._achievable_states() self.assertEqual(self.finite_automaton._live_states(alcancaveis),{"S","A","BF","FS","C","BFS","AC"})
def test_minimiza_retorna_classes_para_novo_automato_nao_deterministico(self): from Automaton import Automaton fa = Automaton() fa.set_alphabet(('a','b')) fa.set_states(('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')) fa.set_initial_state('A') fa.set_final_states(('A','D','G')) fa.add_transition('A', 'a', 'G') fa.add_transition('A', 'b', 'B') fa.add_transition('B', 'a', 'F') fa.add_transition('B', 'b', 'E') fa.add_transition('C', 'a', 'C') fa.add_transition('C', 'b', 'G') fa.add_transition('D', 'a', 'A') fa.add_transition('D', 'b', 'H') fa.add_transition('E', 'a', 'E') fa.add_transition('E', 'b', 'A') fa.add_transition('F', 'a', 'B') fa.add_transition('F', 'b', 'C') fa.add_transition('G', 'a', 'G') fa.add_transition('G', 'b', 'F') fa.add_transition('H', 'a', 'H') fa.add_transition('H', 'b', 'D') self.finite_automaton = fa.determinizar() achievable = self.finite_automaton._achievable_states() live_states = self.finite_automaton._live_states(achievable) self.assertEqual(self.finite_automaton.minimize(live_states), [['A', 'G'], ['B', 'F'], ['C', 'E']])
def testIsFinal_final(self): a = Automaton() a.txtToAutomaton("media/automata/eq1.txt") self.assertTrue(a.isFinal("q2"))
class PushDownAutomaton(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): # Creating an Automaton class instance self.Automaton = Automaton() # Creating a Input_String class instance self.Strings = Input_Strings() # Creating a Configuration_Setting instance self.Config_Setting = Configuration_Settings() # A attribute to remember the def_path self.def_path = '' # A attribute to remember if the automaton was opened self.automaton_open = False self.setWindowTitle("Pushdown Automaton") self.resize(640, 480) self.mainMenu = self.menuBar() self.fileMenu = self.mainMenu.addMenu("File") self.fileMenu.addAction("Open Automaton Ctrl+O", self.open_automaton_action) self.openShorcut = QShortcut(QKeySequence("Ctrl+O"), self) self.openShorcut.activated.connect(self.open_automaton_action) #self.fileMenu.addAction("View Automaton", self.view_automaton_action) self.fileMenu.addAction("Quit Ctrl+Shift+Q", self.quit_action) self.quitAppShorcut = QShortcut(QKeySequence("Ctrl+Shift+Q"), self) self.quitAppShorcut.activated.connect(self.quit_action) self.helpMenu = self.mainMenu.addMenu("Help") self.helpMenu.addAction("User Manual Ctrl+H", self.user_manual_action) self.userManualShorcut = QShortcut(QKeySequence("Ctrl+H"), self) self.userManualShorcut.activated.connect(self.user_manual_action) self.inputStringLabel = QLabel(self) self.inputStringLabel.setGeometry(20, 40, 111, 16) self.inputStringLabel.setText("Input String") self.inputStringLineEdit = QLineEdit(self) self.inputStringLineEdit.setGeometry(20, 60, 231, 20) self.addToListPushButton = QPushButton(self) self.addToListPushButton.setGeometry(80, 90, 111, 23) self.addToListPushButton.setText("Add to List") self.addToListPushButton.clicked.connect(self.add_to_list_clicked) self.addToListShorcut = QShortcut(QKeySequence("Ctrl+Shift+A"), self) self.addToListShorcut.activated.connect(self.add_to_list_clicked) self.addToListPushButton.setToolTip("Ctrl+Shift+A") self.inputStringListLabel = QLabel(self) self.inputStringListLabel.setGeometry(20, 125, 111, 16) self.inputStringListLabel.setText("Input String List") self.inputStringListWidget = QListWidget(self) self.inputStringListWidget.setGeometry(20, 145, 231, 260) self.runStringPushButton = QPushButton(self) self.runStringPushButton.setGeometry(80, 415, 111, 23) self.runStringPushButton.setText("Run String") self.runStringPushButton.clicked.connect(self.run_string_clicked) self.runStringShorcut = QShortcut(QKeySequence("Ctrl+R"), self) self.runStringShorcut.activated.connect(self.run_string_clicked) self.runStringPushButton.setToolTip("Ctrl+R") self.fileNameLabel = QLabel(self) self.fileNameLabel.setGeometry(440, 40, 160, 16) self.fileNameLabel.setText("Automaton Title") self.fileNameLabel.setStyleSheet("color: blue") self.outputLabel = QLabel(self) self.outputLabel.setGeometry(300, 60, 47, 16) self.outputLabel.setText("Output") self.maxTransitionsLabel = QLabel(self) self.maxTransitionsLabel.setGeometry(370, 60, 80, 16) self.maxTransitionsLabel.setText("Max. Transitions") self.maxTransitionsSpinBox = QSpinBox(self) self.maxTransitionsSpinBox.setGeometry(455, 57, 42, 20) self.maxTransitionsSpinBox.setMinimum(1) #access value with self.maxTransitionsSpinBox.value self.displayPathsCheckBox = QCheckBox(self) self.displayPathsCheckBox.setGeometry(530, 60, 101, 17) self.displayPathsCheckBox.setText("Display Paths") #access true or false with self.displayPathsCheckBox.checked self.outputPlainTextEdit = QPlainTextEdit(self) self.outputPlainTextEdit.setGeometry(300, 80, 271, 253) #300, 80, 281, 283 self.stackPlainTextEdit = QPlainTextEdit(self) self.stackPlainTextEdit.setGeometry(581, 80, 30, 253) self.pathLabel = QLabel(self) self.pathLabel.setGeometry(300, 335, 47, 16) self.pathLabel.setText("Path") self.pathPlainTextEdit = QPlainTextEdit(self) self.pathPlainTextEdit.setGeometry(300, 355, 311, 50) self.quitRunningStringPushButton = QPushButton(self) self.quitRunningStringPushButton.setGeometry(335, 415, 111, 23) self.quitRunningStringPushButton.setText("Quit Running String") self.quitRunningStringPushButton.clicked.connect( self.quit_running_string_clicked) self.quitRunningStringShorcut = QShortcut(QKeySequence("Ctrl+Q"), self) self.quitRunningStringShorcut.activated.connect( self.quit_running_string_clicked) self.quitRunningStringPushButton.setToolTip("Ctrl+Q") self.closeAutomatonPushButton = QPushButton(self) self.closeAutomatonPushButton.setGeometry(465, 415, 111, 23) self.closeAutomatonPushButton.setText("Close Automaton") self.closeAutomatonPushButton.clicked.connect( self.close_automaton_clicked) self.closeAutomatonShorcut = QShortcut(QKeySequence("Ctrl+Alt+C"), self) self.closeAutomatonShorcut.activated.connect( self.close_automaton_clicked) self.closeAutomatonPushButton.setToolTip("Ctrl+Alt+C") # Style for status label text self.styleError = 'font: 15pt Arial; color: maroon' self.styleNormal = 'font:15pt Arial; color: green' self.statusBar = self.statusBar() self.statusLabel = QLabel( "application status messages will go here (when something completes, etc.)" ) self.statusLabel.setStyleSheet(self.styleNormal) self.statusBar.addPermanentWidget(self.statusLabel) self.show() def parseConfigFile(self, file_path): # Load the config settings self.Config_Setting.load(file_path) # Set the value parsed from the config file to the spinbox self.maxTransitionsSpinBox.setValue( int(self.Config_Setting.max_trans[0])) return def parseInputStringFile(self, file_path): # If the input string widget is empty add the input strings to the widget if self.inputStringListWidget.count() == 0: # Loading the string into the Strings attribute input_strings self.Strings.load(file_path) for string in self.Strings.input_strings: # If the string is valid if self.Strings.validate(self.Automaton.Input_Alpha.alphabet, string) == True: # Add the string to the widget self.inputStringListWidget.addItem(string) return # A method to update the input string widget def update_input_string_widget(self): self.inputStringListWidget.clear() for string in self.Strings.input_strings: self.inputStringListWidget.addItem(string) def quit_action(self): sys.exit(0) def open_automaton_action(self): #self.outputPlainTextEdit.setPlainText("Open Automaton Clicked") # Save the location of the def file self.def_path, _ = QFileDialog.getOpenFileName( self, "Select Definition File", "", ".def files (*.def)") #self.def_path = 'pda.def' #self.invalid_def_path = 'invalid_pda.def' # Check if the defintion file is valid Valid_def = Validate_Def_File(self.def_path) if Valid_def.def_valid == True: # Load the Automaton self.Automaton.load(self.def_path) # Store the the automaton is opened self.automaton_open = True # Set def path to the status bar self.statusLabel.setText(self.def_path) # Now parse config file self.parseConfigFile(self.def_path) # Now parse the input strings self.parseInputStringFile(self.def_path) # Set normal label styling self.statusLabel.setStyleSheet(self.styleNormal) # Change automaton title label self.fileNameLabel.setText(self.def_path.split("/")[-1]) else: error_list = [] error_list = Valid_def.is_invalid_def() for item in error_list: self.outputPlainTextEdit.appendPlainText(item) # Set status label status = self.def_path + " is invalid!" self.statusLabel.setText(status) # Set error label styling self.statusLabel.setStyleSheet(self.styleError) return #def view_automaton_action(self): # self.outputPlainTextEdit.setPlainText("View Automaton Clicked") # file = open(self.def_path, 'r') # for line in file: # self.outputPlainTextEdit.appendPlainText(line) # return def user_manual_action(self): userMan = HelpMenu() userMan.__init__() def add_to_list_clicked(self): # If the user just clicks add string if (self.inputStringLineEdit.text() == ''): return if self.Strings.is_duplicate(self.inputStringLineEdit.text()) == True: status = self.inputStringLineEdit.text() + ' is a duplicate string' self.statusLabel.setText(status) self.statusLabel.setStyleSheet(self.styleError) self.inputStringLineEdit.clear() return if self.Strings.validate(self.Automaton.Input_Alpha.alphabet, self.inputStringLineEdit.text()) == True: self.Strings.add_input_string(self.Automaton.Input_Alpha.alphabet, self.inputStringLineEdit.text()) self.update_input_string_widget() # Make new string the selected string self.inputStringListWidget.setCurrentRow( (self.inputStringListWidget.count() - 1)) self.inputStringLineEdit.clear() self.statusLabel.setStyleSheet(self.styleNormal) self.statusLabel.setText('') else: status = self.inputStringLineEdit.text() + ' is not a valid string' self.statusLabel.setText(status) self.statusLabel.setStyleSheet(self.styleError) self.update_input_string_widget() self.inputStringLineEdit.clear() return def run_string_clicked(self): selected_string = '' if len(self.inputStringListWidget.selectedItems()) > 0: selected_string = self.inputStringListWidget.selectedItems( )[0].text() else: self.statusLabel.setStyleSheet(self.styleError) self.statusLabel.setText('No input string selected') #self.outputPlainTextEdit.setPlainText("Run String Button Clicked") self.Automaton.run_string(selected_string) outputTransitions = self.Automaton.transitions_list outputStack = self.Automaton.stack outputPath = str(outputTransitions[0]) #self.outputPlainTextEdit.setPlainText(outputTransitions) for element in outputTransitions: self.outputPlainTextEdit.setPlainText(str(element)) #self.stackPlainTextEdit.setPlainText(outputStack) #add \n's self.stackPlainTextEdit.setPlainText("") for char in outputStack: self.stackPlainTextEdit.appendPlainText(char) if (self.displayPathsCheckBox.isChecked()): self.pathPlainTextEdit.appendPlainText(outputPath + " -> ") #add ->'s def quit_running_string_clicked(self): self.outputPlainTextEdit.setPlainText( "Quit Running String Button Clicked") return def close_automaton_clicked(self): self.outputPlainTextEdit.clear() self.inputStringListWidget.clear() self.statusLabel.clear() self.outputPlainTextEdit.setPlainText("Close Automaton Button Clicked") return
def run(): exit_program = False init = False af = Automaton() while not exit_program: AutomatonView.printHeader("Choose an option") print("1: Open automaton") if init: print("2: Show automaton") print("3: Check accepted and rejected words") print("4: Generate grammar") print("5: Convert to minimal automaton") print("6: Verify equivalence with another automaton") print("0: Exit\n") AutomatonView.printDiv() op = input("Option: ") AutomatonView.printDiv() if op == '1': AutomatonView.printHeader('Open automaton') exit_option = False # Try to open automaton file filename = AutomatonFileManager.askFilePath( "Open automaton file", "Automaton txt file") out = af.txtToAutomaton(filename) while out == None and exit_option == False: print("Error: Invalid file path") choose = input( "Press 0 to exit or any button to try again: ") if choose == '0': exit_option = True else: filename = AutomatonFileManager.askFilePath( "Open automaton file", "Automaton txt file") out = af.txtToAutomaton(filename) if not exit_option: init = True elif init: if op == '2': af.printAutomaton() AutomatonView.wait() elif op == '3': AutomatonView.printHeader( 'Check accepted and rejected words') exit_option = False filename = AutomatonFileManager.askFilePath( "Open words file", "Words txt file") wordList = AutomatonFileManager.csvToWordList(filename) while wordList == None and exit_option == False: print("Error: Invalid file path") choose = input( "Press 0 to exit or any button to try again: ") if choose == '0': exit_option = True else: filename = AutomatonFileManager.askFilePath( "Open words file", "Words txt file") wordList = AutomatonFileManager.csvToWordList( filename) af.checkWords(wordList) elif op == '4': AutomatonView.printHeader('Generate grammar') #name = AutomatonFile.askSaveFilePath("Save grammar file") name = input( "Enter a name for the file (or '0' to exit): ") if name: af.generateGrammar(name) AutomatonFileManager.printFileContent(name + '.txt') AutomatonView.wait() elif op == '5': print('Converting to minimal automaton...') af = af.minAutomaton() print('Conversion done successfully!') AutomatonView.wait() elif op == '6': AutomatonView.printHeader( 'Verify equivalence with another automaton') af_tmp = Automaton() exit_option = False filename = AutomatonFileManager.askFilePath( "Choose the automaton file to be compared", "Automaton txt file") out = af_tmp.txtToAutomaton(filename) while out == None and exit_option == False: print("Error: Invalid file path") choose = input( "Press 0 to exit or any button to try again: ") if choose == '0': exit_option = True else: filename = AutomatonFileManager.askFilePath( "Choose the automaton file to be compared") out = af_tmp.txtToAutomaton(filename) if not exit_option: out = af.checkEquivalence(af_tmp) if out == True: print("The %s and %s automata are equivalent!" % (af.name, af_tmp.name)) else: print( "The %s and %s automata are not equivalent!" % (af.name, af_tmp.name)) af_tmp.destroy() AutomatonView.wait() if op == '0': exit_program = True if init: af.destroy()
def testTransitionFunction(self): a = Automaton() a.txtToAutomaton("media/automata/eq1.txt") self.assertEqual(["q2"], a.transitionFunction("q0", '1'))
def initUI(self): # Creating an Automaton class instance self.Automaton = Automaton() # Creating a Input_String class instance self.Strings = Input_Strings() # Creating a Configuration_Setting instance self.Config_Setting = Configuration_Settings() # A attribute to remember the def_path self.def_path = '' # A attribute to remember if the automaton was opened self.automaton_open = False self.setWindowTitle("Pushdown Automaton") self.resize(640, 480) self.mainMenu = self.menuBar() self.fileMenu = self.mainMenu.addMenu("File") self.fileMenu.addAction("Open Automaton Ctrl+O", self.open_automaton_action) self.openShorcut = QShortcut(QKeySequence("Ctrl+O"), self) self.openShorcut.activated.connect(self.open_automaton_action) #self.fileMenu.addAction("View Automaton", self.view_automaton_action) self.fileMenu.addAction("Quit Ctrl+Shift+Q", self.quit_action) self.quitAppShorcut = QShortcut(QKeySequence("Ctrl+Shift+Q"), self) self.quitAppShorcut.activated.connect(self.quit_action) self.helpMenu = self.mainMenu.addMenu("Help") self.helpMenu.addAction("User Manual Ctrl+H", self.user_manual_action) self.userManualShorcut = QShortcut(QKeySequence("Ctrl+H"), self) self.userManualShorcut.activated.connect(self.user_manual_action) self.inputStringLabel = QLabel(self) self.inputStringLabel.setGeometry(20, 40, 111, 16) self.inputStringLabel.setText("Input String") self.inputStringLineEdit = QLineEdit(self) self.inputStringLineEdit.setGeometry(20, 60, 231, 20) self.addToListPushButton = QPushButton(self) self.addToListPushButton.setGeometry(80, 90, 111, 23) self.addToListPushButton.setText("Add to List") self.addToListPushButton.clicked.connect(self.add_to_list_clicked) self.addToListShorcut = QShortcut(QKeySequence("Ctrl+Shift+A"), self) self.addToListShorcut.activated.connect(self.add_to_list_clicked) self.addToListPushButton.setToolTip("Ctrl+Shift+A") self.inputStringListLabel = QLabel(self) self.inputStringListLabel.setGeometry(20, 125, 111, 16) self.inputStringListLabel.setText("Input String List") self.inputStringListWidget = QListWidget(self) self.inputStringListWidget.setGeometry(20, 145, 231, 260) self.runStringPushButton = QPushButton(self) self.runStringPushButton.setGeometry(80, 415, 111, 23) self.runStringPushButton.setText("Run String") self.runStringPushButton.clicked.connect(self.run_string_clicked) self.runStringShorcut = QShortcut(QKeySequence("Ctrl+R"), self) self.runStringShorcut.activated.connect(self.run_string_clicked) self.runStringPushButton.setToolTip("Ctrl+R") self.fileNameLabel = QLabel(self) self.fileNameLabel.setGeometry(440, 40, 160, 16) self.fileNameLabel.setText("Automaton Title") self.fileNameLabel.setStyleSheet("color: blue") self.outputLabel = QLabel(self) self.outputLabel.setGeometry(300, 60, 47, 16) self.outputLabel.setText("Output") self.maxTransitionsLabel = QLabel(self) self.maxTransitionsLabel.setGeometry(370, 60, 80, 16) self.maxTransitionsLabel.setText("Max. Transitions") self.maxTransitionsSpinBox = QSpinBox(self) self.maxTransitionsSpinBox.setGeometry(455, 57, 42, 20) self.maxTransitionsSpinBox.setMinimum(1) #access value with self.maxTransitionsSpinBox.value self.displayPathsCheckBox = QCheckBox(self) self.displayPathsCheckBox.setGeometry(530, 60, 101, 17) self.displayPathsCheckBox.setText("Display Paths") #access true or false with self.displayPathsCheckBox.checked self.outputPlainTextEdit = QPlainTextEdit(self) self.outputPlainTextEdit.setGeometry(300, 80, 271, 253) #300, 80, 281, 283 self.stackPlainTextEdit = QPlainTextEdit(self) self.stackPlainTextEdit.setGeometry(581, 80, 30, 253) self.pathLabel = QLabel(self) self.pathLabel.setGeometry(300, 335, 47, 16) self.pathLabel.setText("Path") self.pathPlainTextEdit = QPlainTextEdit(self) self.pathPlainTextEdit.setGeometry(300, 355, 311, 50) self.quitRunningStringPushButton = QPushButton(self) self.quitRunningStringPushButton.setGeometry(335, 415, 111, 23) self.quitRunningStringPushButton.setText("Quit Running String") self.quitRunningStringPushButton.clicked.connect( self.quit_running_string_clicked) self.quitRunningStringShorcut = QShortcut(QKeySequence("Ctrl+Q"), self) self.quitRunningStringShorcut.activated.connect( self.quit_running_string_clicked) self.quitRunningStringPushButton.setToolTip("Ctrl+Q") self.closeAutomatonPushButton = QPushButton(self) self.closeAutomatonPushButton.setGeometry(465, 415, 111, 23) self.closeAutomatonPushButton.setText("Close Automaton") self.closeAutomatonPushButton.clicked.connect( self.close_automaton_clicked) self.closeAutomatonShorcut = QShortcut(QKeySequence("Ctrl+Alt+C"), self) self.closeAutomatonShorcut.activated.connect( self.close_automaton_clicked) self.closeAutomatonPushButton.setToolTip("Ctrl+Alt+C") # Style for status label text self.styleError = 'font: 15pt Arial; color: maroon' self.styleNormal = 'font:15pt Arial; color: green' self.statusBar = self.statusBar() self.statusLabel = QLabel( "application status messages will go here (when something completes, etc.)" ) self.statusLabel.setStyleSheet(self.styleNormal) self.statusBar.addPermanentWidget(self.statusLabel) self.show()
def testReachableStates(self): a = Automaton() a.txtToAutomaton("media/automata/eq1.txt") self.assertListEqual(['q0', 'q1', 'q2'], a.reachableStates("q0"))
def setUp(self): self.automaton = Automaton(ROWS, COLUMNS) self.simulation = Simulation(self.automaton, False)
def afnToAFD(self): d = self.delta.copy() F = set(self.F) # Histórico de estados criados nesse processo. Guarda <estado>:<estados originais> (ex.: '51': {'5','1'}) # É necessário pra prevenir estados duplicados (ex.: '51' e '15') criados em momentos diferentes. new_states = dict() def is_duplicate(st_components, statelist, find=False): for state, components in statelist.items(): if st_components == components: if find: return state return True return False def is_final(mother_states): for state in mother_states: if state in self.F: return True return False # Resolve indeterminismo inicial (leitura de símbolo num estado podendo levar a mais de um outro) for state in self.delta: # print("-------------") # utils.print_delta(d) for i in range(len(self.delta[state])): trans = self.delta[state][i] # Sendo a transição indeterminística, aglutina estados de destino num único estado novo if len(trans[1]) > 1: new_state = ''.join(trans[1]) trans_symbol = trans[0] mother_states = trans[1] # Adiciona à lista de estados finais, se for gerado a partir de algum estado final if is_final(mother_states): F.add(new_state) new_transitions = [] # Avalia transições desse novo estado e acrescenta entrada (estado e transições) em delta # Prepara, também, informações sobre estados novos criados como destino das transições novas for symbol in self.sigma: dest_new_state = '' dest_mother_states = set() for mother_state in mother_states: for t in self.delta[mother_state]: if t[0] == symbol: new_state_component_candidate = ''.join(t[1]) if dest_new_state != new_state_component_candidate: dest_new_state += ''.join(t[1]) temp = t[1] if isinstance(t[1], str): temp = {temp} dest_mother_states |= temp if dest_new_state == '': continue # Previne duplicação de estados novos com nomes diferentes (concatenações diferentes) state_name = is_duplicate(dest_mother_states, new_states, True) if state_name and state_name != dest_new_state: dest_new_state = state_name # Adiciona à lista de estados finais, se for gerado a partir de algum estado final if is_final(dest_mother_states): F.add(dest_new_state) new_trans = (symbol, dest_new_state) new_transitions.append(new_trans) # Guarda estados criados como destino de estados novos new_states[dest_new_state] = dest_mother_states d[new_state] = new_transitions # Atualiza transição indeterminística antiga d[state][i] = (trans_symbol, new_state) # Guarda guarda estados novos new_states[new_state] = mother_states else: # Atualiza transições já determinísticas (questão de tipo, convertendo de set para string) d[state][i] = (trans[0], ''.join(trans[1])) # Como não é garantida a ordem de concatenação na criação de novos estados, # é possível que new_states contenha estados duplicados nomeados diferentes (ex.: q0q1 e q1q0) # Comparando os estados que deram origem a eles, é simples eliminá-los def eliminate_duplicates(states): res = dict() for state, components in states.items(): if not is_duplicate(components, res): res[state] = components return res # Criação de estados novos a partir de transições criadas no passo anterior # Algoritmo quase idêntico ao trecho do passo anterior. Difere, principalmente, # na repetição enquanto o tamanho da tabela de transições crescer. dlen = -1 while dlen != len(d): dlen = len(d) new_states = eliminate_duplicates(new_states) states_to_add = new_states.copy() for state, mother_states in states_to_add.items(): new_transitions = [] for symbol in self.sigma: dest_new_state = '' dest_mother_states = set() for mother_state in mother_states: for trans in d[mother_state]: if trans[0] == symbol: new_state_component_candidate = ''.join(trans[1]) if dest_new_state != new_state_component_candidate: dest_new_state += ''.join(trans[1]) dest_mother_states.add(trans[1]) if dest_new_state == '': continue state_name = is_duplicate(dest_mother_states, new_states, True) if state_name and state_name != dest_new_state: dest_new_state = state_name if is_final(dest_mother_states): F.add(dest_new_state) new_trans = (symbol, dest_new_state) new_transitions.append(new_trans) new_states[dest_new_state] = dest_mother_states d[state] = new_transitions # Remoção de estados inalcançáveis unreachable = set() graph = utils.deltaToAdjMatrix(d) visited = dict() for state in d: for node in graph: visited[node] = False if not utils.DFS(graph, self.ini, state, visited): unreachable.add(state) for state in unreachable: del d[state] F = F - unreachable Q = list(d.keys()) F = list(F) # Totaliza AFD incomplete_states = set() for state in d: if len(d[state]) < len(self.sigma): incomplete_states.add(state) elif len(d[state]) > len(self.sigma): print("!!!!!!!!!!!!!!!!!") if incomplete_states: new_state_d = "_d" Q.append(new_state_d) d[new_state_d] = [] for symbol in self.sigma: d[new_state_d].append((symbol, new_state_d)) for state in incomplete_states: missing_trans = self.sigma.copy() for trans in d[state]: if trans[0] in missing_trans: missing_trans.remove(trans[0]) for symbol in missing_trans: d[state].append((symbol, new_state_d)) return Automaton(self.sigma, Q, d, self.ini, F)
class TestAutomaton(unittest.TestCase): def setUp(self): self.automaton = Automaton() self.automaton2 = Automaton() def test_retorna_false_se_nao_definir_os_estados(self): self.automaton.set_alphabet(("a")) self.assertFalse(self.automaton.add_transition("A","a","B")) def test_retorna_false_se_nao_definir_o_alfabeto(self): self.automaton.set_states(("A","B")) self.assertFalse(self.automaton.add_transition("A","a","B")) def test_adiciona_transicao_nao_deterministica(self): self.automaton.set_alphabet(("a")) self.automaton.set_states(("A","B")) self.assertTrue(self.automaton.add_transition("A","a","B")) def test_retorna_as_transicoes_corretamente(self): expected = {'A':{'a':['B','C']}} self.automaton.set_alphabet(("a")) self.automaton.set_states(("A","B","C")) self.automaton.add_transition("A","a","B") self.automaton.add_transition("A","a","C") self.assertEqual(self.automaton.transitions, expected) def test_retorna_false_se_nao_tem_transicoes(self): self.assertFalse(self.automaton.determinizar()) def test_retorna_transicoes_deterministicas_submetendo_AFND(self): expected = {'A':{'a':'BC'}, 'BC':{'a':'BC'}} self.automaton.set_alphabet(("a")) self.automaton.set_states(("A","B","C")) self.automaton.add_transition("A","a","B") self.automaton.add_transition("A","a","C") self.automaton.add_transition("B","a","B") self.automaton.add_transition("C","a","C") self.automaton.set_initial_state("A") self.automaton.set_final_states(("A")) self.assertEqual(self.automaton.determinizar().get_transitions(), expected) def test_deterministic_retorna_false_se_nao_tem_alfabeto(self): self.assertFalse(self.automaton.is_deterministic()) def test_deterministic_retorna_false_se_nao_tem_transicoes(self): self.automaton.set_alphabet(("a")) self.assertFalse(self.automaton.is_deterministic()) def test_deterministic_retorna_false_se_nao_tem_estados_finais(self): self.automaton.set_alphabet("a") self.automaton.set_states("A") self.automaton.add_transition("A","a","A") self.assertFalse(self.automaton.is_deterministic()) def test_deterministic_retorna_false_se_nao_tem_estado_inicial(self): self.automaton.set_alphabet("a") self.automaton.set_states("A") self.automaton.set_final_states(("A")) self.automaton.add_transition("A","a","A") self.assertFalse(self.automaton.is_deterministic()) def test_retorna_false_se_AF_eh_nao_deterministico(self): self.automaton.set_alphabet("a") self.automaton.set_states(("A","B")) self.automaton.set_final_states(("A")) self.automaton.set_initial_state("A") self.automaton.add_transition("A","a","A") self.automaton.add_transition("A","a","B") self.assertFalse(self.automaton.is_deterministic()) def test_retorna_true_se_AF_eh_deterministico(self): self.automaton.set_alphabet("a") self.automaton.set_states(("A","B")) self.automaton.set_final_states(("A")) self.automaton.set_initial_state("A") self.automaton.add_transition("A","a","A") self.assertTrue(self.automaton.is_deterministic()) def test_retorna_transicoes_deterministicas_submetendo_AFD(self): from FiniteAutomaton import FiniteAutomaton fa = FiniteAutomaton() fa.set_alphabet(("a")) fa.set_states(("A","B","C")) fa.set_initial_state("A") fa.set_final_states(("A")) fa.add_transition("A","a","B") fa.add_transition("B","a","B") fa.add_transition("C","a","C") self.automaton.set_alphabet(("a")) self.automaton.set_states(("A","B","C")) self.automaton.add_transition("A","a","B") self.automaton.add_transition("B","a","B") self.automaton.add_transition("C","a","C") self.automaton.set_initial_state("A") self.automaton.set_final_states(("A")) self.assertEqual(self.automaton.determinizar().get_transitions(), fa.get_transitions()) def test_completion(self): self.automaton.set_alphabet(("a", "b")) self.automaton.set_states(("A", "B", "C")) self.automaton.add_transition("A", "a", "B") self.automaton.add_transition("B", "b", "B") self.automaton.add_transition("C", "a", "C") self.automaton.set_initial_state("A") self.automaton.set_final_states(("C")) self.assertTrue(self.automaton.completion()) def test_complement(self): self.automaton.set_alphabet(("a", "b")) self.automaton.set_states(("A", "B", "C")) self.automaton.add_transition("A", "a", "B") self.automaton.add_transition("B", "b", "C") self.automaton.add_transition("C", "a", "C") self.automaton.set_initial_state("A") self.automaton.set_final_states(("C")) # self.assertTrue(self.automaton.complement()) def test_union(self): self.automaton.set_alphabet(("a", "b")) self.automaton.set_states(("A", "B", "C")) self.automaton.add_transition("A", "a", "B") self.automaton.add_transition("B", "b", "C") self.automaton.add_transition("C", "a", "C") self.automaton.set_initial_state("A") self.automaton.set_final_states(("C")) self.automaton2.set_alphabet(("a", "b")) self.automaton2.set_states(("A", "B", "C")) self.automaton2.add_transition("A", "a", "B") self.automaton2.add_transition("B", "b", "C") self.automaton2.add_transition("C", "a", "C") self.automaton2.set_initial_state("A") self.automaton2.set_final_states(("C")) # self.assertTrue(self.automaton.union(self.automaton2)) def test_intersection(self): self.automaton.set_alphabet(("a", "b")) self.automaton.set_states(("A", "B", "C")) self.automaton.add_transition("A", "a", "B") self.automaton.add_transition("B", "b", "C") self.automaton.add_transition("C", "a", "C") self.automaton.set_initial_state("A") self.automaton.set_final_states(("C")) self.automaton2.set_alphabet(("a", "b", "c")) self.automaton2.set_states(("A", "B", "C")) self.automaton2.add_transition("A", "a", "A") self.automaton2.add_transition("A", "a", "B") self.automaton2.add_transition("B", "b", "C") self.automaton2.add_transition("C", "c", "C") self.automaton2.set_initial_state("A") self.automaton2.set_final_states(("C")) self.assertTrue(self.automaton.intersection(self.automaton2)) def test_retorna_transicoes_deterministicas_submetendo_AFD_alfabeto_ab(self): from FiniteAutomaton import FiniteAutomaton fa = FiniteAutomaton() fa.set_alphabet(("a","b")) fa.set_states(("S","BDF","ACF")) fa.set_initial_state("S") fa.set_final_states(("BDF","ACF")) fa.add_transition("S","a","BDF") fa.add_transition("BDF","a","ACF") fa.add_transition("ACF","a","BDF") fa.add_transition("S","b","ACF") fa.add_transition("BDF","b","BDF") fa.add_transition("ACF","b","ACF") #mock self.automaton.set_alphabet(("a","b")) self.automaton.set_states(("S","A","B","C","D","F")) self.automaton.add_transition("S","a","B") self.automaton.add_transition("S","a","D") self.automaton.add_transition("S","a","F") self.automaton.add_transition("S","b","A") self.automaton.add_transition("S","b","C") self.automaton.add_transition("S","b","F") self.automaton.add_transition("A","a","B") self.automaton.add_transition("A","a","F") self.automaton.add_transition("A","b","A") self.automaton.add_transition("B","a","A") self.automaton.add_transition("B","b","B") self.automaton.add_transition("B","b","F") self.automaton.add_transition("C","a","D") self.automaton.add_transition("C","b","C") self.automaton.add_transition("C","b","F") self.automaton.add_transition("D","a","C") self.automaton.add_transition("D","a","F") self.automaton.add_transition("D","b","D") self.automaton.set_initial_state("S") self.automaton.set_final_states(("F")) #assert self.assertEqual(self.automaton.determinizar().get_transitions(), fa.get_transitions())
def setUp(self): self.automaton = Automaton() self.automaton2 = Automaton()
def testReachableSymbols(self): a = Automaton() a.txtToAutomaton("media/automata/eq1.txt") self.assertEqual(['0', '1'], a.reachableSymbols("q0"))
def min_automaton(s): d = {'q0': [(s, 'q1')], 'q1': []} return Automaton({s}, ['q0', 'q1'], d, 'q0', ['q1'])
def testIsFinal_noFinal(self): a = Automaton() a.txtToAutomaton("media/automata/eq1.txt") self.assertFalse(a.isFinal("q0"))
""" This script is used to execute the cellular automaton Chile """ from Automaton import Automaton from Simulation import Simulation from Analyzer import Analyzer from Agent import Agent # TODO: USE A GUI TO CONFIG THESE PARAMETERS COLUMNS = 30 ROWS = 30 POPULATION = 100 ITERATIONS = 20 # executing the main method of the code automaton = Automaton(ROWS, COLUMNS) analyzer = Analyzer(automaton) automaton.createPopulation(POPULATION, Agent.randomRangeRadiumUnif(1, 5)) simulation = Simulation(automaton, True) simulation.start(ITERATIONS) rankings = analyzer.getRankingOfPopulation() print analyzer.getLinearRegressionData(False)
class TestFitness(unittest.TestCase): def setUp(self): self.automaton = Automaton(ROWS, COLUMNS) self.simulation = Simulation(self.automaton, False) def test_infiniteRadium(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.createPopulation(POPULATION, Agent.infiniteRadium()) self.simulation.start(ITERATIONS) self.assertTrue(self.automaton.convergence, "IT IS CONVERGENCE") array = self.automaton.getMatrixOfPopulation() # print repr(self.automaton) + " " + repr(array.max()) self.assertEqual(POPULATION, len(self.automaton.getAgents()), "ALL AGENTS") def test_withZeroRadium(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.createPopulation(POPULATION, Agent.constRadium(0)) self.simulation.start(3) self.assertTrue(self.automaton.convergence, "IT IS CONVERGENCE") def test_random(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.createPopulation(POPULATION, Agent.infiniteRadium(), Agent.randomFitness) self.simulation.start(ITERATIONS) self.assertFalse(self.automaton.convergence, " IT IS NOT CONVERGENCE") def test_circularRangeInf(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() rr = [0, 1, 2, 3, 4, 5, 17, 18, 19] rc = [0, 1, 2, 3, 4, 5, 27, 28, 29] ranges = self.automaton.getRanges(1, 1, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_circularRangeSup(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() rr = [0, 1, 2, 14, 15, 16, 17, 18, 19] rc = [0, 1, 23, 24, 25, 26, 27, 28, 29] ranges = self.automaton.getRanges(18, 27, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_circularRangeAndWithoutRandomInf(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() self.automaton.disableRandomVisitingOfCells() rr = [17, 18, 19, 0, 1, 2, 3, 4, 5] rc = [27, 28, 29, 0, 1, 2, 3, 4, 5] ranges = self.automaton.getRanges(1, 1, 4) self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_circularRangeAndWithoutRandomSup(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() self.automaton.disableRandomVisitingOfCells() rr = [14, 15, 16, 17, 18, 19, 0, 1, 2] rc = [23, 24, 25, 26, 27, 28, 29, 0, 1] ranges = self.automaton.getRanges(18, 27, 4) self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_rangeWithoutRandomInf(self): self.automaton.reinit(ROWS, COLUMNS) rr = [0, 1, 2, 3, 4, 5] rc = [0, 1, 2, 3, 4, 5] ranges = self.automaton.getRanges(1, 1, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_rangeWithoutRandomSup(self): self.automaton.reinit(ROWS, COLUMNS) rr = [14, 15, 16, 17, 18, 19] rc = [23, 24, 25, 26, 27, 28, 29] ranges = self.automaton.getRanges(18, 27, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1]))