def AFNDtoAFD(automata, tipo):
    if tipo:
        dfa = DFA.from_nfa(automata)
        minimal_dfa = dfa.minify()
        return minimal_dfa, False
    else:
        return automata, tipo
Beispiel #2
0
 def test_init_nfa_more_complex(self):
     """Should convert to a DFA a more complex NFA."""
     nfa = NFA(
         states={'q0', 'q1', 'q2'},
         input_symbols={'0', '1'},
         transitions={
             'q0': {'0': {'q0', 'q1'}, '1': {'q0'}},
             'q1': {'0': {'q1'}, '1': {'q2'}},
             'q2': {'0': {'q2'}, '1': {'q1'}}
         },
         initial_state='q0',
         final_states={'q2'}
     )
     dfa = DFA.from_nfa(nfa)
     nose.assert_equal(dfa.states, {
         '{q0}', '{q0,q1}', '{q0,q2}', '{q0,q1,q2}'
     })
     nose.assert_equal(dfa.input_symbols, {'0', '1'})
     nose.assert_equal(dfa.transitions, {
         '{q0}': {'1': '{q0}', '0': '{q0,q1}'},
         '{q0,q1}': {'1': '{q0,q2}', '0': '{q0,q1}'},
         '{q0,q2}': {'1': '{q0,q1}', '0': '{q0,q1,q2}'},
         '{q0,q1,q2}': {'1': '{q0,q1,q2}', '0': '{q0,q1,q2}'}
     })
     nose.assert_equal(dfa.initial_state, '{q0}')
     nose.assert_equal(dfa.final_states, {'{q0,q1,q2}', '{q0,q2}'})
Beispiel #3
0
def main():
    nfa = NFA(  # this code builds the weakly divisible by 7 NFA
        states={'start_state', 'q0', 'q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q0prime', 'q1prime', 'q2prime', 'q3prime',
                'q4prime', 'q5prime', 'q6prime', 'fail_state'},
        input_symbols={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'},
        transitions={
            'start_state': {'0': {'fail_state'}, '1': {'q1', 'q0prime'}, '2': {'q2', 'q0prime'}, '3': {'q3', 'q0prime'},
                            '4': {'q4', 'q0prime'}, '5': {'q5', 'q0prime'}, '6': {'q6', 'q0prime'},
                            '7': {'q0', 'q0prime'},
                            '8': {'q1', 'q0prime'}, '9': {'q2', 'q0prime'}},
            'fail_state': {'0': {'fail_state'}, '1': {'fail_state'}, '2': {'fail_state'}, '3': {'fail_state'},
                           '4': {'fail_state'}, '5': {'fail_state'}, '6': {'fail_state'}, '7': {'fail_state'},
                           '8': {'fail_state'}, '9': {'fail_state'}},
            'q0': {'0': {'q0', 'q0prime'}, '1': {'q1', 'q0prime'}, '2': {'q2', 'q0prime'}, '3': {'q3', 'q0prime'},
                   '4': {'q4', 'q0prime'}, '5': {'q5', 'q0prime'}, '6': {'q6', 'q0prime'}, '7': {'q0', 'q0prime'},
                   '8': {'q1', 'q0prime'}, '9': {'q2', 'q0prime'}},
            'q1': {'0': {'q3', 'q1prime'}, '1': {'q4', 'q1prime'}, '2': {'q5', 'q1prime'}, '3': {'q6', 'q1prime'},
                   '4': {'q0', 'q1prime'}, '5': {'q1', 'q1prime'}, '6': {'q2', 'q1prime'}, '7': {'q3', 'q1prime'},
                   '8': {'q4', 'q1prime'}, '9': {'q5', 'q1prime'}, '': {'q1', 'q1prime'}},
            'q2': {'0': {'q6', 'q2prime'}, '1': {'q0', 'q2prime'}, '2': {'q1', 'q2prime'}, '3': {'q2', 'q2prime'},
                   '4': {'q3', 'q2prime'}, '5': {'q4', 'q2prime'}, '6': {'q5', 'q2prime'}, '7': {'q6', 'q2prime'},
                   '8': {'q0', 'q2prime'}, '9': {'q1', 'q2prime'}, '': {'q2', 'q2prime'}},
            'q3': {'0': {'q2', 'q3prime'}, '1': {'q3', 'q3prime'}, '2': {'q4', 'q3prime'}, '3': {'q5', 'q3prime'},
                   '4': {'q6', 'q3prime'}, '5': {'q0', 'q3prime'}, '6': {'q1', 'q3prime'}, '7': {'q2', 'q3prime'},
                   '8': {'q3', 'q3prime'}, '9': {'q4', 'q3prime'}, '': {'q3'}},
            'q4': {'0': {'q5', 'q4prime'}, '1': {'q6', 'q4prime'}, '2': {'q0', 'q4prime'}, '3': {'q1', 'q4prime'},
                   '4': {'q2', 'q4prime'}, '5': {'q3', 'q4prime'}, '6': {'q4', 'q4prime'}, '7': {'q5', 'q4prime'},
                   '8': {'q6', 'q4prime'}, '9': {'q0', 'q4prime'}, '': {'q4'}},
            'q5': {'0': {'q1', 'q5prime'}, '1': {'q2', 'q5prime'}, '2': {'q3', 'q5prime'}, '3': {'q4', 'q5prime'},
                   '4': {'q5', 'q5prime'}, '5': {'q6', 'q5prime'}, '6': {'q0', 'q5prime'}, '7': {'q1', 'q5prime'},
                   '8': {'q2', 'q5prime'}, '9': {'q3', 'q5prime'}, '': {'q5'}},
            'q6': {'0': {'q4', 'q6prime'}, '1': {'q5', 'q6prime'}, '2': {'q6', 'q6prime'}, '3': {'q0', 'q6prime'},
                   '4': {'q1', 'q6prime'}, '5': {'q2', 'q6prime'}, '6': {'q3', 'q6prime'}, '7': {'q4', 'q6prime'},
                   '8': {'q5', 'q6prime'}, '9': {'q6', 'q6prime'}, '': {'q6'}},
            'q0prime': {'0': {'q0prime'}, '1': {'q1prime'}, '2': {'q2prime'}, '3': {'q3prime'}, '4': {'q4prime'},
                        '5': {'q5prime'}, '6': {'q6prime'}, '7': {'q0prime'}, '8': {'q1prime'}, '9': {'q2prime'}},
            'q1prime': {'0': {'q3prime'}, '1': {'q4prime'}, '2': {'q5prime'}, '3': {'q6prime'}, '4': {'q0prime'},
                        '5': {'q1prime'}, '6': {'q2prime'}, '7': {'q3prime'}, '8': {'q4prime'}, '9': {'q5prime'}},
            'q2prime': {'0': {'q6prime'}, '1': {'q0prime'}, '2': {'q1prime'}, '3': {'q2prime'}, '4': {'q3prime'},
                        '5': {'q4prime'}, '6': {'q5prime'}, '7': {'q6prime'}, '8': {'q0prime'}, '9': {'q1prime'}},
            'q3prime': {'0': {'q2prime'}, '1': {'q3prime'}, '2': {'q4prime'}, '3': {'q5prime'}, '4': {'q6prime'},
                        '5': {'q0prime'}, '6': {'q1prime'}, '7': {'q2prime'}, '8': {'q3prime'}, '9': {'q4prime'}},
            'q4prime': {'0': {'q5prime'}, '1': {'q6prime'}, '2': {'q0prime'}, '3': {'q1prime'}, '4': {'q2prime'},
                        '5': {'q3prime'}, '6': {'q4prime'}, '7': {'q5prime'}, '8': {'q6prime'}, '9': {'q0prime'}},
            'q5prime': {'0': {'q1prime'}, '1': {'q2prime'}, '2': {'q3prime'}, '3': {'q4prime'}, '4': {'q5prime'},
                        '5': {'q6prime'}, '6': {'q0prime'}, '7': {'q1prime'}, '8': {'q2prime'}, '9': {'q3prime'}},
            'q6prime': {'0': {'q4prime'}, '1': {'q5prime'}, '2': {'q6prime'}, '3': {'q0prime'}, '4': {'q1prime'},
                        '5': {'q2prime'}, '6': {'q3prime'}, '7': {'q4prime'}, '8': {'q5prime'}, '9': {'q6prime'}}
        },
        initial_state='start_state',
        final_states={'q0', 'q0prime'}
    )

    str_length = int(input("Enter an integer for string length: "))
    dfa = DFA.from_nfa(nfa)  # creates a DFA from the above built NFA

    num_strings = count(str_length, dfa)
    print("The number of strings of length", str_length,
          "accepted by the DFA is", num_strings)
Beispiel #4
0
 def test_init_nfa_lambda_transition(self):
     """Should convert to a DFA an NFA with a lambda transition."""
     dfa = DFA.from_nfa(self.nfa)
     nose.assert_equal(dfa.states, {'{}', '{q0}', '{q1,q2}'})
     nose.assert_equal(dfa.input_symbols, {'a', 'b'})
     nose.assert_equal(dfa.transitions, {
         '{}': {'a': '{}', 'b': '{}'},
         '{q0}': {'a': '{q1,q2}', 'b': '{}'},
         '{q1,q2}': {'a': '{q1,q2}', 'b': '{q0}'},
     })
     nose.assert_equal(dfa.initial_state, '{q0}')
     nose.assert_equal(dfa.final_states, {'{q1,q2}'})
Beispiel #5
0
 def test_nfa_to_dfa_with_lambda_transitions(self):
     """ Test NFA->DFA when initial state has lambda transitions """
     nfa = NFA(
         states={'q0', 'q1', 'q2'},
         input_symbols={'a', 'b'},
         transitions={
             'q0': {'': {'q2'}},
             'q1': {'a': {'q1'}},
             'q2': {'a': {'q1'}}
         },
         initial_state='q0',
         final_states={'q1'}
     )
     dfa = DFA.from_nfa(nfa)  # returns an equivalent DFA
     nose.assert_equal(dfa.read_input('a'), '{q1}')
Beispiel #6
0
def afn_AFD(idA, conjunto, bandera):
    if idA in afn_api.keys() and idA not in afn_convertidos:
        afn = afn_api[idA].copy()
    else:
        afn = conjunto.buscaAfn(idA)

        edosId = set()
        edosfinales = set()
        edosinicial = set()
        ##Obtener transiciones
        dictrans = {}
        alfabeto = set()
        estadoinicial = ""
        for i in afn.edosAFN:
            # print(str(i.identificador))
            if (i.edoInicial == True):

                edosinicial.add(str(i.identificador))
                estadoinicial = str(i.identificador)
                if (len(edosinicial) > 1):
                    try:
                        os.system("cls")
                    except:
                        os.system("clear")
                    print("ERROR, HAY MAS DE UN ESTADO INICIAL")
                    print("ESTADOS INICIALES: " + str(edosinicial))

                    break
            if (i.edoFinal == True):
                edosfinales.add(str(i.identificador))
                agregarTokenEstado(str(i.identificador), str(i.token))
                ##agregardiccionario('',i.identificador)
            edosId.add(str(i.identificador))
            try:
                for j in i.transiciones:
                    var1 = str(j.simbolo)
                    var2 = str(j.simbolo2)
                    var3 = str(j.edoDestino.identificador)
                    elements_transiciones = elementos_transiciones(var1, var2)
                    for letra in elements_transiciones:

                        agregardiccionario(letra, var3)
                        if letra not in alfabeto:
                            if letra != '':
                                alfabeto.add(letra)

                dictrans[str(i.identificador)] = devolverdiccionario()

            except:

                auxtran = i.transiciones
                if auxtran == None:
                    agregardiccionario('', str(i.identificador))
                    dictrans[str(i.identificador)] = devolverdiccionario()
                else:
                    elements_transiciones = elementos_transiciones(
                        str(auxtran.simbolo), str(auxtran.simbolo2))
                    for letra in elements_transiciones:
                        agregardiccionario(
                            letra, str(auxtran.edoDestino.identificador))
                        if letra not in alfabeto:
                            if letra != '':
                                alfabeto.add(letra)
                    dictrans[str(i.identificador)] = devolverdiccionario()

        afn = NFA(states=edosId,
                  input_symbols=alfabeto,
                  transitions=dictrans,
                  initial_state=estadoinicial,
                  final_states=edosfinales)
        afn_api[idA] = afn
    afd = DFA.from_nfa(afn)
    transicionesafd = afd.transitions.copy()
    if bandera == 1:
        return afn
    else:
        pass
    #print("¿CONVERSION CORRECTA?")
    #print(afd.validate())
    # print(str(devolverTokens()))
    transicionesafd = afd.transitions.copy()
    diccionario_tokens = devolverTokens()
    a_borar = []
    for clave, valor in afd.transitions.items():
        if valor == '{}' or clave == '{}' or valor == None or clave == None or len(
                afd.transitions[clave]) == 0:
            try:
                del transicionesafd[clave]
                continue
            except:
                pass
        for j, h in valor.items():
            if h == '{}' or h == None or j == '{}':
                a_borar.append(j)
        for k in a_borar:
            try:
                del transicionesafd[clave][k]
            except:
                continue
        a_borar.clear()
    '''for clave in afd.transitions.keys():
        if clave == None or clave == '{}':
            try:
                del transicionesafd[clave]
            except:
                pass'''
    afd_api[idA] = afd
    archivoAFD = open("AFD.txt", "w")
    archivoAFD.write(
        "ESTADOS              :" +
        str(afd.states).replace("'{}',", '').replace(",'{}'", '') + "\n")
    archivoAFD.write("SIMBOLOS DE ENTRADA  :" +
                     str(afd.input_symbols).replace("'}'}, '{'", "}'}, '{\n") +
                     "\n")
    archivoAFD.write("TRANSICIONES         :" + str(transicionesafd) + "\n")
    archivoAFD.write("ESTADO INICIAL       :" + str(afd.initial_state) + "\n")
    archivoAFD.write("ESTADO(S) FINAL(ES)  :" + str(afd.final_states) + "\n")
    archivoAFD.write("TOKENS (CLAVE, VALOR):" + str(diccionario_tokens))
    archivoAFD.close()
    # VAMONOS CON RICK
    estados_rick = open("estados.pickle", "wb")
    #estados_rick = open("lexEdos.pickle", "wb")
    pickle.dump(afd.states, estados_rick)
    estados_rick.close()

    alfabeto_rick = open("alfabeto.pickle", "wb")
    #alfabeto_rick = open("lexAlfa.pickle", "wb")
    pickle.dump(afd.input_symbols, alfabeto_rick)
    alfabeto_rick.close()

    transiciones_rick = open("transiciones.pickle", "wb")
    #transiciones_rick = open("lexTransitions.pickle", "wb")
    pickle.dump(afd.transitions, transiciones_rick)
    transiciones_rick.close()

    edoInicial_rick = open("edosInicial.pickle", "wb")
    #edoInicial_rick = open("lexEdoIni.pickle", "wb")
    pickle.dump(afd.initial_state, edoInicial_rick)
    edoInicial_rick.close()

    edosFinales_rick = open("edosFinales.pickle", "wb")
    #edosFinales_rick = open("lexEdoFin.pickle", "wb")
    pickle.dump(afd.final_states, edosFinales_rick)
    edosFinales_rick.close()

    tokens_rick = open("token.pickle", "wb")
    #tokens_rick = open("lexToken.pickle", "wb")
    pickle.dump(diccionario_tokens, tokens_rick)
    tokens_rick.close()
Beispiel #7
0
def afn_AFD(idA, conjunto, bandera):
    if idA in afn_api.keys() and idA not in afn_convertidos:
        afn = afn_api[idA].copy()
    else:
        aux3 = copy.deepcopy(conjunto.con)

        for i in aux3:
            if i.idAFN == idA:
                afn = i
        # estados

        edosId = set()
        edosfinales = set()
        edosinicial = set()
        ##Obtener transiciones
        dictrans = {}
        alfabeto = set()
        estadoinicial = ""
        for i in afn.edosAFN:
            if (i.edoInicial == True):
                edosinicial.add(str(i.identificador))
                estadoinicial = str(i.identificador)
                if (len(edosinicial) > 1):
                    print("ERROR, HAY MAS DE UN ESTADO INICIAL")
                    break
            if (i.edoFinal == True):
                edosfinales.add(str(i.identificador))
            edosId.add(str(i.identificador))
            try:
                for j in i.transiciones:
                    var1 = str(j.simbolo)

                    if j.simbolo == None or j.simbolo == " ":
                        var1 = ''
                    else:
                        alfabeto.add(var1)
                    var2 = str(j.edoDestino.identificador)
                    agregardiccionario(var1, var2)
                dictrans[str(i.identificador)] = devolverdiccionario()

            except:
                auxtran = i.transiciones
                if auxtran == None:
                    print(str(i.identificador))
                    agregardiccionario('', str(i.identificador))
                    dictrans[str(i.identificador)] = devolverdiccionario()
                else:
                    if auxtran.simbolo == " ":
                        var1 = ''
                    else:
                        var1 = str(auxtran.simbolo)
                        alfabeto.add(var1)
                    agregardiccionario(var1, str(auxtran.edoDestino.identificador))
                    dictrans[str(i.identificador)] = devolverdiccionario()
        afn = NFA(
            states=edosId,
            input_symbols=alfabeto,
            transitions=dictrans,
            initial_state=estadoinicial,
            final_states=edosfinales
        )
        afn_api[idA] = afn
    afd = DFA.from_nfa(afn)

    transicionesafd = afd.transitions.copy()

    if bandera == 1:
        return afn
    else:
        pass
    print("¿CONVERSION CORRECTA?")
    print(afd.validate())
    for k, i in afd.transitions.items():

        for clave, valor in i.items():
            if clave == '{}' or clave == None or valor == '{}' or valor == None:
                del transicionesafd[k]
    for clave in afd.transitions.keys():
        if clave == None or clave == '{}':
            try:
                del transicionesafd[clave]
            except:
                pass
    print("TRANSICIONES AFD")
    print(str(transicionesafd))
    afd_api[idA] = afd
Beispiel #8
0
def convert_to_dfa(automaton):
    """
    Convert an undeterministic automaton to a deterministic one.
    """
    return DFA.from_nfa(automaton)
Beispiel #9
0
def AFNDtoAFD(automata):

    dfa = DFA.from_nfa(automata)

    return dfa
Beispiel #10
0
#thompson alg output returns a NFA transition table
thompsonOutput = thompsonsAlg.thompsonsAlg(regexToMatch)


#let's try building an NFA!
nfa = NFA(
    states=set(thompsonOutput.s.keys()),
    input_symbols= set(thompsonOutput.keys),
    transitions= thompsonOutput.s,
    initial_state= list(thompsonOutput.s.keys())[0],
    final_states= {list(thompsonOutput.s.keys())[len(list(thompsonOutput.s.keys())) -1]}
)

#build a DFA from NFA (wow i'm really trusting this library with my grade)
dfa = DFA.from_nfa(nfa)

#check for NFA and DFA and generate DOT files also outputs a PDF of the same name
if(args.DFA):
    #makes sure it ends with the right file type
    if(not args.DFA.endswith(".dot")):
        fileName = args.DFA + ".dot"

        dot.graphDFA(dfa, fileName)
    else:
        dot.graphDFA(dfa, args.DFA)
else:
    pass

if(args.NFA):
    if(not args.NFA.endswith(".dot")):
Beispiel #11
0
def determinize(fsm):
    if type(fsm) is NFA:
        return DFA.from_nfa(fsm)
    else:
        return fsm
Beispiel #12
0
    states={'q0', 'q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8'},
    input_symbols={'a', 'b'},
    transitions={
        # Use '' as the key name for empty string (lambda/epsilon) transitions
        'q0': {'a': {'q3'}, '': {'q1'}},
        'q1': {'a': {'q4'}, '': {'q2'}},
        'q2': {'b': {'q5'}, '': {'q0'}},
        'q3': {'b': {'q6'}},
        'q4': {'a': {'q7'}},
        'q5': {'b': {'q8'}},
        'q6': {},
        'q7': {'': {'q8'}},
        'q8': {'': {'q2'}}

    },
    initial_state='q0',
    final_states={'q6'}
)

dfa = DFA.from_nfa(nfa)  # returns an equivalent DFA

print("DFA table")
print(dfa.transitions, "\n")

print("Intial State: ", dfa.initial_state)
print("Final State: ", dfa.final_states, "\n")

print("check whether the string is accepted or not")
print(nfa.accepts_input('bbab'))

Beispiel #13
0
def markovDFA(pattern):
    nfa = markovNFA(pattern)
    return DFA.from_nfa(nfa)
Beispiel #14
0
        'q2': {
            'b': {'q0'}
        }
    },
    initial_state='q0',
    final_states={'q1'})

if nfa.validate():
    print("\nThe NFA is accepted.")
    s2 = input("Enter the Input String: ")
    if nfa.accepts_input(s2):
        print('Accepted!')
        print("The final state that the NFA stopped on:", nfa.read_input(s2))
    else:
        print('Rejected!')
else:
    print("\nThe new NFA is rejected.")
""" NFA-DFA conversion """

equivalent_dfa = DFA.from_nfa(nfa)
if equivalent_dfa.validate():
    print("\nIts Equivalent DFA is accepted.")
    s3 = input("Enter the Input String: ")
    if equivalent_dfa.accepts_input(s3):
        print('Accepted!')
        print("The final state that the Equivalent DFA stopped on:",
              equivalent_dfa.read_input(s3))
    else:
        print('Rejected!')
else:
    print("\Its Equivalent DFA is rejected.")
Beispiel #15
0
def make_DFA_for_pinword(u: str) -> "DFA":
    #print("    Creating DFA for pinword: {}".format(u))
    return DFA_name_reset(DFA.from_nfa(make_NFA_for_pinword(u)))