Esempio n. 1
0
def sync_trans(aut1, aut2, syc_events):

    sync_events = helper.extract_elems_from_trans(aut1.trans, 'event').union(
        helper.extract_elems_from_trans(aut2.trans, 'event'))
    sync_trans = set()
    for event in sync_events:
        if event not in aut1.events:
            for x in aut1.states:
                aut1.trans = aut1.trans | {auto.Transition(x, event, x)}
        if event not in aut2.events:
            for x in aut2.states:
                aut2.trans = aut2.trans | {auto.Transition(x, event, x)}
        for transition1 in auto.filter_trans_by_events(aut1.trans, {event}):
            for transition2 in auto.filter_trans_by_events(
                    aut2.trans, {event}):
                source = merge_label(
                    helper.extract_elems_from_trans({transition1},
                                                    'source').pop(),
                    helper.extract_elems_from_trans({tr2}, 'source').pop())
                target = merge_label(
                    helper.extract_elems_from_trans({transition1},
                                                    'target').pop(),
                    helper.extract_elems_from_trans({tr2}, 'target').pop())
                sync_trans.add(auto.Transition(source, event, target))

    return sync_trans
Esempio n. 2
0
def SEARCH_AUTOMATON(sample,alphabet,text):
	for i in range(len(text)):
		print "text",i
		for s in sample[i]:
			auto = Automaton(s,alphabet[i])

			start = time.clock()
			
			auto.match(text[i])

			end = time.clock()
			print end - start
Esempio n. 3
0
 def remove_epsilons(self):
     # Corresponds to definition (7) in handout
     new_deltas = [(q1, x, q3) for q1 in self.all_states()
                   for x in self.all_labels()
                   for q2 in self.epsilon_closure(q1)
                   for q3 in self.targets(q2, x) if x is not EPSILON]
     new_ends = [
         q for q in self.all_states() for q1 in self.epsilon_closure(q)
         if q1 in self.ends
     ]
     return Automaton(self.start, remove_duplicates(new_ends), new_deltas)
def supervisor(P, Sp, sigma_u):

    S0 = a1.synch(P, Sp)
    S0_states = S0.states.copy()
    S0_events = S0.events.copy()
    S0_trans = S0.trans.copy()
    S0_mark = S0.marked.copy()
    S0_forb = S0.forbidden.copy()

    prev_unsafe = S0_forb
    unsafe = set()
    flag = True

    while flag:
        prev_unsafe = unsafe
        Q_prim = a1.coreach(S0_events, S0_trans, S0_mark, prev_unsafe)
        Q_bis = a1.coreach(sigma_u, S0_trans, (S0_states - Q_prim), set())
        unsafe = prev_unsafe | Q_bis  # Union

        if unsafe == prev_unsafe:
            flag = False

    S_states = S0_states - unsafe

    if S_states == set(
    ):  # There exist no supervisor that can fulfill the specification
        raise ValueError

    S_state = S_states.copy()
    for k in S_states:
        if help.is_defined_for_p(P.trans, k, sigma_u) or help.is_defined_for_q(
                Sp.trans, k, sigma_u):
            S_state.discard(k)

    S_trans = help.filter_trans_by_target(S0_trans, S_state)
    S_trans2 = help.filter_trans_by_source(S_trans, S_state)

    S = auto.Automaton(S_state, S0.init, S0_events, S_trans2)

    return S

    S0 = a1.synch(P, Sp)
    S0_states = S0.states.copy()
    S0_events = S0.events.copy()
    S0_trans = S0.trans.copy()
    S0_mark = S0.marked.copy()
    S0_forb = S0.forbidden.copy()
Esempio n. 5
0
def flip_trans(trans):
    """ Flips the direction of the transitions in the set"""
    return {auto.Transition(t.target, t.event, t.source) for t in trans}
Esempio n. 6
0
def match(text,pattern):
	alp = get_alphabet(text+pattern)
	auto = Automaton(pattern,alp)
	return auto.match(text)
Esempio n. 7
0
#TFT
start = 0
states = {
    0: {
        'action': 'C',
        'C': 0,
        'D': 1
    },
    1: {
        'action': 'D',
        'C': 0,
        'D': 1
    }
}
A1 = Automaton.Automaton(start, states, actions)

#Alternator
start = 0
states = {
    0: {
        'action': 'C',
        'C': 1,
        'D': 1
    },
    1: {
        'action': 'D',
        'C': 0,
        'D': 0
    }
}
def synch(aut1, aut2):
    """
    Returns the synchronous composition of two automata.
    
    :param aut1: Automaton
    :param aut2: Automaton
    """
    import helper as help
    import automaton as auto

    sync_events = help.extract_elems_from_trans(aut1.trans, 'event').union(
        help.extract_elems_from_trans(aut2.trans, 'event'))
    sync_trans = set()
    for event in sync_events:
        if event not in aut1.events:
            for y in aut1.states:
                aut1.trans = aut1.trans.union({auto.Transition(y, event, y)
                                               })  #for y in aut1.states

        if event not in aut2.events:
            for y in aut2.states:
                aut2.trans = aut2.trans.union({auto.Transition(y, event, y)
                                               })  #for y in aut1.states

    for event in sync_events:
        for transition1 in help.filter_trans_by_events(aut1.trans, {event}):
            for transition2 in help.filter_trans_by_events(
                    aut2.trans, {event}):
                source = help.merge_label(
                    help.extract_elems_from_trans({transition1},
                                                  'source').pop(),
                    help.extract_elems_from_trans({transition2},
                                                  'source').pop())
                target = help.merge_label(
                    help.extract_elems_from_trans({transition1},
                                                  'target').pop(),
                    help.extract_elems_from_trans({transition2},
                                                  'target').pop())
                sync_trans.add(auto.Transition(source, event, target))

    # initial states, as a "label" not set
    sync_init = help.merge_label(aut1.init, aut2.init)
    # states to be synchronized
    #sync_states=helper.cross_product(aut1.states,aut2.states)
    sync_states = help.cross_product(aut1.states, aut2.states)
    #sync_states=help.extract_elems_from_trans(sync_trans,'source').union(help.extract_elems_from_trans(sync_trans,'target'),{sync_init})
    # marked states, if no marked states in set --> all states are marked
    if len(aut1.marked) == 0:
        aut1.marked = aut1.states.copy()
    if len(aut2.marked) == 0:
        aut2.marked = aut2.states.copy()
    sync_marked = help.cross_product(aut1.marked, aut2.marked)
    sync_marked = sync_marked.intersection(sync_states)

    # forbidden states, forbidden states according to lecture notes
    sync_forbidden = help.cross_product(aut1.forbidden, aut2.states).union(
        help.cross_product(aut1.states, aut2.forbidden)) & sync_states

    reach_sync_states = reach(sync_events, sync_trans, {sync_init},
                              sync_forbidden)
    reach_sync_marked = sync_marked.intersection(reach_sync_states)
    reach_sync_states.update({sync_init})

    reach_trans = set()
    for element in sync_trans:
        if element.source.issubset(
                reach_sync_states) and element.target.issubset(
                    reach_sync_states):
            reach_trans.update({element})

    return auto.Automaton(states=reach_sync_states,
                          init=sync_init,
                          events=sync_events,
                          trans=reach_trans,
                          forbidden=sync_forbidden,
                          marked=reach_sync_marked)
    """
Esempio n. 9
0
        return output


if __name__ == '__main__':
    """
	This block here is for demo purposes. It prompts the user to enter a string, which it will then encrypt and subsequently 
	decrypt, displaying the string after both stages. This is not intended to be a full and complete end-user program; it 
	only serves to demonstrate the capabilities of the actual class, which is to be incorporated in other programs and scripts 
	as need be.
	"""
    crypto = VernamAutomaton()
    text = input("Please enter a string to be encrypted: ")
    test = ''
    # The following block attempts to convert the provided string into bits and then calculate the length of said bit string.
    for i in text:
        temp = bin(ord(i))
        if len(temp) < 10:
            temp = ('0' * (10 - len(temp))) + temp[2:]
        else:
            temp = temp[2:]
        test += temp
    test = '0b' + test
    robot = Automaton.Automaton('x', 30, len(test) - 2)
    for i in range(10):
        robot.evolve()
    output = crypto.crypt(text, robot.extractRowBits(9))
    print("Encrypted:")
    print(output)
    print("Decrypted:")
    output = crypto.crypt(output, robot.extractRowBits(9))
    print(output)
Esempio n. 10
0
    def __init__(self, regex_tree):
        self._nfa = self._automaton_from_regex(regex_tree)

        self._dfa = Automaton()
        self._dfa.states.append(State({-1}))
        self._dfa.set_start_state({-1})
Esempio n. 11
0
class RegexEvaluator:
    def __init__(self, regex_tree):
        self._nfa = self._automaton_from_regex(regex_tree)

        self._dfa = Automaton()
        self._dfa.states.append(State({-1}))
        self._dfa.set_start_state({-1})

    def _automaton_from_regex(self, root):
        leafs = root.leaf_nodes()

        graph = Automaton()
        graph.states.append(State(-1))
        for leaf in leafs:
            graph.states.append(State(leaf.id))

        graph.set_start_state(-1)

        for node in root.last():
            graph.set_end_state(node.id)

        if root.empty():
            graph.set_end_state(-1)

        for node in root.first():
            graph.add_transition(-1, node.character, node.id)

        for leaf in leafs:
            for node in leaf.next():
                graph.add_transition(leaf.id, node.character, node.id)

        return graph

    def evaluate(self, word):
        current_state = self._dfa.state_by_id({-1})
        for char in word:
            if self._dfa.follow_once(current_state, char) is None:
                following = set()
                for nfa_id in current_state.id:
                    following |= self._nfa.follow_all(
                        self._nfa.state_by_id(nfa_id), char)
                following = self._nfa.ids_from_states(following)

                if self._dfa.state_by_id(following, True) is None:
                    self._dfa.states.append(State(following))
                    for id in following:
                        if self._nfa.is_end_state(id):
                            self._dfa.set_end_state(following)
                            break
                self._dfa.add_transition(current_state.id, char, following)

            current_state = self._dfa.follow_once(current_state, char)

        return current_state in self._dfa.end_states

    def draw_nfa(self, suffix=""):
        self._nfa.generate_dot('graph_nfa' + suffix + '.png')

    def draw_dfa(self, suffix=""):
        self._dfa.generate_dot('graph_dfa' + suffix + '.png')
Esempio n. 12
0
    def _automaton_from_regex(self, root):
        leafs = root.leaf_nodes()

        graph = Automaton()
        graph.states.append(State(-1))
        for leaf in leafs:
            graph.states.append(State(leaf.id))

        graph.set_start_state(-1)

        for node in root.last():
            graph.set_end_state(node.id)

        if root.empty():
            graph.set_end_state(-1)

        for node in root.first():
            graph.add_transition(-1, node.character, node.id)

        for leaf in leafs:
            for node in leaf.next():
                graph.add_transition(leaf.id, node.character, node.id)

        return graph
Esempio n. 13
0
from Automaton import *

if __name__ == '__main__':
    with open('sample_input.txt') as f:
        input_data = f.read().strip().split('\n')
        X = [x for x in input_data[0].split()[1:]]
        S = int(input_data[1].split()[-1])
        S0 = int(input_data[2].split()[-1])
        F = [int(f) for f in input_data[3].split()[1:]]

        I = [i.split(',') for i in input_data[4].split()[1:]]
        I = [(int(i[0]), i[1], int(i[2])) for i in I]

        automaton = Automaton(X, S, S0, F, I)
        automaton.print_parameters()
        print(40 * '-')
        equivalent_automaton = automaton.reduce()
        equivalent_automaton.print_parameters()
Esempio n. 14
0
                ((index % Constants.GRID_SIZE) * Constants.ROOT_SIZE,
                 (index / Constants.GRID_SIZE) * Constants.ROOT_SIZE))

pygame.draw.rect(window, Constants.GREY, Constants.BUTTON_BOX_LOCATION)

window.blit(button, Constants.START_BUTTON_LOCATION)
window.blit(button, Constants.STOP_BUTTON_LOCATION)
window.blit(button, Constants.FASTER_BUTTON_LOCATION)
window.blit(button, Constants.SLOWER_BUTTON_LOCATION)

drawText(Constants.START_LABEL, 45, 535)
drawText(Constants.STOP_LABEL, 175, 535)
drawText(Constants.FASTER_LABEL, 297, 535)
drawText(Constants.SLOWER_LABEL, 422, 535)

automaton = Automaton.Automaton(window, Constants.TOTAL_INDICES)
automaton.setImages([liveCell, deadCell])

run = False

# Main loop

while True:

    automaton.drawGrid()
    pygame.display.flip()
    xPosition, yPosition = pygame.mouse.get_pos()

    overButton = checkButtons((xPosition, yPosition), buttonPositions,
                              buttonDimensions)
Esempio n. 15
0
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 15:10:37 2018

@author: Fredrik Möller
"""

import synch1_1 as synch
import Automaton as auto

p1 = auto.Automaton(states={'p11', 'p12'},
                    init='p11',
                    events={'a', 'b'},
                    trans={
                        auto.Transition('p11', 'a', 'p12'),
                        auto.Transition('p12', 'b', 'p11')
                    },
                    marked={})

p2 = auto.Automaton(states={'p21', 'p22'},
                    init='p21',
                    events={'e', 'd', 'c'},
                    trans={
                        auto.Transition('p22', 'd', 'p21'),
                        auto.Transition('p22', 'e', 'p21'),
                        auto.Transition('p21', 'c', 'p22')
                    },
                    marked={})

sp1 = auto.Automaton(states={'sp11', 'sp12'},
                     init='sp11',
Esempio n. 16
0
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 11:05:39 2018

@author: Fredrik Möller
"""
import Automaton as auto

b1 = auto.Automaton(states={'a', 'b'},
                    init='a',
                    events={1},
                    trans={auto.Transition('a', 1, 'b')},
                    marked={'b'})
b2 = auto.Automaton(states={'c', 'd', 'e'},
                    init='c',
                    events={1, 2},
                    forbidden={},
                    trans={
                        auto.Transition('c', 1, 'd'),
                        auto.Transition('d', 2, 'e'),
                        auto.Transition('e', 1, 'c')
                    })

aut1 = b1
aut2 = b2
Esempio n. 17
0
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 13 15:20:37 2018

@author: Fredrik Möller
"""
#imports
import Automaton as auto

states = {'p11', 'p12'}
init = 'p11'
events = {'a', 'b'}
trans = {
    auto.Transition('p11', 'a', 'p12'),
    auto.Transition('p12', 'b', 'p11')
}
marked = {'p11', 'p12'}

start_states = states

p1 = auto.Automaton(states, init, events, trans, marked)

#coreachable_states = co_reach.coreach(events, trans,start_states, forbidden)
#print(coreachable_states)
Esempio n. 18
0
from Stateitem import *
from State import *
from Automaton import *
import time

current_state = State()
state_list = []
open_list = []
close_list = []
explored_list = []
automaton = Automaton()

if __name__ == '__main__':
    exit=0
    while(exit==0):
        automaton=Automaton()
        path=input("print the automaton path file:")
        time_file = open(path+"/time.txt", "w")
        transition_table=automaton.stateTransitionTable(path+"/transition.edgelist")
        property_table=automaton.statePropertyTable(path+"/state.nodelist")
        state_list=automaton.loadNodefromTransitionTable(property_table, transition_table)

        init_state=automaton.getInitState(state_list)
        end_state_list=automaton.getEndState(state_list)

        start_time=time.time()
        selected_item = Stateitem()
        current_state = init_state

        for goal_state in end_state_list:
            while current_state.get_targetID()!=goal_state.get_targetID():
Esempio n. 19
0
                new_start = num
                break

        new_transitions = []
        for end_state in self.ends:
            new_transitions.append((end_state, EPSILON, self.start))

        return EpsAutomaton(start=new_start,
                            ends=[new_start] + self.ends,
                            deltas=[(new_start, EPSILON, self.start)] +
                            self.deltas + new_transitions)


# Test FSAs
odd_Cs = Automaton(start=False,
                   ends=[True],
                   deltas=[(False, 'C', True), (False, 'V', False),
                           (True, 'C', False), (True, 'V', True)])
even_Vs = Automaton(start=False,
                    ends=[False],
                    deltas=[(False, 'C', False), (False, 'V', True),
                            (True, 'C', True), (True, 'V', False)])

efsa_handout4 = EpsAutomaton(start=10,
                             ends=[20, 30],
                             deltas=[(10, 'a', 10), (10, EPSILON, 20),
                                     (10, EPSILON, 30), (20, 'b', 21),
                                     (21, 'b', 20), (30, 'b', 31),
                                     (31, 'b', 32), (32, 'b', 30)])

efsa_handout5 = EpsAutomaton(start=0,
                             ends=[2],