Exemplo n.º 1
0
 def union(self, AFN2):
     if isinstance(AFN2, AFN):
         #Borramos el estado de aceptacion de los AFN
         self.deleteAcceptState()   
         AFN2.deleteAcceptState()   
         #Creamos nuevos Estados
         newIniSt = State()
         newEndSt = State(True)
         #Creamos las nuevas Trancisiones Iniciales
         t1_i = Transition(newIniSt, self.ini_state, Epsilon.symbol)
         t2_i = Transition(newIniSt, AFN2.ini_state, Epsilon.symbol)
         allTrans = [t1_i, t2_i]
         #Creamos Transiciones de estados finales
         t1_e = Transition(self.end_state, newEndSt, Epsilon.symbol)
         t2_e = Transition(AFN2.end_state, newEndSt, Epsilon.symbol)
         allTrans = allTrans + [t1_e, t2_e]   
         #Insertamos las transiciones ya exisitentes de cada uno de los Automatas
         allTrans.extend(self.transitions)
         allTrans.extend(AFN2.transitions)
         #Agregamos los nuevos estados
         newStates = [newIniSt, newEndSt]  
         #Estados ya exisitentes
         newStates.extend(self.states)
         newStates.extend(AFN2.states)
         #Creacion del nuevo Objeto
         newAFN = AFN(newIniSt, newEndSt, allTrans, newStates)
         return newAFN
     else:
         print("Se espera un Objeto Clase AFN como argumento")
         sys.exit()
Exemplo n.º 2
0
def generate(a, c, m):
    def var(i):
        return "x{}".format(i)

    numeric = range(m)
    boolean = ["t", "f"]

    Q = set(numeric) | set(boolean)
    S = {var(i) for i in range(len(a))}
    I = {var(i): a[i] % m for i in range(len(a))}
    O = {q: 1 if (q == c or q == "t") else 0 for q in Q}
    T = set()

    for n in numeric:
        for n_ in numeric:
            pre = (n, n_)
            post = ((n + n_) % m, "t" if ((n + n_) % m) == c else "f")

            T.add(Transition(pre, post))

        for b in boolean:
            pre = (n, b)
            post = (n, "t" if n == c else "f")

            T.add(Transition(pre, post))

    return Protocol(Q, T, S, I, O)
Exemplo n.º 3
0
    def union_nAFN(arrayAFNS, arrayTokens):
        #Revisamos que ambos argumetnos sean de tipo lista
        if isinstance(arrayAFNS, list) and isinstance(arrayTokens,list):
            #Revisar que la longitud sea la misma
            if len(arrayAFNS) == len(arrayTokens):
                #Asignamos los tokenes dados a cada automata en su estado de aceptacion
                for i in range(0, len(arrayAFNS)):
                    arrayAFNS[i].end_state.token = arrayTokens[i]
                #Unimos todos los AFN
                automata_union = arrayAFNS[0]
                iniState = State()
                endState = State(True)
                newTransitions = []
                newStates = []
                for AFNElem in arrayAFNS:
                    tIniAux = Transition(iniState, AFNElem.ini_state, Epsilon.symbol)
                    tEndAux = Transition(AFNElem.end_state, endState, Epsilon.symbol)
                    newTransitions.append(tIniAux)
                    newTransitions.append(tEndAux)
                    newTransitions.extend(AFNElem.transitions)
                    #States
                    newStates.extend(AFNElem.states)
                #Insertar Nuevo Estado Inicial y Final
                newStates.append(iniState)
                newStates.append(endState)

            return AFN(iniState, endState, newTransitions, newStates)
Exemplo n.º 4
0
 def kleene_star(self):
     #Eliminar estado de aceptacion
     self.deleteAcceptState()
     #Traemos las Transiciones ya existentes
     newTransitions = self.transitions
     #Transicion del final acutal, al inicial actual
     t_return = Transition(self.end_state, self.ini_state, Epsilon.symbol)
     newTransitions.append(t_return)
     #Traer Estados acutales
     newStates = self.states
     #Nuevos estados
     ini_State = State()
     newStates.append(ini_State)
     end_State = State(True)
     newStates.append(end_State)
     #Nuevas transiciones
     t_ini = Transition(ini_State, self.ini_state, Epsilon.symbol)
     newTransitions.append(t_ini)
     t_end = Transition(self.end_state, end_State, Epsilon.symbol)
     newTransitions.append(t_end)
     t_optional = Transition(ini_State, end_State, Epsilon.symbol)
     newTransitions.append(t_optional)
     #Creacion del nuevo Objeto
     newAFN = AFN(ini_State, end_State, newTransitions, newStates)
     return newAFN
Exemplo n.º 5
0
 def add_arc(self, arc, value):
     up = True
     if arc.contains_arc(self):
         up = False
     if arc == self:
         new_trans = Transition(self.position, self.position, value, True, up)
     else:
         new_trans = Transition(self.position, arc.position, value, False, up)
     self.arcs[arc] = new_trans
Exemplo n.º 6
0
def buildStateChildren(currentState: State):
    transitions = [
        Transition(i + 1) for i in range(0, numberOfHoles)
        if isTransitionValid(currentState, Transition(i + 1))
    ]
    possibleStates = [
        makeTransition(currentState, transition) for transition in transitions
    ]
    return possibleStates, transitions
Exemplo n.º 7
0
def generate():
    Q = {"A", "B", "a", "b"}
    T = {Transition(("A", "B"), ("a", "b")),
         Transition(("A", "b"), ("A", "a")),
         Transition(("B", "a"), ("B", "b")),
         Transition(("a", "b"), ("b", "b"))}
    S = {"A", "B"}
    I = {"A": "A", "B": "B"}
    O = {"A": 0, "B": 1, "a": 0, "b": 1}

    return Protocol(Q, T, S, I, O)
Exemplo n.º 8
0
def generate():
    Q = {"Y", "N", "b"}
    T = {Transition(("Y", "b"), ("Y", "Y")),
         Transition(("Y", "N"), ("Y", "b")),
         Transition(("N", "Y"), ("N", "b")),
         Transition(("N", "b"), ("N", "N"))}
    S = {"Y", "N"}
    I = {"Y": "Y", "N": "N"}
    O = {"Y": 1, "N": 0, "b": 1}

    return Protocol(Q, T, S, I, O)
Exemplo n.º 9
0
    def test_transition_init(self, s1, s2, inp, out, cnt, cnt_present):
        if not cnt_present:
            t = Transition(s1, s2, inp, out)
        else:
            t = Transition(s1, s2, inp, out, counter=cnt)

        assert t.init_state == s1
        assert t.output_state == s2
        assert t.input == inp
        assert t.output == out
        assert t.counter == cnt
Exemplo n.º 10
0
 def add_transition(self, from_state: int, to_state: int,
                    actions: List[str]):
     self.enlarge_transitions(max(to_state, from_state) +
                              1)  # TODO This is slow. Better idea?
     self.number_of_states = NumberTools.max(self.number_of_states,
                                             to_state + 1)
     self.transitions[from_state].append(
         Transition(next_state=to_state, actions=actions))
     self.reverse_transitions[to_state].append(
         Transition(next_state=from_state, actions=actions))
     self.pre_states[to_state].add(from_state)
Exemplo n.º 11
0
    def determinisation(auto):
        """ Automate  -> Automate
                rend l'automate déterminisé d'auto
                """
        alphabet = auto.getAlphabetFromTransitions(
        )  #alphabet = la liste de mots
        finalstate = auto.getListFinalStates()
        transitions = []  #liste des transitions a remplir
        Q = []  #Liste des etats
        E = [[auto.getListInitialStates()]]  #list des etats initiaux
        while len(E) > 0:  #tant qu'on a des etats initaux
            S = E[0]  #on prend le premier
            E.remove(S)
            Q.append(S)
            for l in alphabet:
                temp = []
                for k in S:  #pour chaque etat on parcour les transitions pour voir la lettre qui manque
                    for t in auto.getListTransitionsFrom(k):
                        if t.etiquette == l and not (t.stateDest in temp):
                            temp.append(t.stateDest)

                if not (temp in Q) and not (
                        temp in E
                ):  #on voit si on est entrer dans le if, du coup on l'joute a E
                    E.append(temp)

                transitions.append(Transition(
                    S, l,
                    temp))  #on crée une nouvelle transition et on la liste

        states = []  #liste d'etat
        cpt = 0  #compteur pour le nb d'etat

        for o in Q:  #au final Q c'est tout l'automate
            flag = False
            for p in o:
                if p:
                    flag = True
            s = State(cpt, cpt == 0, flag)
            cpt += 1
            states.append(s)
        transitionsFinales = []
        for m in transitions:
            t = Transition(states[auto.indexOf(Q, m.stateSrc)], m.etiquette,
                           states[auto.indexOf(Q, m.stateDest)])
            transitionsFinales.append(t)

        for i in finalstate:
            auto.addState(i)

        auto = Automate(transitionsFinales)

        return auto
Exemplo n.º 12
0
 def petri(self, *elements):
     a = elements[0]
     firings = elements[1]
     ps = [Place(m) for m in a]
     ts = dict(
         t1=Transition([Out(ps[elements[2]])], [In(ps[elements[3]])]),
         t2=Transition([Out(ps[1])], [In(ps[2]), In(ps[0])]),
     )
     firing_sequence = [choice(list(ts.keys()))
                        for _ in range(firings)]  # stochastic execution
     print(firing_sequence)
     petri_net = PetriNet(ts)
     petri_net.run(firing_sequence, ps)
def generate(n):
    Q = set(range(n + 1))
    T = set()
    S = {"0", "1"}
    I = {"0": 0, "1": 1}
    O = {i: (0 if i < n else 1) for i in Q}

    for i in range(1, n):
        T.add(Transition((i, i), (i, i + 1)))

    for i in range(0, n):
        T.add(Transition((n, i), (n, n)))

    return Protocol(Q, T, S, I, O)
Exemplo n.º 14
0
def generate(n):
    Q = set(range(n + 1))
    T = set()
    S = {"0", "1"}
    I = {"0": 0, "1": 1}
    O = {i: (0 if i < n else 1) for i in Q}

    for i in range(n + 1):
        for j in range(n + 1):
            if i + j < n:
                T.add(Transition((i, j), (0, i + j)))
            else:
                T.add(Transition((i, j), (n, n)))

    return Protocol(Q, T, S, I, O)
Exemplo n.º 15
0
def increment(word, verbose=False):
    tape = Tape(word, '|')
    states = [
                State("s0", StateType.Start),
                State("s1", StateType.Empty),
                State("sf", StateType.Final)
             ]

    transitions = [
                     Transition("s0", "$", "s1", "$", Direction.Right),
                     Transition("s1", "|", "s1", "|", Direction.Right),
                     Transition("s1", "#", "sf", "|", Direction.Neutral)
                  ]

    return TuringMachine(states, transitions, tape, verbose)
Exemplo n.º 16
0
    def ajoutTransition(self, nbrEtatA, nbrEtatB, etq):
        self.transition = Transition(self.listEtat[nbrEtatA])
        self.transition.ajoutTransitionLettre(self.listEtat[nbrEtatB], etq)

        # on fait la liaison entre l'etat et la transition ( append )
        self.listEtat[nbrEtatA].listTransition.append(self.transition)
        return None
Exemplo n.º 17
0
    def test_lineartween_down(self):
        print("testing linear tween decreasing values")
        dur = Duration()
        dur.duration_in_seconds = .0001
        duration = int(dur.duration)
        target_angle = 0
        start_angle = 180
        current_angle = 90
        # duration = 10
        start_time = current_milli_time()
        # print("start time", start_time)
        change_in_value = target_angle - start_angle

        # loop
        current_time = current_milli_time()
        elapsed_time = current_time - start_time

        while int(elapsed_time) <= int(duration) or (cur_angle == target_angle-1):
            current_time = current_milli_time()
            elapsed_time = current_time - start_time 
            # angle = tick(start_time, start_angle, change_in_value, duration)
            cur_angle = Transition().linear_tween(current_time=elapsed_time,
                            start_value=start_angle,
                            change_in_value=change_in_value,
                            duration=duration, 
                            start_time=start_time, 
                            target_angle=target_angle)   
        self.assertEqual(cur_angle,target_angle)
Exemplo n.º 18
0
 def load(self, path):
     if len(path) > 0:
         self.clear()
         with open(path, 'r') as infile:
             data = json.load(infile)
         for state in data["states"]:
             new_state = State(position=state["position"],
                               state_name=state["state_name"],
                               radius=state["radius"],
                               selected=state["selected"],
                               state_type=int(state['type']))
             self.states[new_state] = state["key"]
         for arc in data['arcs']:
             start_state = self.get_state_by_name(self.states, arc['start'])
             end_state = self.get_state_by_name(self.states, arc['end'])
             start_state.add_transition(
                 end_state,
                 Transition(
                     start_position=start_state.position,
                     end_position=end_state.position,
                     value=arc['value'],
                     same_state=start_state.position == end_state.position,
                     is_up=arc['up'],
                     values_pos=arc['value_position']))
         self.redraw()
Exemplo n.º 19
0
        def completeAutomate(auto,alphabet) :
                """ Automate x str -> Automate
                rend l'automate complété d'auto, par rapport à alphabet
                """

                if Automate.estComplet(auto, alphabet) :
                        return auto

                newId = 0

                for s in auto.listStates :
                        newId += int(s.id)

                newState = State(newId, False, False, "Puit")
                auto.addState(newState)

                for s in auto.listStates :
                        etiquettes = []
                        for t in auto.transitions(s) :
                                if not(t.etiquette in etiquettes) :
                                        etiquettes.append(t.etiquette)
                        for c in alphabet :
                                if not(c in etiquettes) :
                                        auto.addTransition(Transition(s, c, newState))

                return auto
Exemplo n.º 20
0
    def test_ease_in_out_quad_down(self):
        print("testing ease in-out quad decreasing values")
        dur = Duration()
        dur.duration_in_seconds = .0001
        duration = int(dur.duration)
        target_angle = 0
        start_angle = 180
        current_angle = 90
        start_time = current_milli_time()
        change_in_value = target_angle - start_angle

        # loop
        current_time = current_milli_time()
        elapsed_time = current_time - start_time

        while int(elapsed_time) <= int(duration) or (cur_angle == target_angle-1):
            current_time = current_milli_time()
            elapsed_time = current_time - start_time 
            # angle = tick(start_time, start_angle, change_in_value, duration)
            cur_angle = Transition().ease_in_out_quad(current_time=elapsed_time,
                            start_value=start_angle,
                            change_in_value=change_in_value,
                            duration=duration, 
                            start_time=start_time, 
                            target_angle=target_angle)   
            # print("time:", current_time, "angle", cur_angle, "target_angle",target_angle, "elapsed time", elapsed_time, "duration", duration)
        self.assertEqual(cur_angle,target_angle)
Exemplo n.º 21
0
    def completeAutomate(auto, alphabet):
        """ Automate x str -> Automate
                rend l'automate complété d'auto, par rapport à alphabet
                """

        if auto.estComplet(
                auto, alphabet
        ) == True:  #Si l'automate est deja complet pas besoin de le completer :p
            return auto
        var1 = 0  #on cree la variable qui va rajouter un nouvelle etat, plutot le nouveau id
        for etat in auto.listStates:  #on l'incremente jusqu'au dernier etat
            var1 = var1 + int(etat.id)
        Netat = State(
            var1, False, False,
            "etat puit")  #on crée le nouveau etat qui sera placé a la fin
        auto.addState(Netat)  #on l'ajoute a l'automate
        for etat in auto.listStates:  #Mnt on parcour tout les etats
            etiquettes = []  #liste poubelles pour recuperer les etiquettes
            for transiotioon in auto.getListTransitionsFrom(
                    etat
            ):  #si on trouve une transition qui ne possède pas une etiquette
                if transiotioon.etiquette not in etiquettes:  #alors on l'ajoute a la liste des etiquettes
                    etiquettes.append(transiotioon.etiquette)
            for lettre in alphabet:
                if lettre not in etiquettes:  #ici on cherche les lettres qui manque puis on les ajoute
                    auto.addTransition(Transition(etat, lettre, Netat))

        return auto
Exemplo n.º 22
0
def generate():
    Q = {"t", "f"}
    T = {Transition(("t", "f"), ("t", "t"))}
    S = {"t", "f"}
    I = {"t": "t", "f": "f"}
    O = {"t": 1, "f": 0}

    return Protocol(Q, T, S, I, O)
Exemplo n.º 23
0
 def __init__(self, ioutils):
     
     # State machine's state
     self.state = State()
     # State machine's transition
     self.transition = Transition(ioutils)
     # test class to handle LEDs colors depending on current state
     self.test = Test()
Exemplo n.º 24
0
    def intersection(auto1, auto2):
        """ Automate x Automate -> Automate
        rend l'automate acceptant pour langage l'intersection des langages des deux automates
        """
        autoNew1 = auto1
        autonew2 = auto2

        if (Automate.estDeterministe(auto1) == False):
            autoNew1 = Automate.determinisation(auto1)
        if (Automate.estDeterministe(auto2) == False):
            autonew2 = Automate.determinisation(auto2)

        autoNew = Automate([], [])

        listeAlpha1 = autoNew1.getAlphabetFromTransitions()
        listeAlpha2 = autonew2.getAlphabetFromTransitions()
        listeAlpha = [val for val in listeAlpha1 if val in listeAlpha2]

        listeInt1 = autoNew1.getListInitialStates()
        listeInt2 = autonew2.getListInitialStates()
        listeProduit = list(itertools.product(listeInt1, listeInt2))

        #creation de la liste des etats du nouvel automate
        for couple in listeProduit:
            for c in listeAlpha:
                listee = autoNew1.succElem(couple[0], c)
                listee += autonew2.succElem(couple[1], c)
                if (len(listee) != 2):
                    continue
                if tuple(listee) not in listeProduit:
                    listeProduit.append(tuple(listee))
        #creation des etats
        for i in range(0, len(listeProduit)):
            if (i == 0):
                autoNew.listStates.append(State(i, True, False))
            else:
                autoNew.listStates.append(State(i, False, False))
        #creation des transition
        for couple in listeProduit:
            for c in listeAlpha:
                listee = autoNew1.succElem(couple[0], c)
                listee += autonew2.succElem(couple[1], c)
                indiceCouple = autoNew.listStates[listeProduit.index(couple)]
                indiceSucc = autoNew.listStates[listeProduit.index(
                    tuple(listee))]
                autoNew.addTransition(Transition(indiceCouple, c, indiceSucc))
        #creation des etats finaux
        listFin1 = autoNew1.getListFinalStates()
        listFin2 = autonew2.getListFinalStates()

        listeProduitFin = list(itertools.product(listFin1, listFin2))

        for couple in listeProduitFin:
            if couple in listeProduit:
                autoNew.listStates[listeProduit.index(couple)].fin = True

        return autoNew
Exemplo n.º 25
0
    def __init__(self, training_set):
        self.training_set = training_set

        # Getting tags from transition probs
        self.tags = []

        # Create the transition and emission interfaces
        self.transition = Transition(self.training_set)
        self.emitter = Emitter(self.training_set)
Exemplo n.º 26
0
    def push(self, state, action, state_next, reward):
        """state, action, state_next, rewardをメモリに保存します"""
        self.size += 1

        priority = self.tree.max()
        if priority <= 0:
            priority = 1

        self.tree.add(priority, Transition(state, action, state_next, reward))
Exemplo n.º 27
0
def tick(start_time, start_angle, change_in_value, duration, target_angle):
    current_time = current_milli_time()
    elapsed_time = start_time - current_time
    cur_angle = Transition().ease_in_out_sine(current_time=elapsed_time,
                            start_value=start_angle,
                            change_in_value=change_in_value,
                            duration=duration, 
                            start_time=start_time, target_angle=target_angle)   
    return cur_angle
Exemplo n.º 28
0
    def __evaluate_event_rx(self, rx_event_id: int, rx_value: str,
                            data_frame: pd.DataFrame):

        # Find events caused by the rx
        if rx_event_id not in data_frame.index:
            return
        events_in_between = data_frame.loc[[rx_event_id], :]

        # Keep a tmp variable with the state that can have been changed
        # thanks to this reception
        new_state = set()

        # Keep a list of transmitted routes
        transmitted_routes = []

        # Check each row of the events caused by the reception
        for row_event, row_value in zip(
                events_in_between[NodeAnalyzer.EVALUATION_COLUMNS[2]],
                events_in_between[NodeAnalyzer.EVALUATION_COLUMNS[5]]):
            # If the event is a change in the state, I update the local
            # variable that keeps the state
            if row_event == Events.RIB_CHANGE:
                new_state = NodeAnalyzer.__evaluate_rib_change(row_value)
            # If the event is a TX i update the corresponding sets
            if row_event == Events.TX:
                elem = self.__evaluate_tx(row_value)
                if elem not in transmitted_routes:
                    transmitted_routes.append(elem)

        # Evaluate the reception event
        received_route = self.__evaluate_rx(rx_value)

        transmitted_routes = None if len(transmitted_routes) == 0 else \
                             sorted(transmitted_routes)

        new_state = self.__state_analyzer(new_state, rx_value)
        self.__state_register(new_state)

        # Create the new transition
        input_state = NodeAnalyzer.hash_state_set(self.actual_state)
        output_state = NodeAnalyzer.hash_state_set(new_state)
        transition = Transition(input_state, output_state, received_route,
                                transmitted_routes)

        # Change the state
        self.actual_state = new_state
        # Check if the transition has already been known
        if hash(transition) not in self.transitions.index:
            self.transitions.loc[hash(transition)] = [
                transition.init_state, transition.output_state,
                transition.input, transition.output, transition.counter
            ]
        else:
            # The transition is already in the dictionary, increase the
            self.transitions.at[hash(transition),
                                NodeAnalyzer.TRANSITIONS_COLUMNS[5]] += 1
    def push(self, state, action, state_next, reward):
        """state, action, state_next, rewardをメモリに保存します"""

        if len(self.memory) < self.capacity:
            self.memory.append(None)  # メモリが満タンでないときは足す

        # namedtupleのTransitionを使用し、値とフィールド名をペアにして保存します
        self.memory[self.index] = Transition(state, action, state_next, reward)

        self.index = (self.index + 1) % self.capacity  # 保存するindexを1つずらす
Exemplo n.º 30
0
 def handle_reached_ship(self, state):
     ts = datetime.datetime.now()
     transition_id = TransitionId(state.room, state.door, NullDoor,
                                  state.items, state.beams)
     transition_time = TransitionTime(state.last_gametime_room,
                                      state.last_realtime_room,
                                      state.last_room_lag, FrameCount(0),
                                      state.last_realtime_door)
     transition = Transition(ts, transition_id, transition_time)
     self.on_transitioned(transition)