Beispiel #1
0
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
Beispiel #2
0
 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
Beispiel #3
0
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()
Beispiel #5
0
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
Beispiel #6
0
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()
Beispiel #7
0
###########################################################
## 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)
Beispiel #8
0
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")
Beispiel #10
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
Beispiel #11
0
    def __init__(self):
        self._cache = Cache()
        self._automata = Automata()

        self._coherenceMisses = 0
        self._cacheMisses = 0
Beispiel #12
0
# -*- 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)