def build_dfa(self, syms): dfa = DFA() start_set = self.eps_closure_of([self.nfa.start]) queue = list() # this is actually a BFS graph traverse algorithm queue.append(start_set) # except that the vertex is a set visited_set = [] dfa_states_map = dict() dfa_states_map[repr(start_set)] = self.gen_state() dfa.start = dfa_states_map[repr(start_set)] while queue: cur_set = queue[0] queue = queue[1:] # de-queue visited_set.append(cur_set) # print('cur: {}'.format(cur_set)) if self.nfa.final in cur_set: if dfa_states_map[repr(cur_set)] not in dfa.final: dfa.final.append(dfa_states_map[(repr(cur_set))]) for c in syms: next_set = self.eps_closure_of(list(self.nfa.move(cur_set, c))) # print('next: {}'.format(next_set)) if next_set not in visited_set: queue.append(next_set) # enqueue if repr(next_set) not in dfa_states_map: dfa_states_map[repr(next_set)] = self.gen_state() dfa.add_trans(dfa_states_map[repr(cur_set)], dfa_states_map[repr(next_set)], c) return dfa
def to_dfa(self): done = set() dfa = DFA() init_nstate = frozenset({0}) nstates = [ init_nstate ] encode = { init_nstate: 0 } encoding = 1 while len(nstates) > 0: nstate = nstates.pop() if nstate in done: continue done.add(nstate) # print("\nMaking state {} deterministic...".format(self.frozenstr(nstate))) for char in list(range(UNICODE_LATIN_START, UNICODE_LATIN_END)): dstate = set() for ns in nstate: if char in self.table[ns]: # print("Through char '{}'...".format(chr(char))) for t in self.table[ns][char]: # print("Target '{}'".format(t)) dstate.add(t) if len(dstate) > 0: frozen_dstate = frozenset(dstate) nstates.append(frozen_dstate) if frozen_dstate not in encode: encode[frozen_dstate] = encoding if encoding >= len(dfa.table): dfa.table.append(OrderedDict()) encoding += 1 # print("dstate: {}, encoded: {}".format(self.frozenstr(frozen_dstate), encode[frozen_dstate])) dfa.table[encode[nstate]][char] = encode[frozen_dstate] if self.is_final(frozen_dstate): dfa.finals.add(encode[frozen_dstate]) return dfa
def show_DFA(): contract_id = request.form.get('contract_id', default='id') username = request.form.get('username', default='user') contract = db.get_contract(username, contract_id) print("当前条款: ",contract[10]) DFA.create_fsm(contract[10], contract_id) fsm_struct = util.read_fsm(contract_id) res = {'fsm': fsm_struct } print(fsm_struct) return json.dumps(res), 200
def toDFA(self): self.alphabet.remove("$") result = DFA(self.get_accept_state().id) new_start = State([], NFA.counter.get_next_id(), self.closure(self.get_start_state())) result.add_state([new_start]) visited = [] visited.append(self.closure(self.get_start_state())) self.dfa_next(self.closure(self.get_start_state()), new_start, result, visited) return result
def main(): m = DFA() m.generate() # TO TEST TIME, will open new window, works on pycharm, not sure on terminal # time_results(m) # TO TEST TIME, will open new window, works on pycharm, not sure on terminal print("Spanning Trees will be encoded in the form:\n\n" "XXXXX XXXXX XXXXX ..... ..... XXXXX EXX\n\n" "where X = {0, 1} depending if that edge is present.\n" "Spaces are allowed but not required, the XXXXX blocks\n" "must be length 5, and must have EXX to signal the ending.\n") print("EXAMPLE:\n") print("o---o o o---o") print(" | | | |") print("o---o---o---o o") print("| | |") print("o---o o o---o\n") print("ENCODING: 10111 01100 01110 11001 E11\n") print("Enter the problem # you want to solve.") print("------------------------------------------------------") print("(1) Number of accepted spanning trees in a 3 x n Graph\n" "(2) Enter encoded tree to test acceptance\n" "(3) Specified Edges Spanning Tree\n" "(4) Quit") print("------------------------------------------------------") option = int(input()) while option is not 4: if option == 1: print("------------------------------------------------------") count(m, False, '') elif option == 2: print("------------------------------------------------------") test_string(m) elif option == 3: print("------------------------------------------------------") specified_edges(m, False, '') print("------------------------------------------------------") print("(1) Number of accepted spanning trees in a 3 x n Graph\n" "(2) Enter encoded tree to test acceptance\n" "(3) Specified Edges Spanning Tree\n" "(4) Quit") print("------------------------------------------------------") option = int(input()) print("Quitting...")
def findSong(contour): songsFound = [] with open("midiTracks.csv", newline = '',encoding = "ISO-8859-1") as file: contents = csv.reader(file) dfa = DFA(contour) for row in contents: for i in range(3,len(row)): if len(songsFound) == 50: #limits return list to 50 songs return songsFound stringsFound = dfa.search(row[i]) if stringsFound > 0: songsFound.append(Song(row[0], row[1], row[2], stringsFound)) if len(songsFound) > 0: return songsFound return None
def stateDFA(self): worksheet=DFA.open_worksheet(self.location) sheet=worksheet.sheet_by_index(0) self.Q=sheet.rowval(0) print(self.Q)
def toDFA(self): """ convert NFA to DFA """ import DFA def rename_state(state): import re return re.sub(r"[\{\}\,\sØ]", r"", f"[{state}]") q0 = rename_state(Set(self.q0)) Q = Set(Set(self.q0)) δ = DFA.δ() F = Set() Done = Set() while (Q - Done) != Set(): M = (Q - Done).pop(0) if M.intercept(self.F) != Set(): F = F.union(Set(M)) for a in self.Σ: N = Set.Union([self.δ[p, a] for p in M]) Q = Q.union(Set(N)) δ[rename_state(M), a] = rename_state(N) Done = Done.union(Set(M)) Q = Set([rename_state(qi) for qi in Q]) δ = DFA.δ({(qi, a): Set(target) for (qi, a), target in δ.items()}) F = Set([rename_state(qf) for qf in F]) return DFA(Q, self.Σ, δ, q0, F)
def test_DFA(self): #A variety of patterns and texts to test with d1 = DFA("rrududr") self.assertEqual(d1.search("rrududruuurrududrrurud"),2) d2 = DFA("r") self.assertEqual(d2.search("rrrrrrrrrr"),10) d3 = DFA("urd") self.assertEqual(d3.search("uuuuuuuuuudrdruuuudddr"),0) txt = "uurududuruuu" #A very long text for r in range(500): txt+="rrr" d4 = DFA("dudr") self.assertEqual(d4.search(txt),0) d5 = DFA("r") self.assertEqual(d5.search(txt),1502)
def NFA_to_DFA(): t_start = "q1" t_final = ['q1'] t_states = ["q1", "q2", "q3"] t_symbols = ['a', 'b'] t_trans = { 'q1': { 'b': ['q2'], 'e': ['q3'] }, 'q2': { 'a': ['q2', 'q3'], 'b': ['q3'] }, 'q3': { 'a': ['q1'], }, } t_nfa = NFA.NFA(t_states, t_symbols, t_trans, t_start, t_final) t_dfa = DFA.trans_NFA(t_nfa) print("start state:", end="") print(t_dfa.start_state) print("final states:", end="") print(t_dfa.final_states) print("states:", end="") print(t_dfa.states) print("trans:", end="") print(t_dfa.trans)
def run_lstar(teacher, time_limit): print('run_lstar') table = ObservationTable(teacher.alphabet, teacher) start = clock() teacher.counterexample_generator.set_time_limit(time_limit, start) table.set_time_limit(time_limit, start) while True: while True: while table.find_and_handle_inconsistency(): pass if table.find_and_close_row(): continue else: break dfa = DFA.DFA(obs_table=table) print("obs table refinement took " + str(int(1000 * (clock() - start)) / 1000.0)) counterexample = teacher.equivalence_query(dfa) if counterexample == None: break start = clock() table.add_counterexample(counterexample, teacher.classify_word(counterexample)) return dfa
def main(): NFA = nfa.NFA print("NFA=",NFA) DFA = nfa.nfa_to_dfa() print("DFA=",DFA) min_DFA = dfa.min_dfa(DFA) print("minDFA=",min_DFA)
def findSong(contour): songsFound = [] with open("midiTracks.csv", newline='', encoding="ISO-8859-1") as file: contents = csv.reader(file) dfa = DFA(contour) for row in contents: for i in range(3, len(row)): if len(songsFound) == 50: #limits return list to 50 songs return songsFound stringsFound = dfa.search(row[i]) if stringsFound > 0: songsFound.append( Song(row[0], row[1], row[2], stringsFound)) if len(songsFound) > 0: return songsFound return None
def _reduce(self, imax=None): from utils import roman import DFA def init(i): """ split into two groups I - non terminal II - terminal """ groups = { qi: roman(1) if qi not in self.F else roman(2) for qi in self.Q } δ = DFA.δ(Q=self.Q, Σ=self.Σ) for qi in (self.Q - self.F) + self.F: for a in self.Σ: δ[qi, a] = groups.get(self.δ[qi, a]) if imax is None or i < imax: return step(i + 1, groups, δ) return groups, δ def step(i, groups, δ): new_groups = {} force_move = 0 numeratd_patterns = [] for i in range(len(Set(groups.values()))): for qi, val in groups.items(): target = δ.group()[qi] if val == roman(i + 1): if target not in numeratd_patterns: numeratd_patterns.append(target) index = numeratd_patterns.index(target) new_groups[qi] = roman(index + 1 + force_move) force_move += len(numeratd_patterns) numeratd_patterns = [] new_δ = DFA.δ() for qi in self.Q: for a in self.Σ: new_δ[qi, a] = new_groups.get(self.δ[qi, a]) if (imax is None or i < imax) and groups != new_groups and δ != new_δ: return step(i + 1, new_groups, new_δ) return new_groups, new_δ groups, new_δ = init(0) Q = Set(groups.values()) q0 = groups[self.q0] δ = DFA.δ() for (qi, a), target in new_δ.items(): δ[groups[qi], a] = target F = Set(groups[qf] for qf in self.F) return DFA(Q, self.Σ, δ, q0, F)
def convert_to_dfa(self): ### convert here dfa_table = {} ## state of states that have been seen seen = self.start added_to_table = set() while len(seen) > 0: cur_state = seen.pop(0) added_to_table.add(cur_state) for l in self.alphabet: state_set = set() ## just a single state not a subset if (len(cur_state) == 1) and (cur_state[0], l) in self.transitions: for dest in self.transitions[(cur_state[0], l)]: state_set.add(dest) else: for s in cur_state: if (s, l) in self.transitions: for dest in self.transitions[(s, l)]: state_set.add(dest) dfa_table[(cur_state, l)] = state_set if tuple(state_set) not in added_to_table and tuple( state_set) not in seen: seen.append(tuple(state_set)) dfa_states = set() dfa_accept = [] dfa_transitions = {} for k, v in dfa_table.items(): source_str = ",".join(k[0]) dest_str = ",".join(v) ## add appropriate accepting states for accept_state in self.accept: if accept_state in k[0]: if source_str not in dfa_accept: dfa_accept.append(source_str) if accept_state in v: if dest_str not in dfa_accept: dfa_accept.append(dest_str) dfa_states.add(source_str) dfa_states.add(dest_str) dfa_transitions[(source_str, k[1])] = dest_str dfa = DFA(dfa_states, self.alphabet, dfa_transitions, self.start, dfa_accept) return dfa
def main(): M = DFA() M.generate() # Creates a table containing n = string length, and states S all set to 0 n = int(input('Enter a positive integer between 1 and 300 (inclusive)\n')) s = M.states_length() # table = [[0 for j in range(n+1)] for i in range(s)] prev = [0 for _ in range(s)] next = [0 for _ in range(s)] for i in range(0, s): state = M.get_state_by_id(i) if state in M.accepting_states: # BASE CASE N(j, 0) = 1 if j ∈ F, N(j, 0) = 0 if j NOT ∈ F prev[i] = 1 else: pass for j in range(1, n + 1): for i in range(0, s): state = M.get_state_by_id(i) state_a = state.on_a state_b = state.on_b state_c = state.on_c state_d = state.on_d next[i] = prev[state_a.ID] + prev[state_b.ID] + prev[ state_c.ID] + prev[state_d.ID] prev = next.copy() print('N(0, ' + str(n) + ') = ' + str(next[0]))
def DFA_constructor(w, k, sigma): """ Hamming Automata Construction """ n = len(w) # the length of input string w # Find the number of states from w, k nbS = 0 for i in range(k + 1): nbS += n + 1 - i nbS += 1 # Consider the sink state # Decaler empty initial, transition, final probabilities initial = np.zeros(nbS, dtype=np.float64) final = np.zeros(nbS, dtype=np.float64) transition = {} for alphabet in sigma: transition[alphabet] = np.zeros((nbS, nbS), dtype=np.float64) # Define the final states final_index = n for i in range(k + 1): final[final_index] = 1.0 final_index += n - i # Define the initial state initial[0] = 1.0 # Define the transition matrices current_state = 0 w_index = 0 for i in range(k + 1): w_index = i for j in range(n + 1 - i): for alphabet, tm in transition.items(): if final[current_state] != 1 and alphabet == w[w_index]: next_state = current_state + 1 tm[current_state, next_state] = 1.0 elif final[ current_state] == 1: # final state goes to sink state next_state = nbS - 1 tm[current_state, next_state] = 1.0 else: next_state = current_state + (n + 1 - i) if next_state < nbS: # check if the state index grows over the limit tm[current_state, next_state] = 1.0 else: next_state = nbS - 1 tm[current_state, next_state] = 1.0 tm[nbS - 1, nbS - 1] = 1.0 # sink state w_index += 1 current_state += 1 return DFA.DFA(nbS, len(sigma), 0, initial, transition, final)
def determine(self): """ 将NFA确定化为DFA Returns: DFA """ D = DFA() C = list() T0 = self.get_closure(self.K0) C.append(T0) D.K.add(0) D.K0.add(0) for i in self.Sigma: if i != 'e0': D.Sigma.add(i) D.f[i] = set() l = 0 r = 1 while l < r: T = C[l] for i in self.Sigma: if i != 'e0': newT = self.get_closure(self.move(T, i)) if newT not in C: # 加入DFA的总状态集 D.K.add(r) # 如果DFA的状态中包含NFA的终态,则此状态为DFA的终态 if self.Kt.issubset(newT): D.Kt.add(r) C.append(newT) # 添加DFA的f D.f[i].add((l, r)) r = r + 1 else: pos = 0 for t in C: if t == newT: break pos = pos + 1 D.f[i].add((l, pos)) l = l + 1 return D
def dpfa2dfa(self): new_transitions = {} for alphabet, transition in self.transitions.items(): new_transitions[alphabet] = np.ceil(transition).astype(int) print(new_transitions) states = [i for i in range(self.nbS)] initial_state = np.where(self.initial == 1.0) dfa = DFA.DFA(nbL=self.nbL, nbS=self.nbS, initial_state=initial_state, states=states, transitions=new_transitions) return dfa
def test_dfa(): δ = DFA.δ() A = DFA(Set(1, 2, 3, 4, 5, 6, 7), Set("a", "b"), δ, 1, Set(3, 5, 6)) δ[1, "a"] = 2 δ[1, "b"] = "-" δ[2, "a"] = 3 δ[2, "b"] = 4 δ[3, "a"] = 6 δ[3, "b"] = 5 δ[4, "a"] = 3 δ[4, "b"] = 2 δ[5, "a"] = 6 δ[5, "b"] = 3 δ[6, "a"] = 2 δ[6, "b"] = "-" δ[7, "a"] = 6 δ[7, "b"] = 1 # A.table() B = A.minimize() B.diagram()
def accept(string): dfa = DFA_min(DFA_rename(NFA_2_DFA())) import DFA DFA.states = tuple(dfa.keys()) ls = list(symbols) ls.remove('-1') DFA.symbols = tuple(ls) DFA.startstate = 0 DFA.trans = dfa ls = [] for k, v in dfa.items(): if v['final']: ls.append(k) DFA.acceptstates = tuple(ls) return DFA.accept(string)
def _canonize(self): import DFA Q = Set(chr(ord('A') + i) for i in range(len(self.Q))) letterMapping = dict(zip(self.δ.reachables(self.q0), Q)) δ = DFA.δ() for (qi, a), target in self.δ.items(): δ[letterMapping[qi], a] = letterMapping[target] q0 = letterMapping[self.q0] F = Set(letterMapping[qf] for qf in self.F) return DFA(Q, self.Σ, δ, q0, F)
def accept(string): dfa = DFA_min(DFA_rename(NFA_2_DFA())) import DFA DFA.states = tuple(dfa.keys()) ls = list(symbols) ls.remove('-1') DFA.symbols = tuple(ls) DFA.startstate = 0 DFA.trans = dfa ls = [] for k, v in dfa.items(): if v['final']:ls.append(k) DFA.acceptstates = tuple(ls) return DFA.accept(string)
def nfa_to_dfa(): ''' NFA 转 DFA的函数实现 ''' # 子集族 C = [] # 尚未标记的子集 q = queue.Queue() # 获取T0 T0 = sorted(ε_closure(NFA['s'])) # 初始化DFA DFA = dfa.init_dfa(NFA,T0) C.append(T0) q.put(T0) # 记录当前元素 i = 0 while not q.empty(): T = q.get() DFA['f'][str(i)] = {} for e in NFA['e']: nextT = sorted(ε_closure(move(T,e))) if nextT not in C: j = str(len(C)) C.append(nextT) q.put(nextT) DFA["k"].append(j) else: j = str(C.index(nextT)) DFA["f"][str(i)][e] = j # 判断是否为终态 dfa.has_intersection(DFA,NFA,nextT,'z',j) i = i + 1 return DFA
def __init__(self, specifications, debug=None, debug_flags=7, timings=None): if type(specifications) <> types.ListType: raise Errors.InvalidScanner("Scanner definition is not a list") if timings: from Timing import time total_time = 0.0 time1 = time() nfa = Machines.Machine() default_initial_state = nfa.new_initial_state('') token_number = 1 for spec in specifications: if isinstance(spec, State): user_initial_state = nfa.new_initial_state(spec.name) for token in spec.tokens: self.add_token_to_machine(nfa, user_initial_state, token, token_number) token_number = token_number + 1 elif type(spec) == types.TupleType: self.add_token_to_machine(nfa, default_initial_state, spec, token_number) token_number = token_number + 1 else: raise Errors.InvalidToken( token_number, "Expected a token definition (tuple) or State instance") if timings: time2 = time() total_time = total_time + (time2 - time1) time3 = time() if debug and (debug_flags & 1): debug.write("\n============= NFA ===========\n") nfa.dump(debug) dfa = DFA.nfa_to_dfa(nfa, debug=(debug_flags & 3) == 3 and debug) if timings: time4 = time() total_time = total_time + (time4 - time3) if debug and (debug_flags & 2): debug.write("\n============= DFA ===========\n") dfa.dump(debug) if timings: timings.write("Constructing NFA : %5.2f\n" % (time2 - time1)) timings.write("Converting to DFA: %5.2f\n" % (time4 - time3)) timings.write("TOTAL : %5.2f\n" % total_time) self.machine = dfa
def __init__(self, specifications, debug=None, debug_flags=7, timings=False): if not isinstance(specifications, list): raise Errors.InvalidScanner("Scanner definition is not a list") if timings: from Timing import time total_time = 0.0 time1 = time() nfa = Machines.Machine() default_initial_state = nfa.new_initial_state('') token_number = 1 for spec in specifications: if isinstance(spec, State): user_initial_state = nfa.new_initial_state(spec.name) for token in spec.tokens: self.add_token_to_machine( nfa, user_initial_state, token, token_number) token_number = token_number + 1 elif isinstance(spec, tuple): self.add_token_to_machine( nfa, default_initial_state, spec, token_number) token_number = token_number + 1 else: raise Errors.InvalidToken( token_number, "Expected a token definition (tuple) or State instance") if timings: time2 = time() total_time = total_time + (time2 - time1) time3 = time() if debug and (debug_flags & 1): debug.write("\n============= NFA ===========\n") nfa.dump(debug) dfa = DFA.nfa_to_dfa(nfa, debug = (debug_flags & 3) == 3 and debug) if timings: time4 = time() total_time = total_time + (time4 - time3) if debug and (debug_flags & 2): debug.write("\n============= DFA ===========\n") dfa.dump(debug) if timings: timings.write("Constructing NFA : %5.2f\n" % (time2 - time1)) timings.write("Converting to DFA: %5.2f\n" % (time4 - time3)) timings.write("TOTAL : %5.2f\n" % total_time) self.machine = dfa
def dfa_min(): t_start = "q1" t_final = ["q1", "q3"] t_states = ["q1", "q2", "q3", "q4", "q5", "q6", "q7"] t_symbols = ['a', 'b'] t_trans = { "q1": { "a": "q2", "b": "q4" }, "q2": { "a": "q5", "b": "q3" }, "q3": { "a": "q2", "b": "q6" }, "q4": { "a": "q1", "b": "q5" }, "q5": { "a": "q5", "b": "q5" }, "q6": { "a": "q3", "b": "q5" }, "q7": { "a": "q3", "b": "q6" } } t_dfa = DFA.DFA(t_states, t_symbols, t_trans, t_start, t_final) min_dfa = t_dfa.minimize() print(min_dfa.start_state) print(min_dfa.final_states) print(min_dfa.states) print(min_dfa.trans)
def product(dfa1, dfa2): """ Returns a new automaton which is the product of the two specified DFAs. @param dfa1 the first operand of the product. @param dfa2 the second operand of the product. @return the product of the two DFAs.""" alphabet = set.union(set(list(dfa1.alphabet)), set(list(dfa2.alphabet))) ret = DFA.DFA(alphabet) to_visit = [] """ Returns the superstate corresponding to the specified states and add it to the product DFA if it doesn't exist. """ def get_superstate(state1, state2): sstate = "{" + state1 + "," + state2 + "}" if sstate not in ret.states: is_final = state1 in dfa1.finals and state2 in dfa2.finals ret.add_state(sstate, is_final) to_visit.append((sstate, state1, state2)) return sstate ret.init = get_superstate(dfa1.init, dfa2.init) # Add init state. while len(to_visit) > 0: (sstate, state1, state2) = to_visit.pop() # Add transitions. for symbol in ret.alphabet: dst_state1 = dfa1.dst_state(state1, symbol) dst_state2 = dfa2.dst_state(state2, symbol) if dst_state1 is None or dst_state2 is None: continue dst_sstate = get_superstate(dst_state1, dst_state2) ret.add_transition(sstate, symbol, dst_sstate) return ret
def create_dfa_input_str(): t_start = "q0" t_final = ['q2'] t_states = ["q0", "q1", "q2"] t_symbols = ['a', 'b'] t_trans = { 'q0': { 'a': 'q0', 'b': 'q1' }, 'q1': { 'a': 'q0', 'b': 'q2' }, 'q2': { 'a': 'q2', 'b': 'q2' }, } t_dfa = DFA.DFA(t_states, t_symbols, t_trans, t_start, t_final) input_s = "aba" t_dfa.read_input(input_s)
def DFA_to_RL(): t_start = "q1" t_final = ["q3"] t_states = ["q1", "q2", "q3"] t_symbols = ['a', 'b'] t_trans = { "q1": { "a": "q1", "b": "q3" }, "q2": { "a": "q2", "b": "q1" }, "q3": { "a": "q3", "b": "q2" }, } t_dfa = DFA.DFA(t_states, t_symbols, t_trans, t_start, t_final) t_rl = t_dfa.trans_to_RL() print(t_rl)
def __init__(self, LTLFormula): state0 = Node.NodeState(q=0) state1 = Node.NodeState(q=1) state2 = Node.NodeState(q=2) node0 = Node.Node(state=state0, index=0, isAccepting=False) node1 = Node.Node(state=state1, index=1, isAccepting=False) node2 = Node.Node(state=state2, index=2, isAccepting=True) accepts = [2] startNode = node0 Nodes = [] Nodes.append(node0) Nodes.append(node1) Nodes.append(node2) def transFcn(q, obs): if q == 0: if obs.atGoal and (not obs.crashed) and (not obs.speeding): return 2 elif obs.crashed or obs.speeding: return 1 else: return 0 elif q == 1: return 1 elif q == 2: if obs.crashed or obs.speeding: return 1 else: return 2 self.DFA = DFA.DFA(nodes=Nodes, startNode=startNode, transFcn=transFcn, accepts=accepts)
def intersept(self, other): """ create a new DFA which has: Q3 = Q1 × Q2 F3 = F1 × F2 q3 = (q1, q2) δ3((p, q), a) = (δ1(p, a), δ2(q, a)) """ Q3 = self.Q.cross(other.Q) F3 = self.F.cross(other.F) q3 = (self.q0, other.q0) δ3 = δ() for (p, q) in Q3: for a in self.Σ: if self.δ[p, a] != "-" and other.δ[q, a] != "-": δ3[f"{(p, q)}", a] = f"{(self.δ[p, a], other.δ[q, a])}" M3 = DFA(Q3, self.Σ, δ3, q3, F3) return M3
def convertToDFA(self) -> DFA: allStates = self.__partitions() dictOfPartitions = self.__makeDictOfPartitions(allStates) dfaDict = self.__makeDFAdict(dictOfPartitions) mergedTransitionsInDfaDict = self.__mergeTransitions(dfaDict) mergedTransitionsInDfaDict = self.__simplify(mergedTransitionsInDfaDict) tempResult = self.__transitionsToTuples(mergedTransitionsInDfaDict) converted = self.__makeStates(tempResult, dictOfPartitions) help = sorted(self.allStatesUsingOnlyEpsilonEdges(self.__stateNumber(list(self.dictOfStates.keys())[0]))) help.append(-2) startingNFAState = tuple(help) startingNFAState = dictOfPartitions[startingNFAState] startingNFAState = converted[startingNFAState] unnecessaryState = self.__unnecessaryState(converted, startingNFAState) while(unnecessaryState != -3): converted.pop(unnecessaryState) unnecessaryState = self.__unnecessaryState(converted, startingNFAState) finalDFA = DFA(converted, startingNFAState, self.alphabet) return finalDFA
def minimizeModel(self): dfa = DFA.prismaModel2DFA(self.mc) # get the states, which we should collapse collapse = dfa.minimize() return DFA.DFA2prismaModel(dfa)
#!/usr/bin/env python import DFA import sys DFA_A = DFA.DFA(sys.argv[1]) DFA_B = DFA.DFA(sys.argv[2]) print("[!] Determining eqivalence of {} and {}\n".format( sys.argv[1], sys.argv[2])) if (DFA.isEquivalent(DFA_A, DFA_B) == True): print("Equivalent") else: print("Not equivalent")
def test_accept(self): ls=['ababa','baab','abba','ababaa','bababa','abcdf'] for i in ls: print i,DFA.accept(i)
print 'd.input_sequence("1110101011101") #7517' d.input_sequence("1110101011101") #7517 print "Current state:", d.current_state print "Accepting:", d.status() #raw_input() print "Resetting..." d.reset() print d.current_state d.input_sequence("10011011101") #1245 print d.current_state print d.status() #Various minimizations a = ['1', '11', '111', '1111', '11110', '11111', '111111', '111110'] b = ['0', '1'] e = DFA.from_word_list(a,b) print "a = ['1', '11', '111', '1111', '11110', '11111', '111111', '111110']" print "b = ['0', '1']" print "e = DFA.from_word_list(a,b)" print "..." #raw_input() print "===The starting DFA===" e.pretty_print() #raw_input() print "==Minimized===" e.minimize() e.pretty_print() #raw_input() print "==...then DFCA-Minimized===" e.DFCA_minimize() e.pretty_print()