def bruteForceBeginningTriggerAfterSimpleBijectionTriggerAutomatas(): N = 3 K = 3 functionsList1 = [] functionsList1.append(BoolFunction.BoolFunction(K, "00001110")) functionsList1.append(BoolFunction.BoolFunction(K, "01000000")) functionsList1.append(BoolFunction.BoolFunction(K, "00100000")) linksList1 = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] automata1 = Automata.NK_Automata(N, K, functionsList1, linksList1) AutomataProssesing.doAutomata(N, K, automata1) functionsList2 = [] functionsList2.append(BoolFunction.BoolFunction(K, "01001111")) functionsList2.append(BoolFunction.BoolFunction(K, "00000100")) functionsList2.append(BoolFunction.BoolFunction(K, "00000010")) linksList2 = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] automata2 = Automata.NK_Automata(N, K, functionsList2, linksList2) AutomataProssesing.doAutomata(N, K, automata2) return automata1, automata2
def basinAttractorsDoNotMatchTriggerAutomatas(): N = 3 K = 3 functionsList1 = [] functionsList1.append(BoolFunction.BoolFunction(K, "00001111")) functionsList1.append(BoolFunction.BoolFunction(K, "00000001")) functionsList1.append(BoolFunction.BoolFunction(K, "00000000")) linksList1 = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] automata1 = Automata.NK_Automata(N, K, functionsList1, linksList1) AutomataProssesing.doAutomata(N, K, automata1) functionsList2 = [] functionsList2.append(BoolFunction.BoolFunction(K, "00001111")) functionsList2.append(BoolFunction.BoolFunction(K, "01000110")) functionsList2.append(BoolFunction.BoolFunction(K, "00001010")) linksList2 = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] automata2 = Automata.NK_Automata(N, K, functionsList2, linksList2) AutomataProssesing.doAutomata(N, K, automata2) return automata1, automata2
def generateStockAutomaton(grammar: Grammar): global automatas os.system("cls") alphabet = grammar.terminals initial = "S0" final = "S3" states = ["S0", "S1", "S2", "S3"] stockElements = [] transitions = [] transitionOne = Transition("S0", "S1", "λ", "λ", "#") stockElements.append("#") transitionTwo = Transition("S1", "S2", "λ", "λ", grammar.initialNT) stockElements.append(grammar.initialNT) transitionFinal = Transition("S2", "S3", "λ", "#", "λ") transitions.append(transitionOne) transitions.append(transitionTwo) for production in grammar.productions: for producccion in production.expresion: transition = Transition("S2", "S2", "λ", production.stateOne, producccion) stockElements.append(producccion) transitions.append(transition) for terminal in alphabet: transition = Transition("S2", "S2", terminal, terminal, "λ") transitions.append(transition) transitions.append(transitionFinal) aut = Automata(alphabet, states, initial, final, transitions, stockElements) print(aut.toString()) for a in aut.transitions: print(a.toStringg()) automatas = aut
def buildDFA(self, nfa): allstates = dict() eclose = dict() count = 1 state1 = nfa.getEClose(nfa.startState) eclose[nfa.startState] = state1 dfa = Automata(nfa.language) dfa.setstartState(count) states = [[state1, count]] allstates[count] = state1 count += 1 while len(states) != 0: [state, fromindex] = states.pop() for char in dfa.language: trstates = nfa.getTransitions(state, char) for s in list(trstates)[:]: if s not in eclose: eclose[s] = nfa.getEClose(s) trstates = trstates.union(eclose[s]) if len(trstates) != 0: if trstates not in allstates.values(): states.append([trstates, count]) allstates[count] = trstates toindex = count count += 1 else: toindex = [ k for k, v in allstates.iteritems() if v == trstates ][0] dfa.addTransition(fromindex, toindex, char) for value, state in allstates.iteritems(): if nfa.finalStates[0] in state: dfa.addFinalStates(value) self.dfa = dfa
def evaluar(self): auto = Automata.Automatapila(self.text.get()) auto.validar() self.resultado = auto.resultado self.tran = auto.transiciones self.sgda_ventana()
class Core: def __init__(self): self._cache = Cache(); self._automata = Automata(); self._coherenceMisses = 0; self._cacheMisses = 0; def printStats(self, name): print "Core %s:"%name print "\tCache Misses:", self._cacheMisses print "\tCoherence Misses:", self._coherenceMisses def read(self, s, t): state = self._cache.getState(s, t); # cache hit if(len(state)==1 and state[0]!='I'): return []; # cacheBlock in Invalid state elif(len(state)==1 and state[0]=='I'): self._coherenceMisses = self._coherenceMisses + 1; return ['BR','I']; # cache miss else: self._cacheMisses = self._cacheMisses + 1; return ['BR']; def write(self, s, t): state = self._cache.getState(s, t); if(len(state)==0): self._cacheMisses = self._cacheMisses + 1 self._cache.setState(s, t, 'M'); else: if state[0]=='I': self._coherenceMisses = self._coherenceMisses + 1 self._cache.changeState(s, t, 'M'); return ['BX']; def request(self, s, t, request): state = self._cache.getState(s, t); if(len(state)==0): return [] mesiTxn = self._automata.get(state[0],request); if request=='BR' and len(mesiTxn) !=0 : self._cache.changeState(s, t, mesiTxn[0]); return state; elif request=='BX' and len(mesiTxn)!=0: self._cache.changeState(s, t, mesiTxn[0]); return []; return []; def new(self, s, t, state): self._cache.setState(s, t, state); def change(self, s, t,state): self._cache.changeState(s, t, state);
class Core: def __init__(self): self._cache = Cache() self._automata = Automata() self._coherenceMisses = 0 self._cacheMisses = 0 def printStats(self, name): print "Core %s:" % name print "\tCache Misses:", self._cacheMisses print "\tCoherence Misses:", self._coherenceMisses def read(self, s, t): state = self._cache.getState(s, t) # cache hit if (len(state) == 1 and state[0] != 'I'): return [] # cacheBlock in Invalid state elif (len(state) == 1 and state[0] == 'I'): self._coherenceMisses = self._coherenceMisses + 1 return ['BR', 'I'] # cache miss else: self._cacheMisses = self._cacheMisses + 1 return ['BR'] def write(self, s, t): state = self._cache.getState(s, t) if (len(state) == 0): self._cacheMisses = self._cacheMisses + 1 self._cache.setState(s, t, 'M') else: if state[0] == 'I': self._coherenceMisses = self._coherenceMisses + 1 self._cache.changeState(s, t, 'M') return ['BX'] def request(self, s, t, request): state = self._cache.getState(s, t) if (len(state) == 0): return [] mesiTxn = self._automata.get(state[0], request) if request == 'BR' and len(mesiTxn) != 0: self._cache.changeState(s, t, mesiTxn[0]) return state elif request == 'BX' and len(mesiTxn) != 0: self._cache.changeState(s, t, mesiTxn[0]) return [] return [] def new(self, s, t, state): self._cache.setState(s, t, state) def change(self, s, t, state): self._cache.changeState(s, t, state)
def verificar_extension_automata(ruta): nombre, extension = os.path.split(ruta) extension = extension.split(".") global nuevo_automata if extension[1] == "afd": nuevo_automata = Automata.Automata(extension[0]) return True else: input("Archivo no valido, presione enter") return False
def iniciarAutomata(self): if self.validar() == False: return -1 self.iniciarGrafo() self.automata = Automata(self.dato.get()) self.hilo = threading.Thread(target=self.runAautomata) self.hilo.start() self.cambiarLetra(0) self.automata.setBandera(True) while (self.hilo.is_alive()): self.esperarCambios() self.actualizarGui() self.automata.setBandera(True) if (self.__indexE == 2): messagebox.showinfo("Resultado", "Es palindrome") self.root.destroy() else: messagebox.showinfo("Resultado", "No es palindrome") self.root.destroy()
def validacion(self): if len(self.cadena) % 2 == 0: print("Es par") p = Automata.Pila() p.apilar("#") guardar = Lista.Listas() guardar.addPila("#") print("la pila", p.mostrar()) aux = EstadoPar.EstadosPar(self.cadena, p, self.error, guardar) aux.estado1(p) print(aux.retorno()) if (aux.retorno()): self.estadoPila = aux.devolverPila() self.estadoPila.append("#") print(self.estadoPila) self.estados = aux.devolverEstados() self.estados.append("True") print(self.estados) print("-> Palabra Acepatada PALINDROMO!!!") print("la pila", p.mostrar()) else: self.estadoPila = aux.devolverPila() self.estadoPila.append("#") print(self.estadoPila) self.estados = aux.devolverEstados() self.estados.append("False") print(self.estados) print("-> Palabra no Aceptada, NOOOOO es PALINDROMO!!!!") if len(self.cadena) % 2 != 0: print(' Esta palabra es impar y no es aceptada') print("NOJODAAAAAAAAAAAA", aux.devolverEstados()) print("Diossssssss", aux.devolverPila()) def load_image(filename, transparent=False): try: image = pygame.image.load(filename) except pygame.error, message: raise SystemExit, message image = image.convert() if transparent: color = image.get_at((0, 0)) image.set_colorkey(color, RLEACCEL) return image
def carga(): root = Tk() root.withdraw() root.wm_attributes("-topmost", 1) filename = askopenfilename(initialdir="/", filetypes=(("Archivo de LFP", "*.lfp"), ("All Files", "*.*")), title="Busque su archivo.") root.update() root.destroy() archivo = open(filename, 'r') while True: linea = archivo.readline() # lee línea if not linea: break # Si no hay más se rompe bucle list = Automata.AFD(linea) x = 1 listaElementos = [] listaSolicutudes = [] while x < len(list): if list[x] == 'BUSCAR' or list[x] == 'buscar' or list[ x] == 'ordenar' or list[x] == 'ORDENAR': break else: listaElementos.append(list[x]) x = x + 1 while x < len(list): listaSolicutudes.append(list[x]) x = x + 1 dic1 = { 'nombre': list[0], 'lista': listaElementos, 'solicitud': listaSolicutudes } listaAlpha.append(dic1) archivo.close() # Cierra archivo print("Archivo cargado correctamente")
def graphviz(afd1: Automata): print(afd1.toString()) for p in afd1.transitions: print(p.toStringg()) f = Digraph(format='png', name='automata') f.attr(rankdir="LR", size="8,5") f.attr('node', shape="doublecircle") f.node(afd1.finalStates) for estado in afd1.states: f.attr('node', shape="circle") f.node(estado) for trans in afd1.transitions: etiqueta = "" etiqueta = trans.inputCharacter + "," + trans.readStock + "," + trans.inputStock f.edge(trans.origin, trans.destiny, etiqueta) f.attr('node', shape="none") f.attr("edge", arrowhead="empty", arrowsize="1.5") f.edge("", afd1.initial, None) f.render('output/' + "automata", view=True)
########################################################### ## CTC-34: Autômata e Linguagens Formais ## ## Prof. Forster ## ## ## ## Equipe: ## ## Arthur Fernandes de Morais ## ## Gianluigi Dal Toso ## ## Lucas Alberto Bilobran Lema ## ## ## ########################################################### from Automata import * import pydotplus graph = pydotplus.graph_from_dot_file('teste.dot') Machine = Automata() for node in graph.get_nodes(): node_name = node.get_name() if node_name != 'node': if node_name == 'S1': final = True else: final = False state = State(node_name, final=final) if node_name == 'S0': Machine.set_initial_state(state) else: Machine.add_state(state)
def validacion(self): if len(self.cadena) % 2 == 0: print(' Esta palabra es par y no es aceptada') if len(self.cadena) % 2 != 0: p = Automata.Pila() p.apilar("#") guardar = Lista.Listas() guardar.addPila("#") #print("pila grajdklm",guardar.mostrarPila()) print("la pila", p.mostrar()) aux = EstadoImpar.EstadosImpar(self.cadena, p, self.error, guardar) aux.estado1(p) print(aux.retorno()) if aux.retorno(): self.estadoPila = aux.devolverPila() self.estadoPila.append("#") #self.estadoPila.append("True") print(self.estadoPila) self.estados = aux.devolverEstados() self.estados.append("True") #self.estados.append(" ") print(self.estados) print("-> Palabra Acepatada PALINDROMO!!!") print(p.mostrar()) else: self.estadoPila = aux.devolverPila() self.estadoPila.append("#") print(self.estadoPila) self.estados = aux.devolverEstados() self.estados.append("False") print(self.estados) print("-> Palabra no Aceptada, NOOOOO es PALINDROMO!!!!") # iniciamos el PYGAME def load_image(filename, transparent=False): try: image = pygame.image.load(filename) except pygame.error, message: raise SystemExit, message image = image.convert() if transparent: color = image.get_at((0, 0)) image.set_colorkey(color, RLEACCEL) return image # --------------------------------------------------------------------- def main(cadena, devolverEstados, devolverPila): # Constantes listaPila = devolverPila listaEstado = devolverEstados WIDTH = 903 HEIGHT = 542 reloj = pygame.time.Clock() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("<-- PALINDROMO PAR --") background_image = load_image('img/impar.png') #imagenes errorTrue = pygame.image.load("img/ERRROR_TRUE.png") errorFalse = pygame.image.load("img/ERRROR_FALSE.png") flecha = pygame.image.load("img/flecha.png") apilar = pygame.image.load("img/APILAR.png") desapilar = pygame.image.load("img/DESAPILAR.png") fuente = pygame.font.Font(None, 26) texto1 = fuente.render(cadena, 0, (9, 104, 146)) fuentea = pygame.font.Font(None, 60) #coordenadas de imagenes #flecha xFlecha = 293 yFlecha = 233 #apilar1 xapi = 1000 yapi = 1000 #desapilar xdesa = 1000 ydesa = 1000 i = 0 #errorTrue xTrue = 1000 yTrue = 1000 #errorFalse xFalse = 1000 yFalse = 1000 while True and i < len(listaPila): for eventos in pygame.event.get(): if eventos.type == QUIT: sys.exit(0) pulsada = pygame.key.get_pressed() #reubica ala imagen apilar y desapilar xapi = 1000 yapi = 1000 xdesa = 1000 ydesa = 1000 if listaEstado[ i] == "f": #1 b,b/bb -> desaapila b apila bb xFlecha = 154 yFlecha = 107 #desapi xdesa = 724 ydesa = 276 #apila xapi = 574 yapi = 72 if listaEstado[ i] == "e": #2 a,b/ba -> desaapila b apila ba xFlecha = 154 yFlecha = 137 #desapi xdesa = 724 ydesa = 276 #apila xapi = 574 yapi = 72 if listaEstado[i] == "d": #3 b,a/ab ->desaapila a apila ab xFlecha = 154 yFlecha = 174 #desapi xdesa = 724 ydesa = 276 #apila xapi = 574 yapi = 72 if listaEstado[ i] == "c": #4 a,a/aa ->desapila a y apila aa xFlecha = 154 yFlecha = 211 #desapi xdesa = 724 ydesa = 276 #apila xapi = 574 yapi = 72 if listaEstado[i] == "b": #5 b,#/#b ->apila b xFlecha = 154 yFlecha = 248 #apila xapi = 574 yapi = 72 if listaEstado[i] == "a": #6 a,#/#a ->apila a xFlecha = 154 yFlecha = 280 #apila xapi = 574 yapi = 72 if listaEstado[i] == "g": #7 c,#/# xFlecha = 308 yFlecha = 329 if listaEstado[i] == "h": #8 c,b/b -> apila b xFlecha = 308 yFlecha = 368 if listaEstado[i] == "i": #9 c,a/a -> apila a xFlecha = 308 yFlecha = 415 if listaEstado[i] == "j": #10 b,b/landa -> desapila b xFlecha = 570 yFlecha = 285 #desapi xdesa = 724 ydesa = 276 if listaEstado[i] == "k": #11 a,a/landa -> desapila a xFlecha = 571 yFlecha = 320 #desapi xdesa = 724 ydesa = 276 if listaEstado[i] == "True": #12 landa/#/# final del xFlecha = 532 yFlecha = 431 #desapi xdesa = 724 ydesa = 276 if listaEstado[i] == "True": #4 xTrue = 183 yTrue = 129 if listaEstado[i] == "False": #4 xFalse = 183 yFalse = 129 reloj.tick(0.5) screen.fill((0, 0, 0)) screen.blit(background_image, (0, 0)) screen.blit(flecha, (xFlecha, yFlecha)) a = fuentea.render(listaPila[i], 0, (0, 0, 0)) screen.blit(a, (348, 160)) screen.blit(apilar, (xapi, yapi)) screen.blit(apilar, (1000, 1000)) #reloj.tick(0.1) screen.blit(desapilar, (xdesa, ydesa)) screen.blit(desapilar, (1000, 1000)) screen.blit(texto1, (654, 427)) screen.blit(errorTrue, (xTrue, yTrue)) screen.blit(errorFalse, (xFalse, yFalse)) pygame.display.update() pygame.display.flip() i = i + 1 return 0 pygame.init() main(self.cadena, aux.devolverEstados(), aux.devolverPila())
def parse_dfa(file_path): # open file f = open(file_path, "r") # states line = f.readline() line = line.replace(" ", "") line = line.replace("\n", "") states = {} tokens = line.split("=") if tokens[0] != "S": print("Automaton description isn't valid") return None else: tokens[1] = tokens[1].replace("{", "") tokens[1] = tokens[1].replace("}", "") tokens = tokens[1].split(",") for s in tokens: states[s] = automata.State(s) # alphabet line = f.readline() line = line.replace(" ", "") line = line.replace("\n", "") alph = set() tokens = line.split("=") if tokens[0] != "A": print("Automaton description isn't valid") return None else: tokens[1] = tokens[1].replace("{", "") tokens[1] = tokens[1].replace("}", "") tokens = tokens[1].split(",") for a in tokens: alph.add(a) for s in states.values(): s.accepted_input = alph # initial state line = f.readline() line = line.replace(" ", "") line = line.replace("\n", "") tokens = line.split("=") if tokens[0] != "I": print("Automaton description isn't valid") return None else: initial = tokens[1] # end states line = f.readline() line = line.replace(" ", "") line = line.replace("\n", "") tokens = line.split("=") if tokens[0] != "E": print("Automaton description isn't valid") return None else: tokens[1] = tokens[1].replace("{", "") tokens[1] = tokens[1].replace("}", "") tokens = tokens[1].split(",") for e in tokens: states[e].is_end_state = True # transition function number_of_rules = len(states) * len(alph) for r in range(number_of_rules): line = f.readline() line = line.replace(" ", "") line = line.replace("\n", "") tokens = line.split("=") tokens[0] = tokens[0].replace("d", "") tokens[0] = tokens[0].replace("(", "") tokens[0] = tokens[0].replace(")", "") t = tokens[0].split(",") if alph.__contains__(t[1]): states[t[0]].transitions[t[1]] = tokens[1] else: print("Automaton description isn't valid") return None f.close() # resulting dfa object return automata.DFA(states, alph, initial)
def D_DFA(arbol): complete_tree = copy.copy(arbol) # Tabla base con fistpos y lastpos de cada nodo importante y 3 pos_nodes = 0 pos = 0 for node in complete_tree: if (node != "*" and node != "|" and node != "."): if (node == "3"): complete_tree[pos] = [pos, node, [], []] else: complete_tree[pos] = [ pos, node, pos_nodes, [pos_nodes], [pos_nodes] ] pos_nodes += 1 else: complete_tree[pos] = [pos, node] pos += 1 # Firstpos y lastpos de cada nodo pos = 0 for node in complete_tree: if (node[1] == "*" or node[1] == "." or node[1] == "|"): complete_tree[pos] = [ pos, complete_tree[pos][1], firstpos(complete_tree, pos), lastpos(complete_tree, pos) ] pos += 1 # Followpos for node in complete_tree: followpos(complete_tree, node[0]) print("******** Table ALL************") print("id\tSymbol\tPos n\tfirstpos\tlastpos\tfollowpos") for a in complete_tree: if (len(a) == 6): print(a[0], "\t", a[1], "\t", a[2], "\t\t", a[3], "\t", a[4], "\t", a[5]) elif (len(a) == 5): print(a[0], "\t", a[1], "\t", a[2], "\t\t", a[3], "\t", a[4], "\t", " --") elif (len(a) == 4): print(a[0], "\t", a[1], "\t", a[2], "\t\t", a[3], "\t", "--", "\t", " --") else: print(a[0], "\t", a[1], "\t", a[2], "\t\t", "--", "\t", "--", "\t", " --") print("******** Table DFA************") print("Symbol\tPos n\tfirstpos\tlastpos\tfollowpos\t") table = [] symbols = [] for a in complete_tree: if (isinstance(a[2], int)): if (a[1] != "#"): if a[1] not in symbols: symbols.append(a[1]) table.append(a) for a in table: if (len(a) == 6): print(a[1], "\t", a[2], "\t", a[3], "\t", a[4], "\t", a[5], "\t") else: print(a[1], "\t", a[2], "\t", a[3], "\t", a[4], "\t", " --") # Creando el nuevo automata Aut = Automata() states = [] if (len(complete_tree[len(complete_tree) - 1]) == 4): initial = complete_tree[len(complete_tree) - 1][2] else: initial = complete_tree[len(complete_tree) - 1][4] states.append(initial) Aut.set_inicial(initial) Aut.set_symbols(symbols) print("Inicial", initial) count_states = 0 while count_states < len(states): for sim in symbols: temp_state = [] for pos in states[count_states]: for a in table: if (a[2] == pos): if (sim == a[1]): temp_state = joinList(temp_state, a[5]) if (temp_state not in states): states.append(temp_state) Aut.add_transitions([count_states, len(states) - 1, sim]) else: pos = states.index(temp_state) Aut.add_transitions([count_states, pos, sim]) count_states += 1 for st in states: for a in table: if (a[1] == "#"): if a[2] in st: pos = states.index(st) Aut.add_finalState(pos) all_states = list(range(0, count_states)) Aut.set_states(all_states) return Aut
def menu_principal(): os.system("cls") nombreAutomata = input("Ingrese el nombre del automata: ") if verificar_afd_creado(nombreAutomata): global automata automata = obtener_afd_creado(nombreAutomata) else: automata = Automata.Automata(nombreAutomata) listaAutomatas.append(automata) os.system("cls") opcion = 0 while opcion != 7: os.system("cls") print("----------Menu de Automatas----------") print("1) INGRESAR ESTADOS") print("2) INGRESAR ALFABETO") print("3) DEFINIR ESTADO INICIAL") print("4) DEFINIR ESTADOS DE ACEPTACION") print("5) DEFINIR TRANSICIONES") print("6) AYUDA") print("7) SALIR") try: opcion = int(input("Seleccione una opcion: ")) except: print() if opcion == 1: seleccion = 0 while seleccion != 2: os.system("cls") print("----------Ingresar Estados----------") print("1) INGRESAR NUEVO ESTADO") print("2) SALIR") try: seleccion = int(input("Seleccione una opcion: ")) except: print() if seleccion == 1: nombreEstado = input("Ingrese el nombre del estado: ") ingresar_estado(nombreEstado) elif seleccion == 2: break else: print("Opcion incorrecta, presione enter") input() elif opcion == 2: seleccion = 0 while seleccion != 2: os.system("cls") print("----------Ingresar Alfabeto----------") print("1) INGRESAR NUEVO SIMBOLO") print("2) SALIR") try: seleccion = int(input("Seleccione una opcion: ")) except: print() if seleccion == 1: simbolo = input("Ingrese el simbolo: ") ingresar_alfabeto(simbolo) elif seleccion == 2: break else: print("Opcion incorrecta, presione enter") input() elif opcion == 3: print("----------Definir Estado Inicial----------") estado_inicial = input( "Ingrese el nombre del estado que desea como inicial: ") definir_estado_inicial(estado_inicial) elif opcion == 4: seleccion = 0 while seleccion != 2: os.system("cls") print("----------Estados de Aceptacion----------") print("1) DEFINIR NUEVO ESTADO DE ACEPTACION") print("2) SALIR") try: seleccion = int(input("Seleccione una opcion: ")) except: print() if seleccion == 1: nombre_estado = input( "Escriba el nombre de un estado existente: ") definir_estado_aceptacion(nombre_estado) elif seleccion == 2: break else: print("Opcion incorrecta, presione enter") input() elif opcion == 5: seleccion = 0 while seleccion != 3: os.system("cls") print("----------Menu de Transiciones----------") print("1) MODO 1") print("2) MODO 2") print("3) SALIR") try: seleccion = int(input("Seleccione una opcion: ")) except: print() if seleccion == 1: os.system("cls") cadena = input("Ingrese la transicion: ") transicion_tipo_1(cadena) elif seleccion == 2: os.system("cls") cadena_terminales = input("Ingrese los terminales: ") cadena_estados = input("Ingrese los estados: ") cadena_transiciones = input("Ingrese las transiciones: ") transicion_tipo_2(cadena_terminales, cadena_estados, cadena_transiciones) elif opcion == 6: os.system("cls") print("Lenguajes Formales y de Programacion Seccion A") print("Auxiliar: Elmer Real") print("4") input("Presione enter") elif opcion == 7: break else: print("Opcion invalida, presione enter") input() os.system("cls")
def createDFA(Autom): #Inicializando variables count_states = 0 new_states = [] # Primer e-closure inicial = e_closure(Autom, Autom.initial_state) new_states.append(inicial) Aut = Automata() Aut.set_inicial([0]) Symbols = Autom.symbols if ("3" in Symbols): Symbols.remove("3") Symbols.sort() Aut.set_symbols(Symbols) while count_states < len(new_states): for sim in Symbols: #print("simbolo: ", sim) temp = e_closure(Autom, move(Autom, new_states[count_states], sim)) if (temp != []): if (temp in new_states): #print("igual", temp, new_states) pos = new_states.index(temp) #print(pos) Aut.add_transitions([count_states, pos, sim]) else: #print("diferente", temp, new_states) new_states.append(temp) #print(count_states, len(new_states)-1) Aut.add_transitions( [count_states, len(new_states) - 1, sim]) count_states += 1 for st in new_states: if Autom.final_states[0] in st: pos = new_states.index(st) Aut.add_finalState(pos) states = list(range(0, count_states)) Aut.set_states(states) return Aut
except: pass try: print('cx3 = {}, cy3 = {}'.format(cx3, cy3)) except: pass """ try: coordenadas = cx, cy, cx2, cy2, cx3, cy3 h = 1 except: pass if emparejado is True and h == 1: data = Automata.ir(cx, cy, cx2, cy2, cx3, cy3) comunicacion.escuchar_enviar(data) print('datos enviados!') # Creamos las ventanas de salida y configuracion cv2.imshow('Salida', frame) cv2.imshow('inRange', bn_img) # cv2.namedWindow('inRange') # cv2.resizeWindow('inRange', 300, 600) cv2.imshow('inRange2', bn_img2) # cv2.namedWindow('inRange2') # cv2.resizeWindow('inRange2', 300, 600) cv2.imshow('inRange3', bn_img3) # cv2.namedWindow('inRange3')
def __init__(self): self._cache = Cache(); self._automata = Automata(); self._coherenceMisses = 0; self._cacheMisses = 0;
def Thompson(tokens, countStates): for token in tokens: if (token == "*"): countStates += 1 A1 = tokens[tokens.index(token) - 1] A1.set_final([countStates]) A1.add_state(countStates - 1) A1.add_state(countStates) A1.set_symbols(joinList(A1.symbols, ["3"])) A1.sub_trans_states(1) A1.add_transitions( [A1.initial_state[0], A1.initial_state[0] + 1, "3"]) A1.add_transitions( [A1.final_states[0] - 1, A1.final_states[0], "3"]) A1.add_transitions([A1.initial_state[0], A1.final_states[0], "3"]) A1.add_transitions( [A1.final_states[0] - 1, A1.initial_state[0] + 1, "3"]) tokens.pop(tokens.index(token) - 1) tokens[tokens.index(token)] = A1 countStates += 1 #print(A1.initial_state, A1.final_states, A1.states, A1.symbols, A1.transitions) return tokens, countStates elif (token == "."): A1 = tokens[tokens.index(token) - 2] A2 = tokens[tokens.index(token) - 1] # Cambios en los estados del segundo autómata if (A1.final_states != A2.initial_state): A2.set_inicial(A1.final_states) A2.sub_finaState(-1) A2.sub_states(-1) A2.sub_trans_states(-1) countStates -= 1 #print(A1.initial_state, A1.final_states, A1.states, A1.symbols, A1.transitions) #print(A2.initial_state, A2.final_states, A2.states, A2.symbols, A2.transitions) #Creación del nuevo autómata Aut = Automata() Aut.set_inicial(A1.initial_state) Aut.set_final(A2.final_states) Aut.set_states(joinList(A1.states, A2.states)) Aut.set_symbols(joinList(A1.symbols, A2.symbols)) Aut.set_transitions(joinList(A1.transitions, A2.transitions)) #print(Aut.initial_state, Aut.final_states, Aut.states, Aut.symbols, Aut.transitions) tokens.pop(tokens.index(token) - 1) tokens.pop(tokens.index(token) - 1) tokens[tokens.index(token)] = Aut return tokens, countStates elif (token == "|"): countStates += 1 A1 = tokens[tokens.index(token) - 2] A2 = tokens[tokens.index(token) - 1] Aut = Automata() Aut.set_inicial(A1.initial_state) Aut.set_final([countStates]) Aut.set_states(joinList(A1.states, A2.states)) Aut.add_state(countStates - 1) Aut.add_state(countStates) Aut.set_symbols(joinList(A1.symbols, A2.symbols)) Aut.set_symbols(joinList(Aut.symbols, ["3"])) A1.sub_trans_states(1) A2.sub_trans_states(1) Aut.set_transitions(joinList(A1.transitions, A2.transitions)) Aut.add_transitions( [Aut.initial_state[0], A1.initial_state[0] + 1, "3"]) Aut.add_transitions( [Aut.initial_state[0], A2.initial_state[0] + 1, "3"]) Aut.add_transitions( [A1.final_states[0] + 1, Aut.final_states[0], "3"]) Aut.add_transitions( [A2.final_states[0] + 1, Aut.final_states[0], "3"]) #Actualizar array tokens.pop(tokens.index(token) - 1) tokens.pop(tokens.index(token) - 1) tokens[tokens.index(token)] = Aut countStates += 1 #print("Creacion", Aut.initial_state, Aut.final_states, Aut.states, Aut.symbols, Aut.transitions) return tokens, countStates elif (isinstance(token, str)): Aut = Automata() Aut.add_symbol(token) Aut.set_inicial([countStates]) countStates += 1 Aut.set_final([countStates]) countStates += 1 Aut.set_states([Aut.initial_state[0], Aut.final_states[0]]) Aut.add_transitions( [Aut.initial_state[0], Aut.final_states[0], token]) tokens[tokens.index(token)] = Aut #print("Creacion", Aut.initial_state, Aut.final_states, Aut.states, Aut.symbols, Aut.transitions) return tokens, countStates
class mostrar(): def __init__(self): self.lista = list() self.ventana() def ventana(self): self.root = Tk() self.listpila = list() self.root.title(" Palindromo Impar") self.root.geometry('600x400') self.root.configure(background="light blue") self.texto = Label(self.root, text="Ingrese el Palindromo (ab) impar:", bg="light blue", font=("Times New Roman", 16)) self.texto.pack(padx=0, pady=0) self.texto.place(x=9, y=9) self.dato = Entry(self.root, text="validar") self.dato.place(x=300, y=16) self.boton = Button(self.root, text="Validar", fg="red", command=self.iniciarAutomata) self.boton.place(x=340, y=40) self.root.mainloop() def validar(self): lenguaje = self.dato.get() self.__palabraEntry = lenguaje j = 0 validar2 = re.match('^[a-bA-B]+c[a-bA-B]+$', lenguaje) valen = len(lenguaje) % 2 total = len(lenguaje) if valen == 1 and total >= 3 and validar2 is not None: pos = 15 cont = 0 for i in self.lista: self.lista[cont].destroy() cont = cont + 1 for i in lenguaje: botonp = Button(self.root, text=i, fg="white", background="Light Blue", command=self.PruebaDeAnimaciones) botonp.pack(padx=0, pady=0, ipadx=130, ipady=10) botonp.grid(row=0, column=1, columnspan=3, sticky='EWNS') botonp.place(x=(10) + pos, y=70) pos = pos + 15 self.lista.append(botonp) return True else: messagebox.showerror("Validación", "Dato invalido") return False def iniciarGrafo(self): self.__indexP = -1 self.__indexE = -1 self.__pila = Pila() self.transicionA = -1 self.generarPila() self.canvas = Canvas(width=380, height=220, bg="#ECEE38") self.canvas.pack(expand=NO) self.canvas.place(x=20, y=160) self.boton = Button(self.root, text="Fast") self.boton.place(x=450, y=200) self.boton = Button(self.root, text="Slow") self.boton.place(x=450, y=250) self.canvas = Canvas(width=380, height=220, bg="#ECEE38") self.canvas.pack(expand=NO) self.canvas.place(x=20, y=160) # Lineas de inicio self.canvas.create_line(0, 150, 23, 150, width=4, fill="black") self.canvas.create_line(12, 140, 23, 150, width=4, fill="black") self.canvas.create_line(12, 160, 23, 150, width=4, fill="black") # creacion del primer estado self.canvas.create_oval(23, 95, 65, 130, width=2, fill='white') # circulo del primer estado self.canvas.create_oval(25, 120, 85, 180, width=5, fill='white') # circulo del arco de transicion self.canvas.create_line( 20, 125, 35, 128, width=2, fill="black") # Linea uno de la flecha de transicion P self.canvas.create_line( 35, 115, 35, 128, width=2, fill="black") # Linea dos de la flecha de transicion P self.canvas.create_text(55, 150, text='P', fill='black') # letra P # transiciones primer estado self.canvas.create_text(35, 85, text='a,#/#a', fill='black') self.canvas.create_text(35, 70, text='b,#/#b', fill='black') self.canvas.create_text(35, 55, text='a,a/aa', fill='black') self.canvas.create_text(35, 40, text='b,a/ab', fill='black') self.canvas.create_text(35, 25, text='a,b/ba', fill='black') self.canvas.create_text(35, 10, text='b,b/bb', fill='black') self.canvas.create_line(85, 150, 175, 150, width=5, fill='black') # linea de transicion de p a q self.canvas.create_line(160, 160, 175, 150, width=4, fill="black") self.canvas.create_line(160, 140, 175, 150, width=4, fill="black") # transiciones de la linea 1 self.canvas.create_text(125, 135, text='c,b/b', fill='black') self.canvas.create_text(125, 120, text='c,#/#', fill='black') self.canvas.create_text(125, 165, text='c,b/b', fill='black') # creacion del segundo estado self.canvas.create_oval(173, 95, 215, 130, width=2, fill='white') # circulo del segundo estado self.canvas.create_oval( 175, 120, 235, 180, width=5, fill='white') # circulo del arco de transicion de segundo estado self.canvas.create_text(205, 150, text='q', fill='black') # letra q self.canvas.create_line( 170, 125, 185, 128, width=2, fill="black") # Linea uno de la flecha de transicion Q self.canvas.create_line( 185, 115, 185, 128, width=2, fill="black") # Linea dos de la flecha de transicion Q # transiciones del segundo estado self.canvas.create_text(220, 85, text='a,a/λ', fill='black') self.canvas.create_text(220, 70, text='b,b/λ', fill='black') self.canvas.create_line(235, 150, 315, 150, width=5, fill='black') # linea de transicion de q a r self.canvas.create_line(300, 160, 315, 150, width=4, fill="black") self.canvas.create_line(300, 140, 315, 150, width=4, fill="black") # transicion de la linea 2 self.canvas.create_text(280, 165, text='λ,#/#', fill='black') # creacion del tercer estado self.canvas.create_oval(315, 120, 375, 180, width=5, fill='white') # circulo tercer estado self.canvas.create_oval( 320, 125, 370, 175, width=2, fill='white') # circulo de estado de aceptacion self.canvas.create_text(345, 150, text='r', fill='black') # letra r def generarPila(self): n = len(self.dato.get()) n = (int)(n / 2) n = n + 1 pos = 0 i = 0 for i in range(n): botonp = Button(self.root, text="_", fg="white", background="blue", command=self.PruebaDeAnimaciones) botonp.pack(padx=200, pady=200, ipadx=130, ipady=10) botonp.place(x=200, y=(120 - pos)) pos = pos + 25 self.listpila.append(botonp) self.listpila[0].configure(text="#") def iniciarAutomata(self): if self.validar() == False: return -1 self.iniciarGrafo() self.automata = Automata(self.dato.get()) self.hilo = threading.Thread(target=self.runAautomata) self.hilo.start() self.cambiarLetra(0) self.automata.setBandera(True) while (self.hilo.is_alive()): self.esperarCambios() self.actualizarGui() self.automata.setBandera(True) if (self.__indexE == 2): messagebox.showinfo("Resultado", "Es palindrome") self.root.destroy() else: messagebox.showinfo("Resultado", "No es palindrome") self.root.destroy() def esperarCambios(self): x = 0 while (True): if (self.automata.getBandera() == True): time.sleep(0.2) x += 1 if (x == 4): break else: break def actualizarGui(self): if (self.__indexE != self.automata.getEstado()): self.cambiarEstado(self.automata.getEstado()) if (self.transicionA != self.automata.getTransicion()): self.cambiarTransicionTexto(self.automata.getTransicion()) if (self.__indexP != self.automata.getLetra()): self.cambiarLetra(self.automata.getLetra()) self.cambiarPila(self.automata.getPila()) def cambiarPila(self, pilaaux): j = 0 for i in self.listpila: self.listpila[j].configure(text="_") j = j + 1 j = 0 for i in pilaaux.getVec(): self.listpila[j].configure(text=pilaaux.getVec()[j]) j = j + 1 def cambiarEstado(self, x): if (x == 1): self.OffestadoCirculoP() self.transcicionPQ() self.OnEstadocirculoQ() if (x == 2): self.OffEstadocirculoQ() self.TransicionQR() self.TextotransicionesQ(3) self.estadoAceptacion() if (x == 0): self.lineaini() self.OnestadoCirculoP() self.__indexE = x def cambiarTransicionTexto(self, i): self.transicionA = self.automata.getTransicion() if (self.__indexE == 0): self.transicionP() self.textoTransicionesP(i) if (self.__indexE == 1): self.TransicionQ() self.TextotransicionesQ(i) def cambiarLetra(self, i): if (self.__indexP == -1): self.lista[self.__indexP + 1].configure(background="red") self.root.update() if (len(self.dato.get()) > i): self.lista[i].configure(background="red") def runAautomata(self): self.automata.run() def PruebaDeAnimaciones(self): self.lineaini() self.OnestadoCirculoP() self.transicionP() j = 1 for i in range(1, 10): self.textoTransicionesP(j) j += 1 self.OffestadoCirculoP() self.transcicionPQ() self.OnEstadocirculoQ() self.TransicionQ() k = 1 for i in range(1, 4): self.TextotransicionesQ(k) k += 1 self.OffEstadocirculoQ() self.TransicionQR() self.estadoAceptacion() def lineaini(self): self.canvas.create_line(0, 150, 23, 150, width=4, fill="red") self.canvas.create_line(12, 140, 23, 150, width=4, fill="red") self.canvas.create_line(12, 160, 23, 150, width=4, fill="red") self.root.update() time.sleep(0.5) self.canvas.create_line(0, 150, 23, 150, width=4, fill="black") self.canvas.create_line(12, 140, 23, 150, width=4, fill="black") self.canvas.create_line(12, 160, 23, 150, width=4, fill="black") def transicionP(self): self.canvas.create_oval(23, 95, 65, 130, width=2, fill='blue') # circulo del primer estado self.root.update() time.sleep(0.5) self.canvas.create_oval(23, 95, 65, 130, width=2, fill='white') # circulo del primer estado def OnestadoCirculoP(self): self.canvas.create_oval(25, 120, 85, 180, width=5, fill='blue') # circulo del arco de transicion self.textoP() self.root.update() time.sleep(0.5) def OffestadoCirculoP(self): self.canvas.create_oval(25, 120, 85, 180, width=5, fill='white') # circulo del arco de transicion self.canvas.create_line( 20, 125, 35, 128, width=2, fill="black") # Linea uno de la flecha de transicion self.canvas.create_line( 35, 115, 35, 128, width=2, fill="black") # Linea dos de la flecha de transicion self.textoP() self.root.update() time.sleep(0.5) def textoP(self): self.canvas.create_text(55, 150, text='P', fill='black') # letra P def textoTransicionesP(self, i): if i == 9: self.canvas.create_text(125, 135, text='c,b/b', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(125, 135, text='c,b/b', fill='black') if i == 7: self.canvas.create_text(125, 120, text='c,#/#', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(125, 120, text='c,#/#', fill='black') if i == 8: self.canvas.create_text(125, 165, text='c,b/b', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(125, 165, text='c,b/b', fill='black') if i == 6: self.canvas.create_text(35, 85, text='a,#/#a', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(35, 85, text='a,#/#a', fill='black') if i == 5: self.canvas.create_text(35, 70, text='b,#/#b', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(35, 70, text='b,#/#b', fill='black') if i == 4: self.canvas.create_text(35, 55, text='a,a/aa', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(35, 55, text='a,a/aa', fill='black') if i == 3: self.canvas.create_text(35, 40, text='b,a/ab', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(35, 40, text='b,a/ab', fill='black') if i == 2: self.canvas.create_text(35, 25, text='a,b/ba', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(35, 25, text='a,b/ba', fill='black') if i == 1: self.canvas.create_text(35, 10, text='b,b/bb', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(35, 10, text='b,b/bb', fill='black') def transcicionPQ(self): self.canvas.create_line(160, 160, 175, 150, width=4, fill="blue") self.canvas.create_line(160, 140, 175, 150, width=4, fill="blue") self.canvas.create_line(85, 150, 175, 150, width=5, fill='blue') # linea de transicion de p a q self.root.update() time.sleep(0.5) self.canvas.create_line(85, 150, 175, 150, width=5, fill='black') self.canvas.create_line(160, 160, 175, 150, width=4, fill="black") self.canvas.create_line(160, 140, 175, 150, width=4, fill="black") # transiciones de la linea 1 def TransicionQ(self): self.canvas.create_oval(173, 95, 215, 130, width=2, fill='red') # circulo del segundo estado self.textoEstadoQ() self.root.update() time.sleep(0.5) self.canvas.create_oval(173, 95, 215, 130, width=2, fill='white') def OnEstadocirculoQ(self): self.canvas.create_oval( 175, 120, 235, 180, width=5, fill='blue') # circulo del arco de transicion de segundo estado self.textoEstadoQ() self.root.update() time.sleep(0.5) def OffEstadocirculoQ(self): self.canvas.create_oval( 175, 120, 235, 180, width=5, fill='white') # circulo del arco de transicion de segundo estado self.canvas.create_line( 170, 125, 185, 128, width=2, fill="black") # Linea uno de la flecha de transicion Q self.canvas.create_line( 185, 115, 185, 128, width=2, fill="black") # Linea dos de la flecha de transicion Q self.textoEstadoQ() self.root.update() def textoEstadoQ(self): self.canvas.create_text(205, 150, text='q', fill='black') # letra q def TextotransicionesQ(self, i): print("trasicion texto q ", i) if i == 2: self.canvas.create_text(220, 85, text='a,a/λ', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(220, 85, text='a,a/λ', fill='black') if i == 1: self.canvas.create_text(220, 70, text='b,b/λ', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(220, 70, text='b,b/λ', fill='black') if i == 3: self.canvas.create_text(280, 165, text='λ,#/#', fill='blue') self.root.update() time.sleep(0.5) self.canvas.create_text(280, 165, text='λ,#/#', fill='black') def TransicionQR(self): self.canvas.create_line(300, 160, 315, 150, width=4, fill="blue") self.canvas.create_line(300, 140, 315, 150, width=4, fill="blue") self.canvas.create_line(235, 150, 315, 150, width=5, fill='blue') # linea de transicion de q a r self.root.update() time.sleep(0.5) self.canvas.create_line(235, 150, 315, 150, width=5, fill='black') self.canvas.create_line(300, 160, 315, 150, width=4, fill="black") self.canvas.create_line(300, 140, 315, 150, width=4, fill="black") def estadoAceptacion(self): self.canvas.create_oval(315, 120, 375, 180, width=5, fill='white') # circulo tercer estado self.canvas.create_oval(320, 125, 370, 175, width=2, fill='blue') # circulo de estado de aceptacion self.canvas.create_text(345, 150, text='r', fill='black') # letra r self.root.update()
# -*- coding: utf-8 -*- #Imports import lightgbm as lgbm from graphviz import Digraph import pydotplus import networkx import sys import matplotlib.pyplot as plt from Automata import * from IPython.display import Image, display #Entrada 1 teste_1 = Automata() # Inicializa os estados S0 e S1 (sendo S1 um estado final) S0 = State('0') S1 = State('1', final=True) S2 = State('2') S3 = State('3') S4 = State('4') S5 = State('5') S6 = State('6') # Adiciona os estados à e-NFA teste_1.set_initial_state(S0) teste_1.add_state(S1) teste_1.add_state(S2) teste_1.add_state(S3)
import sys sys.path.append("AFN/") from Automata import * aut = Automata("A") aut2 = Automata("B") aut.printTupla() aut2.printTupla() aut = aut.concatenarAFN(aut2) aut.printTupla() aut3 = Automata("C") aut = aut.concatenarAFN(aut3) aut.printTupla() aut = aut.cerraduraPo() aut4 = Automata("D") aut4.printTupla() aut.printTupla() aut = aut.unirAFN(aut4) aut.printTupla() afd = aut.AFNtoAFD() print(aut.printTupla()) print(afd.printTupla()) aut.graphAutomata() afd.graphAutomata()
def __init__(self): self._cache = Cache() self._automata = Automata() self._coherenceMisses = 0 self._cacheMisses = 0
import Automata as atm gramatica={ "grafemas":{ "valores":[1,2,3], "operador":["*","+"]} } grafo=[ ["S",["grafemas,valores","S"],["grafemas,operador","Q1"]], ["Q1",["grafemas,valores","S"]] ] a=atm.Leng(gramatica,grafo) s=raw_input("Entre una oracion del lenguaje: ") a.run(s)
## Prof. Forster ## ## ## ## Equipe: ## ## Arthur Fernandes de Morais ## ## Gianluigi Dal Toso ## ## Lucas Alberto Bilobran Lema ## ## ## ########################################################### # Importa bibliotecas auxiliares from IPython.display import Image, display from Automata import * # Lê a expressão regular do usuário e constrói o autômato referênte à ela regEx = input('Digite a expressão regular: ') Machine = Automata() # Variável auxiliar para contar o número de grafos impressos graph_counter = 0 # ----- PASSO I: Inicialização do autômato ----- # Inicializa os estados S0 e S1 (sendo S1 um estado final) S0 = State('S0') S1 = State('S1', final=True) # Adiciona os estados à e-NFA Machine.set_initial_state(S0) Machine.add_state(S1) # Adiciona a transição S0 -> S1 à e-NFA utilizando a regEx de entrada