Пример #1
0
    def intersect(self, other):
        """ return an FA that is the intersection of this FA with other """
        start_label = frozenset([self.start_state, other.start_state])
        states = {start_label: State()}  # maps a label to its new state
        transitions = dict()
        final_states = set()

        boundary = {start_label}
        while boundary:
            label = boundary.pop()
            if all(x in self.final_states | other.final_states for x in label):
                final_states.add(states[label])

            for symbol in self.alphabet:
                # build next label
                merged_transitions = {**self.transitions, **other.transitions}
                next_label = [merged_transitions[x, symbol] for x in label]
                next_label = frozenset(next_label)
                # create state for new labels
                if next_label not in states:
                    states[next_label] = State()
                    boundary.add(next_label)

                transitions[states[label], symbol] = states[next_label]

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[start_label],
            final_states,
        )
Пример #2
0
    def kleene_star(self):
        """ return an FA that is the kleene closure of this FA """
        start_label = frozenset([self.start_state])
        states = {start_label: State()}
        transitions = dict()
        final_states = {states[start_label]}

        boundary = {start_label}
        while boundary:
            label = boundary.pop()
            if any(x in self.final_states for x in label):
                final_states.add(states[label])

            for symbol in self.alphabet:
                # build next label
                next_label = [self.transitions[x, symbol] for x in label]
                if any(x in self.final_states for x in next_label):
                    next_label.append(self.start_state)
                next_label = frozenset(next_label)
                # create state for new labels
                if next_label not in states:
                    states[next_label] = State()
                    boundary.add(next_label)

                transitions[states[label], symbol] = states[next_label]

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[start_label],
            final_states,
        )
Пример #3
0
    def from_atom(cls, atom, alphabet="ab"):
        """create an FA from an atom"""
        state = start_state = State()
        garbage = State()
        states = {start_state, garbage}
        transitions = {(garbage, symbol): garbage for symbol in alphabet}

        for char in atom:
            new_state = State()
            for symbol in alphabet:
                transitions[state,
                            symbol] = new_state if char == symbol else garbage
            state = new_state
            states.add(state)

        # have all edges from final state point to garbage state
        transitions.update({(state, symbol): garbage for symbol in alphabet})
        return cls(states, alphabet, transitions, start_state, {state})
Пример #4
0
    def test_tcp_fsm(self):
        STATES = ['LISTEN', 'SYN RCVD', 'ESTABLISHED', 'SYN SENT', 
          'FIN WAIT 1', 'FIN WAIT 2', 'TIME WAIT', 'CLOSING', 'CLOSE WAIT',
          'LAST ACK']

        tcpip = FiniteStateMachine('TCP IP')
        closed = State('CLOSED', initial=True)
        listen, synrcvd, established, synsent, finwait1, finwait2, timewait, \
        closing, closewait, lastack = [State(s) for s in STATES]
        
        timewait['(wait)'] = closed
        closed.update({r'passive\nopen': listen,
                       'send SYN': synsent})
        
        synsent.update({r'close /\ntimeout': closed,
                        r'recv SYN,\nsend\nSYN+ACK': synrcvd,
                        r'recv SYN+ACK,\nsend ACK': established})
        
        listen.update({r'recv SYN,\nsend\nSYN+ACK': synrcvd,
                       'send SYN': synsent})
        
        synrcvd.update({'recv ACK': established,
                        'send FIN': finwait1,
                        'recv RST': listen})
        
        established.update({'send FIN': finwait1,
                            r'recv FIN,\nsend ACK': closewait})
        
        closewait['send FIN'] = lastack
        
        lastack['recv ACK'] = closed
        
        finwait1.update({'send ACK': closing,
                         'recv ACK': finwait2,
                         r'recv FIN, ACK\n send ACK': timewait})
        
        finwait2[r'recv FIN,\nsend ACK'] = timewait
        
        closing[r'recv\nACK'] = timewait
        
        graph = get_graph(tcpip)
        graph.draw('tcp.png', prog='dot')
Пример #5
0
def initialize_fsm():
    req_data = request.get_json()

    global fsm
    fsm = FiniteStateMachine(State(req_data['start']))

    for transition in req_data['transitions']:
        print_transition_data(transition)
        fsm.add_transition(transition['currentState'], transition['nextState'],
                           transition['actionName'])

    return json.dumps(req_data), 201
Пример #6
0
 def drawStateTransitionGraph():
     #Here we appy the state transitions to create a finite state machine
     ktail = FiniteStateMachine('K-TAIL')
     for nx,kvx in stateMap1.items():
             for c in kvx:
                 State(nx).update({kvx[c]:State(c)})
                 print 'State Transition: ' +str(nx) + '-->'+str(c) + '[label='+kvx[c] +']'
             #Define initial state    
             if nx==0:
                     nx=State(0, initial=True)
     #Create a state machine
     print '------------------------------------------------------------------------------------'
     #Check if there is existing graph data 
     try:
         graph=get_graph(ktail)
         if graph!=None:
             graph.draw('../graph/ktail.png', prog='dot')
             print graph
         else:
             pass
     except GraphvizError:
         tkMessageBox.ERROR
Пример #7
0
def mk_state(mode, name, next_state, condition):
    return State(
        id=mode.value,
        name=name,
        attributes={"mode": mode.value},
        transitions=[
            Transition(
                id=f"{mode.value}_to_{next_state.value}",
                next=next_state.value,
                conditions=[condition],
            )
        ],
    )
Пример #8
0
    def concatenate(self, other):
        """ return an FA that is the concatenation of this FA with other """
        start_label = [self.start_state]
        if self.start_state in self.final_states:
            start_label.append(other.start_state)
        start_label = frozenset(start_label)

        states = {start_label: State()}
        transitions = dict()
        final_states = set()

        boundary = {start_label}
        while boundary:
            label = boundary.pop()
            if any(x in other.final_states for x in label):
                final_states.add(states[label])

            for symbol in self.alphabet:
                # build next label
                merged_transitions = {**self.transitions, **other.transitions}
                next_label = [merged_transitions[x, symbol] for x in label]
                if any(x in self.final_states for x in next_label):
                    next_label.append(other.start_state)
                next_label = frozenset(next_label)
                # create state for new labels
                if next_label not in states:
                    states[next_label] = State()
                    boundary.add(next_label)

                transitions[states[label], symbol] = states[next_label]

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[start_label],
            final_states,
        )
Пример #9
0
    def complement(self):
        """return a DFA that is the complement of this DFA"""
        states = {x: State() for x in self.states}
        transitions = {(states[state], symbol): states[to_state]
                       for (state,
                            symbol), to_state in self.transitions.items()}
        final_states = {
            states[state]
            for state in self.states - self.final_states
        }

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[self.start_state],
            final_states,
        )
Пример #10
0
    def test_parkingmeter_fsm(self):
        parking_meter = MooreMachine('Parking Meter')

        ready = State('Ready', initial=True)
        verify = State('Verify')
        await_action = State(r'Await\naction')
        print_tkt = State('Print ticket')
        return_money = State(r'Return\nmoney')
        reject = State('Reject coin')
        ready[r'coin inserted'] = verify
        
        verify.update({'valid': State(r'add value\rto ticket'), 
                       'invalid': reject})
        
        for coin_value in verify:
            verify[coin_value][''] = await_action
        
        await_action.update({'print': print_tkt,
                             'coin': verify,
                             'abort': return_money,
                             'timeout': return_money})
        return_money[''] = print_tkt[''] = ready
        get_graph(parking_meter).draw('parking.png', prog='dot')
Пример #11
0
Файл: loop.py Проект: NielXu/fsm

def foo(mapper):
    if mapper["a"] < mapper["k"]:
        return False
    return True


def incre(mapper):
    print("Looping:", mapper["a"])
    mapper["a"] += 1


set_any("*")

start = State("Start")
s0 = State("Loop", exe=incre)
end = State("End")

# Start state go to s0 directly
start.add_transit(get_any(), s0)
# Define bool expr
sin0 = Signal(foo)

# Define two transits, if a >= k go to end
# Otherwise, go back to itself
s0.add_transit(sin0, end)
s0.add_transit(get_any(), s0)

m = Machine(start, [end], mapper)
m.start()
Пример #12
0
from fsm import MealyMachine, State

adder = MealyMachine('Binary addition')

carry = State('carry')
nocarry = State('no carry', initial=True)

nocarry[(1, 0), 1] = nocarry
nocarry[(0, 1), 1] = nocarry
nocarry[(0, 0), 0] = nocarry
nocarry[(1, 1), 0] = carry

carry[(1, 1), 1] = carry
carry[(0, 1), 0] = carry
carry[(1, 0), 0] = carry
carry[(0, 0), 1] = nocarry

number1 = list(int (i) for i in '0001010')
number2 = list(int (i) for i in '0001111')

inputs = zip(number1, number2)

print list(adder.process(inputs[::-1]))[::-1]
Пример #13
0
from fsm import FiniteStateMachine, State
import itertools

STATES = [
    "A", "AC", "ACE", "ACEM", "ACEMU", "ACEMK", "ACK", "ACKM", "ACKME",
    "ACKMU", "ACKS", "ACKSU", "ACKSQ", "ACKI", "ACKIQ", "AI", "AIQ", "AIQS",
    "AIQSK", "AIQSU", "AIK", "AIKC", "AIKCE", "AIKM", "AIKME", "AIKMU", "AIKS",
    "AIKSQ", "AIKSU", "REWARD", "PUNISHMENT"
]

bad_states = [s for s in STATES if (s != "ACKMU") and (len(s) == 5)]

maze = FiniteStateMachine("maze")

states = {}
states['A'] = State('A', initial=True)
for state in STATES[1:]:
    states[state] = State(state)
    states[state].DOT_ATTRS['shape'] = 'rectangle'
    states[state].DOT_ATTRS['height'] = 0.3

states['REWARD'].DOT_ATTRS['fillcolor'] = 'green'
states['PUNISHMENT'].DOT_ATTRS['fillcolor'] = 'red'

states['A'].update({'right': states['AC'], 'down': states['AI']})

states['AC'].update({'right': states['ACE'], 'down': states['ACK']})

states['ACE'].update({'down': states['ACEM']})

states['ACEM'].update({'left': states['ACEMK'], 'down': states['ACEMU']})
Пример #14
0
    def createContentModel(self, node, _stack=list()):
        name = node.prop("name")
        minOccurs = node.prop("minOccurs")
        minOccurs = 1 if minOccurs is None else int(minOccurs)
        maxOccurs = node.prop("maxOccurs")
        maxOccurs = 1 if maxOccurs is None else (
            maxOccurs if maxOccurs == "unbounded" else int(maxOccurs))
        fsm = None
        ea = list()
        la = list()
        self.processActions(node, ea, la)
        if _stack.count(node) > 0:
            if node.name != "element" or ("{%s}%s" %
                                          (self.targetNamespace(node),
                                           name)) not in self.providedElements:
                print "*** recursion detected ***"
                return XMLFsm().empty()

        stack = list(_stack)
        stack.append(node)
        print "%s%s: '{%s}%s' (%s, %s) %s | %s" % (
            len(_stack) * "  ", node.name, self.targetNamespace(node), name,
            minOccurs, maxOccurs, [self.actions[e]
                                   for e in ea], [self.actions[a] for a in la])
        for case in switch(node.name):
            if case("element"):
                # wenn Referenz, dann verwende das Model des referenzierten Elements und wende Aktionen und Particle-Rule an
                if node.prop("ref") is not None:
                    ref = self.Decls[1][self.expandQName(
                        node, node.prop("ref"))]
                    if ref is None:
                        raise BaseException(
                            "Referenced element not known: %s" %
                            node.prop("ref"))
#					print "Verwende referenz %s" % node.prop("ref")
                    fsm = self.createContentModel(
                        ref, stack).onenter(ea).onleave(la).particle(
                            minOccurs, maxOccurs)
                else:
                    # sonst, falls nicht abstract, baue das Modell aus dem angegebenen Typ oder den Kind-Elementen
                    #   und erzeuge das Element
                    # erzeuge für jedes Mitglied der SubstitutionGroup das Inhaltsmodell und ggf. den Aufruf für die Gruppe
                    #   und füge diese mit dem für dieses Element zusammen
                    # Ist das Element provided, wird ein Einsprung dafür definiert
                    substitutions = []
                    name = node.prop("name")
                    if name is None:
                        raise BaseException(
                            "Element declaration requires a name")

                    qname = "{%s}%s" % (self.targetNamespace(node), name)
                    if qname in self.providedElements or \
                       qname in self.elements:
                        #						print "Creating call to %s" % name
                        # Einsprung via Element-Name in Zielmaschine; abstract="true" impliziert --preserve-substitution
                        fsm = XMLFsm()
                        fsm.entry = State()
                        leave = State()
                        fsm.entry.addTransition(
                            self.getElementId(
                                self.targetNamespace(node),
                                "%s%s" % ('!' if node.prop("abstract")
                                          == "true" else "", name)), leave, ea)
                        fsm.accepts.add(leave)
                        fsm = fsm.particle(minOccurs, maxOccurs)
                    else:
                        #						print "%s nicht in %s" % (qname, self.providedElements)
                        if "{%s}%s" % (self.targetNamespace(node),
                                       name) in self.genElements:
                            self.providedElements.add(
                                "{%s}%s" % (self.targetNamespace(node), name))
                        if node.prop("abstract") != "true":
                            #							print "Erzeuge content model fuer %s" % name
                            content = None
                            # compute the direct content model
                            if node.prop("type") is not None:
                                typename = self.expandQName(
                                    node, node.prop("type"),
                                    self.targetNamespace(node))
                                if not self.Decls[2].has_key(typename):
                                    raise BaseException("Unknown type %s" %
                                                        typename)
                                if self.Decls[2][typename] is not None:
                                    content = self.createContentModel(
                                        self.Decls[2][typename], stack)
                                # if None, it is a predefined simpleType
                            else:
                                child = node.children
                                while child is not None:
                                    if child.name in ("simpleType",
                                                      "complexType"):
                                        content = self.createContentModel(
                                            child, stack)
                                        break
                                    child = child.next
                            if content is None:
                                content = XMLFsm().empty()
                            substitutions.append(XMLFsm().element(
                                self.getElementId(self.targetNamespace(node),
                                                  name), content, ea,
                                la).particle(minOccurs, maxOccurs))
#						else:
#							print "Kein content-model fuer %s, da abstract" % name

                        if self.substs.has_key(qname):
                            for child in self.substs[qname]:
                                #								print "Fuege subst %s fuer %s hinzu" % (child.prop("name"), qname)
                                substitutions.append(
                                    self.createContentModel(child, stack))
                        if qname in self.preservedSubsts:
                            f = XMLFsm()
                            f.entry = State()
                            leave = State()
                            f.entry.addTransition(
                                self.getElementId(self.targetNamespace(node),
                                                  "!%s" % name), leave, ea)
                            f.accepts.add(leave)
                            substitutions.append(f)
                        fsm = XMLFsm().empty() if len(
                            substitutions) == 0 else XMLFsm().choice(
                                substitutions).particle(minOccurs, maxOccurs)
                break

            if case("simpleType", "simpleContent"):
                fsm = XMLFsm().empty()
                break

            if case("complexType"):
                if node.prop("name") is None or self.expandQName(
                        node, node.prop("name"),
                        self.targetNamespace(node)) not in self.providedTypes:
                    if "{%s}%s" % (self.targetNamespace(node),
                                   name) in self.genTypes:
                        self.providedTypes.add(
                            "{%s}%s" % (self.targetNamespace(node), name))
                    child = node.children
                    while child is not None:
                        if child.name in ("simpleContent", "complexContent",
                                          "group", "choice", "sequence",
                                          "all"):
                            fsm = self.createContentModel(
                                child, stack).onenter(ea).onleave(la)
                            break
                        child = child.next
                if fsm is None: fsm = XMLFsm().empty()
                break

            if case("sequence", "choice"):
                content = []
                child = node.children
                while child is not None:
                    if child.name in ("element", "group", "choice", "sequence",
                                      "any"):
                        content.append(self.createContentModel(child, stack))
                    child = child.next
                fsm = XMLFsm().empty() if len(content) == 0 else (
                    XMLFsm().sequence(content, ea, la)
                    if node.name == "sequence" else XMLFsm().choice(
                        content, ea, la)).particle(minOccurs, maxOccurs)
                break

            if case("complexContent"):
                content = None
                child = node.children
                while child is not None:
                    if child.name in ("extension", "restriction"):
                        content = self.createContentModel(child, stack)
                        break
                    child = child.next
                fsm = XMLFsm().empty() if content is None else content
                break

            if case("extension", "restriction"):
                if node.name == "extension":
                    qname = self.expandQName(node, node.prop("base"),
                                             self.targetNamespace(node))
                    if qname not in self.Decls[2]:
                        raise BaseException("base type %s not known" % qname)
                    base = self.Decls[2][qname]
                    baseContent = XMLFsm().empty(
                    ) if base is None else self.createContentModel(
                        base, stack)
                else:
                    baseContent = XMLFsm().empty()
                content = None
                child = node.children
                while child is not None:
                    if child.name in ("group", "choice", "sequence"):
                        content = self.createContentModel(child, stack)
                        break
                    child = child.next
                fsm = baseContent if content is None else baseContent.concat(
                    content)
                break

            if case("any"):
                fsm = XMLFsm().element(
                    self.getElementId(self.targetNamespace(node), "*"),
                    XMLFsm().empty(), ea, la).particle(minOccurs, maxOccurs)
                break

            if case("group"):
                if node.prop("ref") is not None:
                    ref = self.Decls[1][self.expandQName(
                        node, node.prop("ref"))]
                    if ref is None:
                        raise BaseException("Referenced group not known: %s" %
                                            node.prop("ref"))
                    fsm = self.createContentModel(
                        ref, stack).onenter(ea).onleave(la).particle(
                            minOccurs, maxOccurs)
                else:
                    content = None
                    child = node.children
                    while child is not None:
                        if child.name in ("all", "choice", "sequence"):
                            content = self.createContentModel(child, stack)
                            break
                        child = child.next
                    fsm = XMLFsm(
                    ).empty if content is None else content.onenter(
                        ea).onleave(la)
                break

            if case():
                raise BaseException("Unknown schema object: %s" % node.name)


#		self.dump(fsm)
#		print "*" * 32
        if len(stack) % 5 == 0: fsm = fsm.determinize(False).minimize(False)
        return fsm
Пример #15
0
import json

import flask
from flask import request

from fsm import FiniteStateMachine
from fsm import State

app = flask.Flask(__name__)
app.config["DEBUG"] = True

fsm = FiniteStateMachine(State('uninitialized'))


@app.route('/fsm', methods=['GET'])
@app.route('/fsm/current-state', methods=['GET'])
def get_current_state():
    return json.dumps(
        {"currentState": fsm.get_current_state().current_state_name})


@app.route('/fsm/valid-actions', methods=['GET'])
def get_valid_actions():
    return json.dumps({"validActions": fsm.list_valid_actions()})


@app.route('/fsm', methods=['POST'])
def post_fsm():
    args = request.args

    if "action_name" in args:
Пример #16
0
    def generateStateTransition(self, loadEquiState, tmpDictx, dotFile):
        ktailx = loadEquiState

        if len(ktailx) == 0:
            pass

        #Identify unique states from the merged state list
        kTailFSMGraph.getUniqueStates = set()

        for val in ktailx:
            kTailFSMGraph.getUniqueStates.add(val)

        print 'unique states' + str(kTailFSMGraph.getUniqueStates)

        #Dictionary to keep track of the state and its assocated transition labels
        kTailFSMGraph.transDict = {}
        for g in kTailFSMGraph.getUniqueStates:
            for tmpk, tmpv in tmpDictx.items():
                if g == tmpk:
                    kTailFSMGraph.transDict[g] = tmpv

        print 'transDict' + str(kTailFSMGraph.transDict)

        #Create a list of mapping combinations identified from the state merged list
        #Example: [0,1,1,3,4] ==>[0-->1,1-->1,1-->3,3-->4]

        current = None
        nxt = None
        index = 0
        kTailFSMGraph.mapping = []
        while (index + 1) < len(ktailx):
            current = ktailx[index]
            nxt = ktailx[index + 1]
            kTailFSMGraph.mapping.append(str(current) + '-->' + str(nxt))
            index += 1

        print 'mapping' + str(kTailFSMGraph.mapping)

        #This dictionary stores transition of each state
        #A state may have multiple transitions.
        #Example: State 0: may have a or more transitions to itself and another transition to other state

        kTailFSMGraph.stateMap = {}
        kTailFSMGraph.sampleStatemap = {}
        print kTailFSMGraph.transDict
        for td, tv in kTailFSMGraph.transDict.items():
            #Intialize the embedded dictionary with empty string for each state
            if dotFile == 'sample':
                kTailFSMGraph.sampleStatemap[td] = {}
            elif dotFile == 'ktail':
                kTailFSMGraph.stateMap[td] = {
                }  #The embedded dictionary stores the next transition state with the transition label as the key.

        for z in kTailFSMGraph.getUniqueStates:
            for e, f in kTailFSMGraph.transDict.items():
                if z == e:
                    for m in kTailFSMGraph.mapping:
                        st = [int(s) for s in m.split('-->') if s.isdigit()
                              ]  #extract digits in a mapping entry
                        if str(z) == str(st[0]) and str(z) == str(st[1]):
                            if dotFile == 'sample':
                                kTailFSMGraph.sampleStatemap[z][int(st[0])] = f
                            else:
                                kTailFSMGraph.stateMap[z][int(st[0])] = f
                            #Check if the transition from the current node
                            #to the next node is the same as the self-transition on current node
                            #If so then we assign and arbitrary label-as it might cause non-deterministic fsm
                        elif str(z) != str(st[1]) and str(z) == str(st[0]):
                            if dotFile == 'sample':
                                kTailFSMGraph.sampleStatemap[z][int(st[1])] = f
                            else:
                                kTailFSMGraph.stateMap[z][int(st[1])] = f

        print 'Test Input Trace Map' + str(kTailFSMGraph.stateMap)
        print 'Sample Input Trace Map' + str(kTailFSMGraph.sampleStatemap)

        #Look for non-determistic paths in the traces for the sample input.

        if dotFile == 'sample':
            print 'Checking for non-deterministic paths in Sample Trace Automata:'
            kTailFSMGraph.samplendfaloginfor.append(
                'Checking for non-deterministic paths in Sample Trace Automata:'
            )
            for k, v in kTailFSMGraph.transDict.items():
                if self.duplicate_dictionary_check(
                        kTailFSMGraph.sampleStatemap, str(v)) == None:
                    pass
                else:
                    kTailFSMGraph.samplendfaloginfor.append('==>' + str(
                        self.duplicate_dictionary_check(
                            kTailFSMGraph.sampleStatemap, str(v))))
                    print self.duplicate_dictionary_check(
                        kTailFSMGraph.sampleStatemap, str(v))
                    tkMessageBox.showinfo(
                        "Non-deterministic FA",
                        self.duplicate_dictionary_check(
                            kTailFSMGraph.sampleStatemap, str(v)))

        elif dotFile == 'ktail':
            kTailFSMGraph.ndfaloginfor = []  #re
            print 'Checking for non-deterministic paths in Input Trace Automata:'
            kTailFSMGraph.ndfaloginfor.append(
                'Checking for non-deterministic paths in Input Trace Automata:'
            )
            #print 'alpa'+str(alphabet)
            for k, v in kTailFSMGraph.transDict.items():
                #print self.duplicate_dictionary_check(kTailFSMGraph.stateMap,str(v))
                if self.duplicate_dictionary_check(kTailFSMGraph.stateMap,
                                                   str(v)) == None:
                    pass
                else:
                    kTailFSMGraph.ndfaloginfor.append('==>' + str(
                        self.duplicate_dictionary_check(
                            kTailFSMGraph.stateMap, str(v))))
                    print self.duplicate_dictionary_check(
                        kTailFSMGraph.stateMap, str(v))
                    #tkMessageBox.showinfo("Non-deterministic FA", self.duplicate_dictionary_check(kTailFSMGraph.stateMap,str(v)))

        #Here we appy the state transitions to create a finite state machine

        ktailFSM = FiniteStateMachine('K-TAIL')
        kTailFSMGraph.alphabetfromtrace.clear()
        tmpstateMap = {}

        #make a shallow copy of the state map dictionaries
        if dotFile == 'sample':
            tmpstateMap = kTailFSMGraph.sampleStatemap.copy()
        elif dotFile == 'ktail':
            tmpstateMap = kTailFSMGraph.stateMap.copy()

        for nx, kvx in tmpstateMap.items():
            #n=[State(s) for s in list(getUniqueStates)]
            for c in kvx:
                State(nx).update({kvx[c]: State(c)})
                print 'State Transition: ' + str(nx) + '-->' + str(
                    c) + '[label=' + kvx[c] + ']'
                kTailFSMGraph.alphabetfromtrace[(nx, kvx[c])] = c
            #Define initial state
            if nx == 0:
                nx = State(0, initial=True)
            #Define acceptings states for the state machine
            if dotFile == 'sample':
                for a in kTailFSMGraph.accepting_states:
                    if a == nx:
                        nx = State(a, accepting=True)
        #clear the the tmp states map after the operation
        tmpstateMap.clear()
        #Create a state machine

        print '------------------------------------------------------------------------------------'

        try:
            graph = get_graph(ktailFSM)
            if graph != None:  #Check if there is existing graph data
                graph.draw('../graph/' + dotFile + '.png', prog='dot')
            else:
                pass
        except GraphvizError:
            tkMessageBox.ERROR

        print '-------------------------------------------------------------------------------------'
Пример #17
0
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 05 19:20:23 2014

@author: dlmu__000
"""

from fsm import State, Transducer, get_graph

microwave = Transducer('Microwave Oven')

closed_i = State(r'CLOSED\nidle', initial=True)
closed_p = State(r'CLOSED\nprocessing')
opened_i = State(r'OPEN\nidle')
paused = State('PAUSED')
settings = State(r'SETUP')

closed_i[r'PSB, TK /\nset program,\nset timer'] = closed_i
closed_i['SSB / start'] = closed_p
closed_i['ODH / open door'] = opened_i
closed_i['ELS / enter setup'] = settings
settings['SSB / save setup'] = settings
settings['ELS / leave setup'] = closed_i
opened_i['DL / shut door'] = closed_i
closed_p['PRB / pause'] = paused
closed_p['ODH / open door'] = opened_i
closed_p['TO / ready'] = closed_i
paused['SSB / stop'] = closed_i
paused['PRB / resume'] = closed_p
paused[r'PSB, TK /\nreset program,\nreset timer'] = paused
paused['ODH / open door'] = opened_i
Пример #18
0
    def generateStateTransition(self, loadEquivalentState):
        #print k_tail_value,trace
        #kt=kTails('k-tails')
        ktailx = loadEquivalentState  #kt.do_kTailEquivCheck(k_tail_value,trace)

        print 'transition ' + str(ktailx)

        if len(ktailx) == 0:
            pass
        #for mv in ktailx:
        #    if mv==match_Values(ktailx):
        #        print mv

        #Identify unique states from the merged state list
        getUniqueStates = set()
        for val in ktailx:
            getUniqueStates.add(val)

        print getUniqueStates
        #Dictionary to keed track of the state and its assocated transition labels
        transDict = {}
        for g in getUniqueStates:
            for tmpk, tmpv in ktail.tmpDict.items():
                if g == tmpk:
                    transDict[g] = tmpv

        print 'transDict' + str(transDict)

        #Create a list of mapping combinations identified from the state merged list
        #Example: [0,1,1,3,4] ==>[0-->1,1-->1,1-->3,3-->4]
        current = None
        nxt = None
        index = 0
        mapping = []
        while (index + 1) < len(ktailx):
            current = ktailx[index]
            nxt = ktailx[index + 1]
            mapping.append(str(current) + '-->' + str(nxt))
            index += 1

        print 'mapping' + str(mapping)

        #This dictionary stores transition of each state
        #A state may have multiple transitions.
        #Example: State 0: may have a or more transitions to itself and another transition to other state
        stateMap = {}
        print transDict
        for td, tv in transDict.items():
            #for tm in mapping:
            #    stm=[int(s) for s in tm.split('-->') if s.isdigit()]
            #    if str(td)==stm[0]:
            #stateMap[td]={ tv:' '}  #Intialize the embedded dictionary with empty string for each state
            stateMap[td] = {
            }  #The embedded dictionary stores the next transition state with the
            #transition label as the key.
        print 'stateMap' + str(stateMap)
        for z in getUniqueStates:
            for e, f in transDict.items():
                if z == e:
                    for m in mapping:
                        st = [int(s) for s in m.split('-->')
                              if s.isdigit()]  #extract digits a mapping entry
                        if str(z) == str(st[0]) and str(z) == str(st[1]):
                            #if str(z)==m[-1] and str(z)==m[0]:#Check for occurance of transition to itself
                            #if m[0] not in stateMap[z]:
                            stateMap[z][int(st[0])] = f
                            #print 'x'+stateMap[z][m[-1]] + m
                            #Check if the transition from the current node
                            #to the next node is the same as the self-transition on current node
                            #If so then we assign and arbitrary label-as it might cause non-deterministic fsm
                        elif str(z) != str(st[1]) and str(z) == str(st[0]):
                            #print stateMap[z][int(st[1])]
                            stateMap[z][int(st[1])] = f
                        #elif str(z)==str(st[1]) and str(z)!=str(st[0]):
                        #    stateMap[z][int(st[0])]=f
        print 'statemap' + str(stateMap)

        #Here we appy the state transitions to create a finite state machine
        for nx, kvx in stateMap.items():
            #n=[State(s) for s in list(getUniqueStates)]
            for c in kvx:
                State(nx).update({kvx[c]: State(c)})
                print 'State: ' + str(nx) + kvx[c] + ':' + str(c)
            #Define initial state
            if nx == 0:
                nx = State(0, initial=True)

        #Create a state machine
        graph = get_graph(ktail)
        graph.draw('ktail.png', prog='dot')
        print 'End of Print line'
Пример #19
0
from fsm import StateMachine, State
import time
traffic_light = StateMachine("LIGHT_GREEN")

light_green = State()
light_yellow = State()
light_red = State()

traffic_light["LIGHT_GREEN"] = light_green
traffic_light["LIGHT_YELLOW"] = light_yellow
traffic_light["LIGHT_RED"] = light_red


@light_green.transition
def switch():
    return "LIGHT_YELLOW"


@light_yellow.transition
def switch():
    return "LIGHT_RED"


@light_red.transition
def switch():
    return "LIGHT_GREEN"


if __name__ == "__main__":
    while True:
        print("Current State: " + traffic_light.state)
Пример #20
0
import unittest

from fsm import State, FSM

CONNECTION_STATES = [
    State('LISTENING', {
        'connect': 'CONNECTED',
        'error': 'LISTENING'
    }),
    State('CONNECTED', {
        'accept': 'ACCEPTED',
        'close': 'CLOSED'
    }),
    State('ACCEPTED', {
        'close': 'CLOSED',
        'read': 'READING',
        'write': 'WRITING'
    }),
    State('READING', {
        'read': 'READING',
        'close': 'CLOSED',
        'write': 'WRITING'
    }),
    State('WRITING', {
        'read': 'READING',
        'close': 'CLOSED',
        'write': 'WRITING'
    }),
    State('CLOSED', {}, default_event='LISTENING'),
    State('ERROR', {}, default_event='ERROR')
]
Пример #21
0
from fsm import FiniteStateMachine, get_graph, State

STATES = ['LISTEN', 'SYN RCVD', 'ESTABLISHED', 'SYN SENT',
          'FIN WAIT 1', 'FIN WAIT 2', 'TIME WAIT', 'CLOSING', 'CLOSE WAIT',
          'LAST ACK']

tcpip = FiniteStateMachine('TCP IP')

closed = State('CLOSED', initial=True)
listen, synrcvd, established, synsent, finwait1, finwait2, timewait, \
closing, closewait, lastack = [State(s) for s in STATES]

timewait['(wait)'] = closed
closed.update({r'passive\nopen': listen,
               'send SYN': synsent})

synsent.update({r'close /\ntimeout': closed,
                r'recv SYN,\nsend\nSYN+ACK': synrcvd,
                r'recv SYN+ACK,\nsend ACK': established})

listen.update({r'recv SYN,\nsend\nSYN+ACK': synrcvd,
               'send SYN': synsent})

synrcvd.update({'recv ACK': established,
                'send FIN': finwait1,
                'recv RST': listen})

established.update({'send FIN': finwait1,
                    r'recv FIN,\nsend ACK': closewait})

closewait['send FIN'] = lastack
Пример #22
0
from fsm import InitState, State, TerminalState, FSM

fsm = FSM({
    'A': InitState({
        'a': 'A',
        'b': 'B',
        'c': 'D'
    }),
    'B': State({
        'a': 'A',
        'b': 'B',
        'c': 'C'
    }),
    'C': State({
        'a': 'A',
        'b': 'F',
        'c': 'D'
    }),
    'D': State({'b': 'E'}),
    'E': TerminalState({}),
    'F': TerminalState({
        'a': 'A',
        'b': 'B',
        'c': 'C'
    })
})