Ejemplo n.º 1
0
    def initializeObservationTable(self):

        self.log.info("Initialization of the observation table")
        self.suffixes = []
        self.D = []
        # Create the S and SA
        self.S = []
        self.SA = []
        self.initialD = []
        # fullfill D with the dictionary
        for entry in self.getInputDictionary():
            letter = DictionarySymbol(entry)
            mq = MembershipQuery([letter])
            self.addWordInD(mq)
            self.initialD.append(mq)
#            self.D.append(letter)
#            self.suffixes.append(letter)

        # Initialize the observation table
        emptyMQ = MembershipQuery([EmptySymbol()])
        self.addWordInS(emptyMQ)
Ejemplo n.º 2
0
    def preloadCacheEntry(self, data, vocabulary):
        tab = data.split(" > ")
        msgSymbols = tab[0]
        mqSymbols = msgSymbols.split(",")
        symbols = []
        for mqSymbol in mqSymbols:
            symbol = vocabulary.getSymbolByName(mqSymbol)
            if symbol is not None:
                symbols.append(symbol)
        mq = MembershipQuery(symbols)

        msgResult = tab[1]
        tmp = msgResult.split(",")
        symbolsResult = []
        for t in tmp:
            symbol = vocabulary.getSymbolByName(t)
            if symbol is not None:
                symbolsResult.append(symbol)
        self.cacheResult(mq, symbolsResult)
Ejemplo n.º 3
0
    def findCounterExample(self, mmstd, inputSymbols, cache):
        self.log.info("=====================================================")
        self.log.info("Find a counterexample which invalids the given MMSTD")
        self.log.info("=====================================================")

        inputDictionary = []
        for entry in inputSymbols:
            letter = DictionarySymbol(entry)
            inputDictionary.append(letter)
            self.log.info("The vocabulary contains: {0}".format(str(letter)))

        # -----------------------------------------------------------------------
        # FIRST WE COMPUTE WHICH WILL WE MAKE !
        # -----------------------------------------------------------------------
        # This our plan to find same
        # STEP 1 : Estimate the maximum number of states (m) in the correct implementation
        #          of the FSM (DONE PREVISOULY AND TRANSMITED THROUGH PARAM self.maxsize
        # STEP 2 : Construct the characterization set W for [MMSTD]
        # STEP 3:
        #          (a) Construct the "testing tree" for MMSTD
        #          (b) Generate the transition cover set P from the testing tree
        # STEP 4 : Construct set Z from W and m
        # STEP 5 : We have the list of so desired test cases = P.Z

        # STEP 2:
        # - Construct a sequence of k-equivalence partitions of the states of MMSTD:

        # Find all the couples of states
        couples = []
        states = mmstd.getAllStates()
        W = []
        self.log.info("The MMSTD has " + str(len(states)) + " states")
        self.log.info("A number of " + str(self.m) + " states is estimated.")
        for state in states:
            for state2 in states:
                if state != state2:
                    found = False
                    for (s1, s2) in couples:
                        if not ((s1 == state) and (s2 == state2) or
                                ((s1 == state2) and (s2 == state))):
                            found = True
                    if not found:
                        couples.append((state, state2))

        self.log.info("A number of " + str(len(couples)) +
                      " couples was found")

        for (state1, state2) in couples:
            self.log.info("Search a distinguish string between " +
                          state1.getName() + " and " + state2.getName())
            z = MembershipQuery([EmptySymbol()])

            mqToTest = deque([])
            for letter in inputDictionary:
                mqToTest.append(
                    z.getMQSuffixedWithMQ(MembershipQuery([letter])))

            lastIndiguishableZ = z
            distinguishableZ = z
            done = False
            i = 0
            while not done:
                mq = mqToTest.popleft()
                if i > self.m * self.m:
                    break

                self.log.info("Can we distinguish with MQ = " + str(mq))
                if not self.canWeDistinguishStates(mmstd, mq, state1, state2):
                    done = False
                    lastIndiguishableZ = mq
                    for letter in inputDictionary:
                        z = mq.getMQSuffixedWithMQ(MembershipQuery([letter]))
                        mqToTest.append(z)
                else:
                    done = True
                    distinguishableZ = mq

                i = i + 1
            self.log.info(
                "FOUND: the following distinguish them: {0} last which doesn't is {1}"
                .format(str(distinguishableZ), str(lastIndiguishableZ)))
            W.append(distinguishableZ)
        self.log.info("=================================")
        self.log.info("W = " + str(W))
        self.log.info("=================================")

        # Execute STEP 3 : We compute P
        # init P = {E, ...}
        currentMQ = MembershipQuery([EmptySymbol()])
        P = [currentMQ]
        openMQ = deque([currentMQ])
        closeMQ = []
        statesSeen = [mmstd.getInitialState()]
        while len(openMQ) > 0:
            self.log.info("Compute P, ...")
            mq = openMQ.popleft()
            tmpstatesSeen = []
            for letter in inputDictionary:
                z = mq.getMQSuffixedWithMQ(MembershipQuery([letter]))
                self.log.debug(
                    "Get output trace if we execute the MMSTD with " +
                    str(z.getSymbols()))
                (trace,
                 outputState) = mmstd.getOutputTrace(mmstd.getInitialState(),
                                                     z.getSymbols())
                if outputState in statesSeen:
                    # we close this one
                    self.log.info("Adding " + str(z) + " in closeMQ")
                    closeMQ.append(z)
                else:
                    tmpstatesSeen.append(outputState)
                    self.log.info("Adding " + str(z) + " in closeMQ")
                    closeMQ.append(z)
                    # still open
                    openMQ.append(z)
            statesSeen.extend(tmpstatesSeen)

        P.extend(closeMQ)

        # STEP 4 : We compute Z
        # it follows the formula Z= W U (X^1.W) U .... U (X^(m-1-n).W) U (W^(m-n).W)
        self.log.info("Computing Z:")
        Z = []
        # First we append W in Z
        for w in W:
            Z.append(w)

        v = self.m - len(states)
        if v < 0:
            v = 0

        mqInputs = []
        for input in inputDictionary:
            mqInputs.append(MembershipQuery([input]))

        X = dict()
        X[0] = W

        for i in range(1, v + 1):
            self.log.info("Computing X^{0}: ".format(str(i)))
            self.log.info("MQ INputs: {}".format(str(len(mqInputs))))
            self.log.info("W: {}".format(str(len(W))))
            X[i] = []
            previousX = X[i - 1]
            self.log.info(previousX)
            for x in previousX:
                X[i].extend(x.multiply(mqInputs))
            for w in W:
                for xi in X[i]:
                    if not xi in Z:
                        Z.append(xi)
                    else:
                        self.log.warn(
                            "Impossible to add X[{0}] = {1} in Z, it already exists"
                            .format(str(i), str(xi)))

        for z in Z:
            self.log.info("z = {0}".format(str(z)))

        # STEP 5 : We have the list of so desired test cases T = P.Z
        T = []
        for p in P:
            T.extend(p.multiply(Z))

        self.log.info("Tests cases are: ")
        for t in T:
            self.log.info("=> {0}".format(str(t)))

        self.log.info(
            "----> Compute the responses to the the tests over our model and compare them with the real one"
        )
        i_test = 0
        # We compute the response to the different tests over our learning model and compare them with the real one
        for test in T:
            i_test = i_test + 1
            # Compute our results
            (traceTest,
             stateTest) = mmstd.getOutputTrace(mmstd.getInitialState(),
                                               test.getSymbols())

            # Verify the request is not in the cache
            cachedValue = cache.getCachedResult(test)
            if cachedValue is None:
                # Compute real results
                if self.resetScript != "":
                    os.system("sh " + self.resetScript)

                self.log.debug("=====================")
                self.log.debug("Execute test {0}/{1}: {2}".format(
                    str(i_test), str(len(T)), str(test)))
                self.log.debug("=====================")

                isMaster = not self.communicationChannel.isServer()

                testedMmstd = test.toMMSTD(mmstd.getVocabulary(),
                                           isMaster)  # TODO TODO
                oracle = NetworkOracle(self.communicationChannel,
                                       isMaster)  # TODO TODO is master ??
                oracle.setMMSTD(testedMmstd)
                oracle.start()
                while oracle.isAlive():
                    time.sleep(0.01)
                oracle.stop()

                if isMaster:
                    resultQuery = oracle.getGeneratedOutputSymbols()
                else:
                    resultQuery = oracle.getGeneratedInputSymbols()
                cache.cacheResult(test, resultQuery)

            else:
                resultQuery = cachedValue

            mqOur = MembershipQuery(traceTest)
            mqTheir = MembershipQuery(resultQuery)

            if not mqOur.isStrictlyEqual(mqTheir):
                self.log.info("========================")
                self.log.info("We found a counter example")
                self.log.info("========================")
                self.log.info("TEST: {0}".format(str(test)))
                self.log.info("OUR: {0}".format(str(mqOur)))
                self.log.info("THEIR: {0}".format(str(mqTheir)))
                return test
            else:
                self.log.info("========================")
                self.log.info("Not a counter example")
                self.log.info("========================")

        return None
    def findCounterExample(self, mmstd, inputSymbols, cache):
        self.log.info("=====================================================")
        self.log.info("Find a counterexample which invalids the given MMSTD")
        self.log.info("=====================================================")

        inputDictionary = []
        for entry in inputSymbols:
            letter = DictionarySymbol(entry)
            inputDictionary.append(letter)
            self.log.info("The vocabulary contains: {0}".format(str(letter)))

        # -----------------------------------------------------------------------
        # FIRST WE COMPUTE WHICH WILL WE MAKE !
        # -----------------------------------------------------------------------
        # This our plan to find same
        # STEP 1 : Estimate the maximum number of states (m) in the correct implementation
        #          of the FSM (DONE PREVISOULY AND TRANSMITED THROUGH PARAM self.maxsize
        # STEP 2 : Construct the characterization set W for [MMSTD]
        # STEP 3:
        #          (a) Construct the "testing tree" for MMSTD
        #          (b) Generate the transition cover set P from the testing tree
        # STEP 4 : Construct set Z from W and m
        # STEP 5 : We have the list of so desired test cases = P.Z

        # STEP 2:
        # - Construct a sequence of k-equivalence partitions of the states of MMSTD:

        # Find all the couples of states
        couples = []
        states = mmstd.getAllStates()
        W = []
        self.log.info("The MMSTD has " + str(len(states)) + " states")
        self.log.info("A number of " + str(self.m) + " states is estimated.")
        for state in states:
            for state2 in states:
                if state != state2:
                    found = False
                    for (s1, s2) in couples:
                        if not ((s1 == state) and (s2 == state2) or ((s1 == state2) and (s2 == state))):
                            found = True
                    if not found:
                        couples.append((state, state2))

        self.log.info("A number of " + str(len(couples)) + " couples was found")

        for (state1, state2) in couples:
            self.log.info("Search a distinguish string between " + state1.getName() + " and " + state2.getName())
            z = MembershipQuery([EmptySymbol()])

            mqToTest = deque([])
            for letter in inputDictionary:
                mqToTest.append(z.getMQSuffixedWithMQ(MembershipQuery([letter])))

            lastIndiguishableZ = z
            distinguishableZ = z
            done = False
            i = 0
            while not done:
                mq = mqToTest.popleft()
                if i > self.m * self.m:
                    break

                self.log.info("Can we distinguish with MQ = " + str(mq))
                if not self.canWeDistinguishStates(mmstd, mq, state1, state2):
                    done = False
                    lastIndiguishableZ = mq
                    for letter in inputDictionary:
                        z = mq.getMQSuffixedWithMQ(MembershipQuery([letter]))
                        mqToTest.append(z)
                else:
                    done = True
                    distinguishableZ = mq

                i = i + 1
            self.log.info("FOUND: the following distinguish them: {0} last which doesn't is {1}".format(str(distinguishableZ), str(lastIndiguishableZ)))
            W.append(distinguishableZ)
        self.log.info("=================================")
        self.log.info("W = " + str(W))
        self.log.info("=================================")

        # Execute STEP 3 : We compute P
        # init P = {E, ...}
        currentMQ = MembershipQuery([EmptySymbol()])
        P = [currentMQ]
        openMQ = deque([currentMQ])
        closeMQ = []
        statesSeen = [mmstd.getInitialState()]
        while len(openMQ) > 0:
            self.log.info("Compute P, ...")
            mq = openMQ.popleft()
            tmpstatesSeen = []
            for letter in inputDictionary:
                z = mq.getMQSuffixedWithMQ(MembershipQuery([letter]))
                self.log.debug("Get output trace if we execute the MMSTD with " + str(z.getSymbols()))
                (trace, outputState) = mmstd.getOutputTrace(mmstd.getInitialState(), z.getSymbols())
                if outputState in statesSeen:
                    # we close this one
                    self.log.info("Adding " + str(z) + " in closeMQ")
                    closeMQ.append(z)
                else:
                    tmpstatesSeen.append(outputState)
                    self.log.info("Adding " + str(z) + " in closeMQ")
                    closeMQ.append(z)
                    # still open
                    openMQ.append(z)
            statesSeen.extend(tmpstatesSeen)

        P.extend(closeMQ)

        # STEP 4 : We compute Z
        # it follows the formula Z= W U (X^1.W) U .... U (X^(m-1-n).W) U (W^(m-n).W)
        self.log.info("Computing Z:")
        Z = []
        # First we append W in Z
        for w in W:
            Z.append(w)

        v = self.m - len(states)
        if v < 0:
            v = 0

        mqInputs = []
        for input in inputDictionary:
            mqInputs.append(MembershipQuery([input]))

        X = dict()
        X[0] = W

        for i in range(1, v + 1):
            self.log.info("Computing X^{0}: ".format(str(i)))
            self.log.info("MQ INputs: ".format(str(len(mqInputs))))
            self.log.info("W: ".format(str(len(W))))
            X[i] = []
            previousX = X[i - 1]
            self.log.info(previousX)
            for x in previousX:
                X[i].extend(x.multiply(mqInputs))
            for w in W:
                for xi in X[i]:
                    if not xi in Z:
                        Z.append(xi)
                    else:
                        self.log.warn("Impossible to add X[{0}] = {1} in Z, it already exists".format(str(i), str(xi)))

        for z in Z:
            self.log.info("z = {0}".format(str(z)))

        # STEP 5 : We have the list of so desired test cases T = P.Z
        T = []
        for p in P:
            T.extend(p.multiply(Z))

        self.log.info("Tests cases are: ")
        for t in T:
            self.log.info("=> {0}".format(str(t)))

        testsResults = dict()
        self.log.info("----> Compute the responses to the the tests over our model and compare them with the real one")
        i_test = 0
        # We compute the response to the different tests over our learning model and compare them with the real one
        for test in T:
            i_test = i_test + 1
            # Compute our results
            (traceTest, stateTest) = mmstd.getOutputTrace(mmstd.getInitialState(), test.getSymbols())

            # Verify the request is not in the cache
            cachedValue = cache.getCachedResult(test)
            if cachedValue is None:
                # Compute real results
                if self.resetScript != "":
                    os.system("sh " + self.resetScript)

                self.log.debug("=====================")
                self.log.debug("Execute test {0}/{1}: {2}".format(str(i_test), str(len(T)), str(test)))
                self.log.debug("=====================")

                isMaster = not self.communicationChannel.isServer()

                testedMmstd = test.toMMSTD(mmstd.getVocabulary(), isMaster)  # TODO TODO
                oracle = NetworkOracle(self.communicationChannel, isMaster)  # TODO TODO is master ??
                oracle.setMMSTD(testedMmstd)
                oracle.start()
                while oracle.isAlive():
                    time.sleep(0.01)
                oracle.stop()

                if isMaster:
                    resultQuery = oracle.getGeneratedOutputSymbols()
                else:
                    resultQuery = oracle.getGeneratedInputSymbols()
                cache.cacheResult(test, resultQuery)

            else:
                resultQuery = cachedValue

            mqOur = MembershipQuery(traceTest)
            mqTheir = MembershipQuery(resultQuery)

            if not mqOur.isStrictlyEqual(mqTheir):
                self.log.info("========================")
                self.log.info("We found a counter example")
                self.log.info("========================")
                self.log.info("TEST: {0}".format(str(test)))
                self.log.info("OUR: {0}".format(str(mqOur)))
                self.log.info("THEIR: {0}".format(str(mqTheir)))
                return test
            else:
                self.log.info("========================")
                self.log.info("Not a counter example")
                self.log.info("========================")

        return None
Ejemplo n.º 5
0
    def computeAutomata(self):
        wordAndStates = []
        startState = None
        idState = 0
        idTransition = 0
        states = []

        self.log.info("Compute the automata...")

        # Create the states of the automata
        uniqueRowsInS = self.getUniqueRowsInS()
        for (w, r) in uniqueRowsInS:
            self.log.info("The row with word {0} is unique !".format(str(w)))
            # We create a State for each unique row
            nameState = self.appendValuesInRow(r)
            self.log.info("Create state: {0}".format(nameState))
            currentState = NormalState(idState, nameState)
            states.append(currentState)
            wordAndStates.append((w, currentState))
            # Is it the starting state (wordS = [EmptySymbol])
            if startState is None and w == MembershipQuery([EmptySymbol()]):
                startState = currentState
                self.log.info("Its the starting state")

            idState = idState + 1

        self.log.debug("Create the transition of the automata")
        # Create the transitions of the automata
        for (word, state) in wordAndStates:
            self.log.debug("Working on state: {0}".format(str(state.getName())))

            for symbol in self.initialD:
                # retrieve the value:
                dicValue = self.observationTable[symbol]
                value = dicValue[word]
                # search for the output state
                mq = word.getMQSuffixedWithMQ(symbol)
                self.log.debug("> What happen when we send " + str(symbol) + " after " + str(word))
                self.log.debug(">> " + str(mq))

                for wordSandSA in self.getSandSAWords():
                    self.log.info("IS " + str(wordSandSA) + " eq " + str(mq))
                    if wordSandSA == mq:
                        self.log.info("YES its equal")
                        rowOutputState = self.getRowOfObservationTable(wordSandSA)
                        outputStateName = self.appendValuesInRow(rowOutputState)
                        self.log.debug("rowOutputState = " + str(rowOutputState))
                        self.log.debug("outputStateName = " + str(outputStateName))

                        # search for the state having this name:
                        outputState = None
                        self.log.info("Search for the output state: {0}".format(outputStateName))
                        for (w2, s2) in wordAndStates:
                            if s2.getName() == outputStateName:
                                outputState = s2
                                self.log.info("  == " + str(s2.getName()))
                            else:
                                self.log.info("   != " + str(s2.getName()))

                        if outputState is not None:
                            inputSymbol = symbol.getSymbolsWhichAreNotEmpty()[0]

                            self.log.info("We create a transition from " + str(state.getName()) + "=>" + str(outputState.getName()))
                            self.log.info(" input: {0}".format(str(inputSymbol)))
                            self.log.info(" output: {0}".format(str(value)))

                            transition = SemiStochasticTransition(idTransition, "Transition " + str(idTransition), state, outputState, inputSymbol)
                            transition.addOutputSymbol(value, 100, 1000)
                            state.registerTransition(transition)

                            idTransition = idTransition + 1

                        else:
                            self.log.error("<!!> Impossible to retrieve the output state named " + str(s2.getName()))

        if startState is not None:
            self.log.info("An infered automata has been computed.")

            self.inferedAutomata = MMSTD(startState, self.dictionary)
            for state in states:
                self.inferedAutomata.addState(state)
            self.log.info(self.inferedAutomata.getDotCode())