Exemple #1
0
 def test_Put_morph(self):
     correct_dict = {
         0: {
             'a': 1,
             'b': 2
         },
         1: {
             'a': 3,
             'b': 5
         },
         2: {
             'a': 3,
             'b': 2
         },
         3: {
             'a': 3,
             'b': 4
         },
         4: {
             'a': 3,
             'b': 2
         },
         5: {
             'a': 5,
             'b': 5
         }
     }
     dfa = Dfa(read_automaton())
     set_minimized = dfa._minimize(dfa._final_or_not())
     complete_dfa = dfa._put_the_morphs(set_minimized)
     self.assertEqual(complete_dfa, correct_dict)
Exemple #2
0
 def test_Minimize(self):
     correct_sets = [{0}, {1}, {2}, {3}, {4}, {5, 6, 7}]
     dfa = Dfa(read_automaton())
     comparative = all(
         map(lambda x: True if x in correct_sets else False,
             dfa._minimize(dfa._final_or_not())))
     self.assertTrue(comparative)
Exemple #3
0
 def __init__(self, automaton):
     self.__automaton = automaton
     if self.automaton["deterministic"]:
         self.heritage = Dfa(automaton)
     elif not self.automaton["deterministic"]:
         self.heritage = Nfa(automaton)
     else:
         raise TypeError
Exemple #4
0
    def createRootClone(self, description, tapeStr, name, keepHistory):
        """Create the root clone of this nondeterministic Turing
        machine.
        
        Overrides NDTuringMachine.createRootClone(). See that method
        for documentation.

        """
        return Dfa(description, tapeStr, 0, name, keepHistory=keepHistory)
Exemple #5
0
 def make_new_dfa_with_new_ids(self, sf):
     """
     sf: SplitFind
     """
     new_dfa = Dfa()
     # make new_dfa with new ids
     for state in self.dfa.states.keys():
         assert (self.dfa.states[state] is not None)
         converted = sf.find(state)
         new_dfa.states[converted] = {}
         for char, dst in self.dfa.states[state].items():
             new_dfa.states[converted][char] = sf.find(dst)
     # register start_key, accepted_keys
     start_nfa_key = 0  #FIXME hard cording
     accepted_nfa_key = 1  # FIXME hard cording
     for old_key, new_key in sf.arr.items():
         assert (type(old_key) is HashableSet)
         if accepted_nfa_key in old_key:
             new_dfa.accepted_keys.add(new_key)
         elif start_nfa_key in old_key:
             new_dfa.start_key = new_key
     return new_dfa
Exemple #6
0
 def test_Dictionary(self):
     correct_dict = {
         0: {
             'a': 1,
             'b': 2
         },
         1: {
             'a': 3,
             'b': 5
         },
         2: {
             'a': 3,
             'b': 2
         },
         3: {
             'a': 3,
             'b': 4
         },
         4: {
             'a': 3,
             'b': 2
         },
         5: {
             'a': 6,
             'b': 7
         },
         6: {
             'a': 6,
             'b': 5
         },
         7: {
             'a': 6,
             'b': 7
         }
     }
     dfa = Dfa(read_automaton())
     self.assertEqual(correct_dict, dfa.dictionary)
Exemple #7
0
 def __init__(self, nfa):
     self.nfa = nfa
     self.dfa = Dfa()
     self.epsilon_extented = {}  # key is HashableSet, value is HashableSet
def convertNfaToDfa(nfaString):
    nfa = Nfa(nfaString, name = 'sourceNfa')

    # print('source nfa is', nfa.write())

    dfa = Dfa(None, name = 'destDfa')
    # Dictionary of states in destDfa. Key is the name of the state (e.g. q0, qA),
    # and value is the set of states in sourceNfa to which the destDfa
    # state corresponds.
    stateToSubset = dict()
    # As above, but the key is the value and vice versa
    subsetToState = dict()

    # Find out where we can get to in the nfa without consuming any symbols.
    initialStateSet = getAllStayDests(nfa, set([TuringMachine.startState]))

    # If we can immediately reach the accept state, we are in the
    # special case of accepting all strings, so construct and return a
    # suitable dfa.
    if TuringMachine.acceptState in initialStateSet:
        t = Transition(TuringMachine.startState, TuringMachine.acceptState,
                       TuringMachine.anySym, None, TuringMachine.rightDir)
        dfa.addTransition(t)
        return dfa.write()

    # Begin the core algorithm by creating the first state in the dfa,
    # which corresponds to the subset of states in the NFA that can be
    # reached without consuming any symbols.
    stateToSubset[TuringMachine.startState] = initialStateSet
    subsetToState[ initialStateSet  ] = TuringMachine.startState

    # Also create an accept state
    stateToSubset[TuringMachine.acceptState] = frozenset([TuringMachine.acceptState])
    subsetToState[ frozenset([TuringMachine.acceptState])  ] = TuringMachine.acceptState
    
    # Keep track of which states in the dfa have not yet been processed
    unprocessedDfaStates = [TuringMachine.startState]

    iteration = 0 # for debugging
    while len(unprocessedDfaStates)>0:
        # print('iteration:', iteration); iteration+=1
        dfa.unifyTransitions(); # print(dfa.write())
        dfaState = unprocessedDfaStates.pop()
        nfaStates = stateToSubset[dfaState]

        # print('processing dfa state', dfaState, 'corresponding to nfa states', nfaStates)

        # 'transitions' will store transitions from dfaState.
        # key is label, value is a set of destinations
        transitions = dict()
        for c in TuringMachine.validSymbols:
            transitions[c] = set()
        for nfaState in nfaStates:
            # print('processing nfaState', nfaState)
            transitionList = nfa.getTransitions(nfaState)
            # print('transitions are', transitionList)
            for t in transitionList:
                for c in TuringMachine.validSymbols:
                    # The special anySym symbol with the 'stay'
                    # direction represents an epsilon-transition.
                    # These will be dealt with separately. For now,
                    # don't consider these to be matches.
                    if t.label==TuringMachine.anySym and \
                       t.direction == TuringMachine.stayDir:
                        continue
                    if nfa.labelMatchesSymbol(c, t.label):
                        # print(c, 'matches label', t.label)
                        if t.destState != TuringMachine.rejectState:
                            # print('adding transition with label', c, 'and dest', t.destState)
                            transitions[c].add(t.destState)
        # Expand the destinations by following all epsilon-transitions.
        # The values will now be frozensets, which is what we need.
        for c in TuringMachine.validSymbols:
            transitions[c] = getAllStayDests(nfa, transitions[c])
        # Add any new transitions to the dfa
        for label, subset in transitions.items():
            if len(subset) == 0:
                continue
            if subset not in subsetToState:
                name = getNewStateName(stateToSubset)
                stateToSubset[name] = subset
                subsetToState[subset] = name
                unprocessedDfaStates.append(name)
            else:
                name = subsetToState[subset]
            tr = Transition(dfaState, name, label, None, TuringMachine.rightDir)
            dfa.addTransition(tr)

    # not strictly necessary, but makes the representation easier to test
    dfa.unifyTransitions()

    return dfa.write()
Exemple #9
0
# Joseph Frazier
# CSCE 355
# December 6, 2018
# main
#!/usr/bin/env python
import sys
from dfa import Dfa
from dfs import Dfs

r1 = Dfa()
properties = ""
empNonemp = False

# Opens the DFA text file and fills out the dfa statistics:
# State Number, Accepting States, Alphabet, and State Changes
flDfa = open(sys.argv[1])

r1.set_statesNo(int(flDfa.readline()[18:-1]))

r1.set_accepting(flDfa.readline()[18:-1])

r1.set_alphabet(flDfa.readline()[10:-1])

tempStates = []
for i in range(0, r1.statesNo):
    tempStates.append(flDfa.readline()[0:-1])

r1.set_states(tempStates)
flDfa.close()

# sets up reachable states from 0
Exemple #10
0
import json

from nfa import Nfa
from dfa import Dfa

if __name__ == "__main__":
    with open("json/dfa.json", "r") as f:
        data = json.load(f)

        con = Dfa(data)
        c = con.minimize()
        print(c.minimize())
        print(c.read("aab"))
        print(con.read("aab"))
    with open("json/nfa.json", "r") as f:
        data = json.load(f)
        con = Nfa(data)
        h = con.determine()
        print(h)
        print(con.read("ab"))
        a = h.dot_dictionary("hola")
        print(a)
Exemple #11
0
 def _to_dfa(self, dictionary_convert: dict) -> Dfa:
     return Dfa({
         'deterministic': True,
         'alphabet': self.__alphabet,
         'states': self._generate_list_states_dfa(dictionary_convert)
     })
Exemple #12
0
def main():
    parser = argparse.ArgumentParser(
        description='Tool to transform regex to DFA')
    parser.add_argument('alphabet', type=str, help='Alphabet of REGEX.')
    parser.add_argument('regex', type=str, help='Regular expression.')
    parser.add_argument(
        '--visualizer',
        action='store_true',
        help='Add this flag for printing the DFA in graphviz format.')

    args = parser.parse_args()
    regex = args.regex
    alphabet = args.alphabet

    global visualizer
    visualizer = args.visualizer

    regex = '(' + regex + ')#'  # mark the end of the expression
    (tree, k, cnt_nodes) = make_expression_tree(regex, alphabet)

    global follow_pos
    follow_pos = [[]] * (k + 1)
    global leaf
    leaf = [0] * (k + 1)

    compute_functions(tree)
    compute_follow_pos(tree)

    for i in range(1, k + 1):
        follow_pos[i] = set(follow_pos[i])

    # Q, sigma, delta, q0, F
    dfa = Dfa(sigma=alphabet)
    is_final = False
    if k in tree.get_first_pos():
        is_final = True
    dfa.q0 = dfa.new_state(tree.get_first_pos(), is_final)
    p = 0
    u = 0
    while p <= u:
        for ch in alphabet:
            all_follow_pos = set([])
            for x in dfa.get_pos(p):
                if leaf[x] == ch:
                    all_follow_pos = all_follow_pos.union(follow_pos[x])
            if len(all_follow_pos) != 0:
                if dfa.is_state_already(all_follow_pos) == False:
                    is_final = False
                    if k in all_follow_pos:
                        is_final = True
                    new_state = dfa.new_state(all_follow_pos, is_final)
                    dfa.add_transition(dfa.get_state(p), ch, new_state)
                    u += 1
                else:
                    state = dfa.search_state(all_follow_pos)
                    dfa.add_transition(dfa.get_state(p), ch, state)
        p += 1
    if visualizer == True:
        f = open('dfa.out', 'w')
        f.write(dfa.str_graphviz_web_format())
    else:
        print(dfa)
Exemple #13
0
def simulateDfa(dfaString, inString):
    tm = Dfa(dfaString)
    tm.reset(inString)
    tmResult = tm.run()
    return tmResult
Exemple #14
0
# Joseph Frazier
# CSCE 355
# December 6, 2018
# main
#!/usr/bin/env python
import sys
from dfa import Dfa

r1 = Dfa()

# Opens the DFA text file and fills out the dfa statistics:
# State Number, Accepting States, Alphabet, and State Changes
flDfa = open(sys.argv[1])

r1.set_statesNo(int(flDfa.readline()[18:-1]))

r1.set_accepting(flDfa.readline()[18:-1])

r1.set_alphabet(flDfa.readline()[10:-1])

tempStates = []
for i in range(0, r1.statesNo):
    tempStates.append(flDfa.readline()[0:-1])

r1.set_states(tempStates)
flDfa.close()

# goes through the test trings and runs them against the dfa
dfainput = open(sys.argv[2])

testString = dfainput.readline()