示例#1
0
        public override CompoundTerm DoStep(InterpretationContext c, CompoundTerm action)
        {
            // Result of invocation must be a value term (must support IComparable)

            IComparable /*?*/ thisArg;

            IComparable /*?*/[] methodArgs = this.ConvertTermArgumentsToMethodArguments(c, action.Arguments, out thisArg);

            foreach (IComparable /*?*/ o in methodArgs)
            {
                AbstractValue.FinalizeImport(o);
            }

            object /*?*/       resultObj    = this.method.methodInfo.Invoke(thisArg, methodArgs);
            CompoundTerm /*?*/ finishAction = null;

            // Handle output args and return value
            if (null != this.finishActionMethod)
            {
                int             nOutputs = this.finishActionMethod.actionLabel.Arguments.Count;
                Sequence <Term> outputs  = Sequence <Term> .EmptySequence;

                for (int i = 0; i < nOutputs; i += 1)
                {
                    int outputArgIndex = this.finishActionMethod.outputArgumentIndices[i];
                    if (-2 == outputArgIndex) // "any" placeholder
                    {
                        outputs = outputs.AddLast(Any.Value);
                    }
                    else
                    {
                        object output = (-1 == outputArgIndex ? resultObj : methodArgs[outputArgIndex]);


                        IComparable outputAsComparable;
                        if (null == output)
                        {
                            outputAsComparable = null;
                        }
                        else
                        {
                            outputAsComparable = output as IComparable;
                            if (null == outputAsComparable)
                            {
                                throw new InvalidOperationException(MessageStrings.LocalizedFormat(MessageStrings.ComparableResultRequired, action.ToString(), output.ToString()));
                            }
                        }
                        outputs = outputs.AddLast(AbstractValue.GetTerm(outputAsComparable));
                    }
                }
                finishAction = new CompoundTerm(this.FinishAction, outputs);
            }

            return(finishAction);
        }
示例#2
0
            void CreateVariableWiewers()
            {
                //view also the control mode of the root state if the product has more than one machine in it
                //the id of the composed state is -1
                //if (leafStates.Count > 1)
                //    termViewers.Add(TermViewer.Create("[Control Mode]", rootState.ControlMode), -1);

                for (int stateId = 0; stateId < this.leafStates.Count; stateId++)
                {
                    IState leafState = this.leafStates[stateId];
                    //string modelName = this.modelNames[stateId];

                    //each state has a control mode, create a viewer for it if the controlMode is
                    //not an empty sequence
                    if (!leafState.ControlMode.ToCompactString().Equals("Sequence()"))
                    {
                        termViewers.Add(TermViewer.Create("[Control Mode]", leafState.ControlMode), stateId);
                    }

                    IExtendedState estate = leafState as IExtendedState;
                    if (estate != null)
                    {
                        #region add the domain map viewer, skip this if there are no domains
                        if (estate.DomainMap.Count > 0)
                        {
                            //StringBuilder sb = new StringBuilder();
                            Sequence <Term> args = Sequence <Term> .EmptySequence;
                            foreach (Pair <Symbol, int> si in estate.DomainMap)
                            {
                                args = args.AddLast(new Literal(si.First.FullName));
                                args = args.AddLast(new Literal(si.Second));
                            }
                            Symbol symb   = Symbol.Parse("Map<String, Integer>");
                            Term   domMap = new CompoundTerm(symb, args);

                            termViewers.Add(TermViewer.Create("[Domain Map]", domMap), stateId);
                        }
                        #endregion

                        //add a viewer for each state variable
                        for (int j = 0; j < estate.LocationValuesCount; j++)
                        {
                            termViewers.Add(TermViewer.Create(estate.GetLocationName(j),
                                                              estate.GetLocationValue(j)), stateId);
                        }
                    }
                }
            }
示例#3
0
        public void AddLine(TextType txtType, String text)
        {
            string indent = "";

            switch ((int)txtType)
            {
            // HeaderOpenBlock
            case 0:
                indent = "    ";
                break;

            // Header
            case 1:
                indent = "    ";
                break;

            // Indent1
            case 2:
                indent = "         ";
                break;

            // CloseBlock
            case 3:
                indent = "    )";
                break;

            // EmptyLine
            case 4:
                indent = "";
                break;
            }

            _text = _text.AddLast(indent + text);
            _type = _type.AddLast(txtType);
        }
示例#4
0
        private void UpdateRequirementMaps(Sequence <CompoundTerm> actions, IState iState)
        {
            Set <string> yesStrings = new Set <string>();

            foreach (Action a in actions)
            {
                System.Console.WriteLine(iState.GetHashCode() + a.ToString());
                foreach (string s in this.modelProgram.GetEnablingConditionDescriptions(iState, a, false))
                {
                    yesStrings = yesStrings.Add(s);
                    if (!requirementProperties.Contains(s))
                    {
                        requirementProperties  = requirementProperties.AddLast(s);
                        requireEnabledStateMap = requireEnabledStateMap.Add(s, Set <int> .EmptySet);
                    }
                    requireEnabledStateMap = requireEnabledStateMap.Override(s, requireEnabledStateMap[s].Add(iState.GetHashCode()));
                }
            }
            bdt = bdt.addState(yesStrings, iState.GetHashCode());
            if (i == 0)
            {
                if (i < requirementProperties.Count)
                {
                    string s1 = requirementProperties[i++];
                    bdt = bdt.Refine(s1, requireEnabledStateMap[s1]);
                    bdt.PrintTree(0);
                }
            }
        }
示例#5
0
        public static int Commit(string client, string message, Map <string, Op> changes)
        {
            foreach (Pair <string, Op> change in changes)
            {
                string              file     = change.First;
                Op                  op       = change.Second;
                Revision            revision = new Revision(op, currentRevision + 1);
                Sequence <Revision> revisions;

                if (db.TryGetValue(file, out revisions))
                {
                    db = db.Override(file, revisions.AddFirst(revision));
                }
                else
                {
                    db = db.Add(file, new Sequence <Revision>(revision));
                }
            }

            currentRevision  = currentRevision + 1;
            revisionMessages = revisionMessages.AddLast(message);
            revisionClients  = revisionClients.AddLast(client);

            return(currentRevision);
        }
示例#6
0
        /// <summary>
        /// For a given type, returns the associated sort (abstract type). This is calculated
        /// by using the value of the "Sort" attribute, or by constructing a symbol from
        /// the type name if the attribute is not present. See <see cref="SortAttribute"/>.
        /// </summary>
        /// <param name="t">The type</param>
        /// <returns>The associated sort</returns>
        public static Symbol TypeSort(Type t)
        {
            Symbol sort;

            // Case 1: use cached sort for this type
            if (typeSorts.TryGetValue(t, out sort))
            {
                return(sort);
            }

            string sortName;

            // Case 2: if instantiated generic type, use sort name from generic type instantiation
            //         and recurse to fill in domain parameters
            if (t.IsGenericType && !t.IsGenericTypeDefinition)
            {
                Symbol            genericSort      = TypeSort(t.GetGenericTypeDefinition());
                Sequence <Symbol> domainParameters = Sequence <Symbol> .EmptySequence;
                foreach (Type typeArg in t.GetGenericArguments())
                {
                    domainParameters = domainParameters.AddLast(TypeSort(typeArg));
                }

                sort = new Symbol(genericSort.Name, domainParameters);
            }

            // Case 3: Build new sort by looking up "sort" attribute.
            //         This is either a nongeneric type or a generic type definition (uninstantiated)
            else
            {
                string sortAttrName = GetSortAttributeString(t);
                if (!String.IsNullOrEmpty(sortAttrName))
                {
                    // use name given by "Sort" attribute
                    sortName = sortAttrName;
                }
                else
                {
                    // else use name of type (taking care to remove extra markings for generics)
                    StringBuilder sb = new StringBuilder();
                    PrettyPrinter.FormatTypeName(sb, t);
                    sortName = sb.ToString();
                }

                // if generic type definition, tag symbol with empty "<>"
                if (t.IsGenericType && t.IsGenericTypeDefinition)
                {
                    sort = new Symbol(sortName, Sequence <Symbol> .EmptySequence);
                }
                else
                {
                    sort = new Symbol(sortName);
                }
            }
            typeSorts[t] = sort;
            return(sort);
        }
示例#7
0
        /// <summary>
        /// Utility function to create an compound term from a string <paramref name="name"/>
        /// and arguments. The arguments will be converted to term representations.
        /// An argument that is alredy a term is not coverted but left as is.
        /// </summary>
        /// <param name="name">The name of the function symbol.</param>
        /// <param name="args">The .NET values to be converted to terms.</param>
        /// <returns>The created compound term</returns>
        static public CompoundTerm Create(string name, params IComparable[] args)
        {
            Sequence <Term> termArgs = Sequence <Term> .EmptySequence;

            foreach (IComparable arg in args)
            {
                Term t = arg as Term;
                if (t == null)
                {
                    termArgs = termArgs.AddLast(NModel.Internals.AbstractValue.GetTerm(arg));
                }
                else
                {
                    termArgs = termArgs.AddLast(t);
                }
            }

            return(new CompoundTerm(new Symbol(name), termArgs));
        }
示例#8
0
        private Sequence <Term> SubstituteInSubterms(Sequence <Term> sequence, Map <Variable, Term> substitution)
        {
            Sequence <Term> result = Sequence <Term> .EmptySequence;

            foreach (Term subterm in sequence)
            {
                result = result.AddLast(subterm.Substitute(substitution));
            }
            return(result);
        }
示例#9
0
        private void btn_AddLast_Click(object sender, RoutedEventArgs e)
        {
            // validar datos
            string item = tB_ItemToAdd.Text;

            if (string.IsNullOrEmpty(item))
            {
                return;
            }
            list.AddLast(item);
            CUtilities.FillListView(lV_Items, list);
        }
示例#10
0
            Symbol ParseSymbol()
            {
                if (nextToken.kind != Token.Kind.Symbol)
                {
                    throw new SyntaxErrorException("saw " + nextToken.kind.ToString() + " where " +
                                                   Token.Kind.Symbol.ToString() + " was expected");
                }
                string symbolName = nextToken.value;

                Next();

                if (nextToken.kind == Token.Kind.LBracket)
                {
                    Next();
                    bool expectComma = false;

                    Sequence <Symbol> domainParameters = Sequence <Symbol> .EmptySequence;
                    while (nextToken.kind != Token.Kind.RBracket)
                    {
                        if (expectComma)
                        {
                            Expect(Token.Kind.Comma);
                        }
                        Symbol domainParameter = ParseSymbol();
                        domainParameters = domainParameters.AddLast(domainParameter);
                        expectComma      = true;
                    }

                    //if (domainParameters.Count == 0)
                    //  throw new SyntaxErrorException("found empty list of domain parameters ");

                    Expect(Token.Kind.RBracket);
                    Symbol[] symArray = new Symbol[domainParameters.Count];
                    domainParameters.CopyTo(symArray, 0);
                    return(new Symbol(symbolName, symArray));
                }
                else
                {
                    return(new Symbol(symbolName));
                }
            }
示例#11
0
        /// <summary>
        /// Run a single test case.
        /// Returns the result of the test case, containing the action trace
        /// </summary>
        /// <param name="testNr">test case number</param>
        /// <returns>test result</returns>
        internal TestResult RunTestCase(int testNr)
        {
            Sequence <Action> testCase = Sequence <Action> .EmptySequence;
            Action /*?*/      o        = null;

            // Requirements metrics
            Bag <Pair <string, string> > executedRequirements = Bag <Pair <string, string> > .EmptyBag;

            while ((this.stepsCnt <= 0) || testCase.Count < stepsCnt || (!model.IsInAcceptingState && (maxStepsCnt <= 0 || testCase.Count < maxStepsCnt)))
            {
                if (o != null || (IsAsync && !observations.IsEmpty))
                {
                    #region there is an implementation action o to be checked
                    if (o == null)
                    {
                        o = observations.Dequeue();
                    }

                    testCase = testCase.AddLast(o);  //record the action in the testCase

                    string failureReason = "";
                    if (model.IsActionEnabled(o, out failureReason)) //check conformance to the model
                    {
                        model.DoAction(o);
                        o = null;                    //consume the action
                    }
                    else
                    {
                        return(new TestResult(testNr, Verdict.Failure, failureReason, testCase, executedRequirements)); // Requirements metrics: ", executedRequirements"
                    }
                    #endregion
                }
                else
                {
                    //use only cleanup actions when in cleanup phase
                    Set <Symbol> actionSymbols = (((stepsCnt <= 0) || testCase.Count < stepsCnt) ? this.testerActionSymbols : this.cleanupActionSymbols);

                    //select a tester action that is enabled in the current model state
                    Action testerAction = model.SelectAction(actionSymbols);

                    //if a tester action could be chosen
                    if (testerAction != null)
                    {
                        #region execute the tester action

                        //get the timespan within which calling impl with testerAction must return
                        TimeSpan t = (!internalActionSymbols.Contains(testerAction.Symbol) ?
                                      this.testerActionTimeout(model.CurrentState, testerAction) : new TimeSpan());

                        //do the action in the model
                        model.DoAction(testerAction);

                        // Requirements metrics

                        string actionName = testerAction.Name;
                        foreach (string methodName in LibraryModelProgram.AllModeledRequirements.Keys)
                        {
                            // The methods names don't contain "_Start"
                            // when testerAction.Name == actionName_Start, remove the "_Start"
                            // in order to check it in AllModeledRequirements.Keys
                            if (actionName.Contains("_Start"))
                            {
                                actionName = actionName.Replace("_Start", "");
                            }
                            // I use 'Contains' to get all the enabled actions as well
                            if (methodName.Contains(actionName))
                            {
                                foreach (Pair <string, string> req in LibraryModelProgram.AllModeledRequirements[methodName])
                                {
                                    executedRequirements = executedRequirements.Add(req);
                                }
                            }
                        }

                        //record the action in the testCase
                        testCase = testCase.AddLast(testerAction);

                        //call the implementation if the symbol is shared
                        if (!internalActionSymbols.Contains(testerAction.Symbol))
                        {
                            try
                            {
                                DateTime startAction = DateTime.Now; // Performance metrics

                                o = DoAction(testerAction, t);       //if return value is non-null it will be checked next time around

                                // Requirements metrics
                                CalcPerformance(testerAction, startAction);
                            }
                            catch (ConformanceTesterException e)
                            {
                                return(new TestResult(testNr, Verdict.Failure, e.Message, testCase, executedRequirements));  //conformance failure // Requirements : ", executedRequirements"
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        //otherwise, try to get an implementation action
                        if (IsAsync)
                        {
                            //get the Wait action from the model
                            Action w          = model.SelectAction(waitActionSet);
                            int    obsTimeout = (w == null ? 0 : (int)w[0]);
                            if (w != null)
                            {
                                testCase = testCase.AddLast(w);
                                model.DoAction(w);
                            }
                            if (!observations.TryDequeue(new TimeSpan(0, 0, 0, 0, obsTimeout), out o))
                            {
                                //if there are no tester actions and no observables but the
                                //model is in accepting state, the test succeeds
                                if (model.IsInAcceptingState)
                                {
                                    return(new TestResult(testNr, Verdict.Success, "", testCase, executedRequirements));// Requirements metrics: ", executedRequirements"
                                }
                                else
                                {
                                    o = timeoutAction;
                                }
                            }
                        }
                        else
                        {
                            //if there are no tester actions and no observables but the
                            //model is in accepting state, the test succeeds
                            if (model.IsInAcceptingState)
                            {
                                return(new TestResult(testNr, Verdict.Success, "", testCase, executedRequirements));// Requirements metrics: ", executedRequirements"
                            }
                            else
                            {
                                return(new TestResult(testNr, Verdict.Failure, "Run stopped in a non-accepting state", testCase, executedRequirements));// Requirements metrics: ", executedRequirements"
                            }
                        }
                    }
                }
            }
            if (model.IsInAcceptingState)
            {
                return(new TestResult(testNr, Verdict.Success, "", testCase, executedRequirements));// Requirements metrics: ", executedRequirements"
            }
            else
            {
                return(new TestResult(testNr, Verdict.Failure, "Test run did not finish in accepting state", testCase, executedRequirements));// Requirements metrics: ", executedRequirements"
            }
        }
示例#12
0
        public static void RunWithCommandLineArguments(string[] args)
        {
            //System.Diagnostics.Debugger.Break();
            ConformanceTester confTester = null;

            try
            {
                ConfTesterCommandLineSettings settings = new ConfTesterCommandLineSettings();
                if (!Parser.ParseArgumentsWithUsage(args, settings))
                {
                    //Console.ReadLine();
                    return;
                }

                #region load the libraries
                List <Assembly> libs = new List <Assembly>();
                try
                {
                    if (settings.reference != null)
                    {
                        foreach (string l in settings.reference)
                        {
                            libs.Add(System.Reflection.Assembly.LoadFrom(l));
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new ModelProgramUserException(e.Message);
                }
                #endregion

                #region create the implementation stepper using the factory method
                string implStepperMethodName;
                string implStepperClassName;
                ReflectionHelper.SplitFullMethodName(settings.iut, out implStepperClassName, out implStepperMethodName);
                Type       implStepperType   = ReflectionHelper.FindType(libs, implStepperClassName);
                MethodInfo implStepperMethod = ReflectionHelper.FindMethod(implStepperType, implStepperMethodName, Type.EmptyTypes, typeof(IStepper));
                IStepper   implStepper       = null;
                try
                {
                    implStepper = (IStepper)implStepperMethod.Invoke(null, null);
                }
                catch (Exception e)
                {
                    throw new ModelProgramUserException("Invocation of '" + settings.iut + "' failed: " + e.ToString());
                }
                #endregion

                #region create a model program for each model using the factory method and compose into product
                string       mpMethodName;
                string       mpClassName;
                ModelProgram mp = null;
                if (settings.model != null && settings.model.Length > 0)
                {
                    ReflectionHelper.SplitFullMethodName(settings.model[0], out mpClassName, out mpMethodName);
                    Type       mpType   = ReflectionHelper.FindType(libs, mpClassName);
                    MethodInfo mpMethod = ReflectionHelper.FindMethod(mpType, mpMethodName, Type.EmptyTypes, typeof(ModelProgram));
                    try
                    {
                        mp = (ModelProgram)mpMethod.Invoke(null, null);
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Invocation of '" + settings.model[0] + "' failed: " + e.ToString());
                    }
                    for (int i = 1; i < settings.model.Length; i++)
                    {
                        ReflectionHelper.SplitFullMethodName(settings.model[i], out mpClassName, out mpMethodName);
                        mpType   = ReflectionHelper.FindType(libs, mpClassName);
                        mpMethod = ReflectionHelper.FindMethod(mpType, mpMethodName, Type.EmptyTypes, typeof(ModelProgram));
                        ModelProgram mp2 = null;
                        try
                        {
                            mp2 = (ModelProgram)mpMethod.Invoke(null, null);
                        }
                        catch (Exception e)
                        {
                            throw new ModelProgramUserException("Invocation of '" + settings.model[i] + "' failed: " + e.ToString());
                        }
                        mp = new ProductModelProgram(mp, mp2);
                    }
                }
                #endregion

                #region load the test cases if any
                Sequence <Sequence <CompoundTerm> > testcases = Sequence <Sequence <CompoundTerm> > .EmptySequence;
                if (!String.IsNullOrEmpty(settings.testSuite))
                {
                    try
                    {
                        System.IO.StreamReader testSuiteReader =
                            new System.IO.StreamReader(settings.testSuite);
                        string testSuiteAsString = testSuiteReader.ReadToEnd();
                        testSuiteReader.Close();
                        CompoundTerm testSuite = (CompoundTerm)Term.Parse(testSuiteAsString);
                        foreach (CompoundTerm testCaseTerm in testSuite.Arguments)
                        {
                            Sequence <CompoundTerm> testCase =
                                testCaseTerm.Arguments.Convert <CompoundTerm>(delegate(Term t) { return((CompoundTerm)t); });
                            testcases = testcases.AddLast(testCase);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Cannot create test suite: " + e.Message);
                    }
                }
                #endregion

                #region load the fsms if any
                Dictionary <string, FSM> fsms = new Dictionary <string, FSM>();
                if (settings.fsm != null && settings.fsm.Length > 0)
                {
                    try
                    {
                        foreach (string fsmFile in settings.fsm)
                        {
                            System.IO.StreamReader fsmReader = new System.IO.StreamReader(fsmFile);
                            string fsmAsString = fsmReader.ReadToEnd();
                            fsmReader.Close();
                            fsms[fsmFile] = FSM.FromTerm(CompoundTerm.Parse(fsmAsString));
                        }
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Cannot create fsm: " + e.Message);
                    }
                }
                #endregion

                if (mp == null && testcases.IsEmpty && fsms.Count == 0)
                {
                    throw new ModelProgramUserException("No model, fsm, or test suite was given.");
                }

                if (fsms.Count > 0)
                {
                    foreach (string fsmName in fsms.Keys)
                    {
                        ModelProgram fsmmp = new FsmModelProgram(fsms[fsmName], fsmName);
                        if (mp == null)
                        {
                            mp = fsmmp;
                        }
                        else
                        {
                            mp = new ProductModelProgram(mp, fsmmp);
                        }
                    }
                }

                #region create the model stepper
                IStrategy ms;

                if (!testcases.IsEmpty)
                {
                    ms = new TestSuiteStepper(settings.startTestAction, testcases, mp);
                }
                else
                {
                    ms = CreateModelStepper(libs, mp, settings.modelStepper, settings.coverage);
                }

                #endregion

                confTester = new ConformanceTester(ms, implStepper);

                #region configure conformance tester settings

                confTester.ContinueOnFailure = settings.continueOnFailure;
                confTester.StepsCnt          = (testcases.IsEmpty ? settings.steps : 0);
                confTester.MaxStepsCnt       = (testcases.IsEmpty ? settings.maxSteps : 0);
                confTester.RunsCnt           = (testcases.IsEmpty ? settings.runs : testcases.Count);
                confTester.WaitAction        = settings.waitAction;
                confTester.TimeoutAction     = settings.timeoutAction;

                Symbol waitActionSymbol    = confTester.waitActionSet.Choose();
                Symbol timeoutActionSymbol = confTester.timeoutAction.FunctionSymbol1;

                Set <Symbol> obs = new Set <string>(settings.observableAction).Convert <Symbol>(delegate(string s) { return(Symbol.Parse(s)); });
                confTester.ObservableActionSymbols = obs;

                Set <Symbol> cleanup = new Set <string>(settings.cleanupAction).Convert <Symbol>(delegate(string s) { return(Symbol.Parse(s)); });
                confTester.CleanupActionSymbols = cleanup;

                if (confTester.IsAsync)
                {
                    //remove the wait and timeout action symbol from tester action symbols
                    if (confTester.testerActionSymbols.Contains(waitActionSymbol) ||
                        confTester.testerActionSymbols.Contains(timeoutActionSymbol))
                    {
                        confTester.testerActionSymbols =
                            confTester.testerActionSymbols.Remove(waitActionSymbol).Remove(timeoutActionSymbol);
                    }
                }

                Set <Symbol> internals = new Set <string>(settings.internalAction).Convert <Symbol>(delegate(string s) { return(Symbol.Parse(s)); });

                confTester.InternalActionSymbols =
                    (testcases.IsEmpty || settings.startTestAction != "Test" ?
                     internals :
                     internals.Add(Symbol.Parse("Test")));

                TimeSpan timeout = new TimeSpan(0, 0, 0, 0, settings.timeout);
                confTester.TesterActionTimeout = delegate(IState s, CompoundTerm a) { return(timeout); };
                confTester.Logfile             = settings.logfile;
                confTester.OverwriteLog        = settings.overwriteLog;
                if (settings.randomSeed != 0)
                {
                    confTester.RandomSeed = settings.randomSeed;
                }
                #endregion

                //finally, run the application
                confTester.Run();
            }
            catch (ModelProgramUserException)
            {
                throw;
            }
            catch (ConformanceTesterException e)
            {
                throw new ModelProgramUserException(e.Message);
            }
            finally
            {
                if (confTester != null)
                {
                    confTester.Dispose();
                }
            }
        }
示例#13
0
        public static void RunWithCommandLineArguments(string[] args)
        {
            //System.Diagnostics.Debugger.Break();
            ConformanceTester confTester = null;

            try
            {
                ConfTesterCommandLineSettings settings = new ConfTesterCommandLineSettings();
                if (!Parser.ParseArgumentsWithUsage(args, settings))
                {
                    //Console.ReadLine();
                    return;
                }

                #region load the libraries
                List <Assembly> libs = new List <Assembly>();
                try
                {
                    if (settings.reference != null)
                    {
                        foreach (string l in settings.reference)
                        {
                            libs.Add(System.Reflection.Assembly.LoadFrom(l));
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new ModelProgramUserException(e.Message);
                }
                #endregion

                #region create the implementation stepper using the factory method
                string implStepperMethodName;
                string implStepperClassName;
                ReflectionHelper.SplitFullMethodName(settings.iut, out implStepperClassName, out implStepperMethodName);
                Type       implStepperType   = ReflectionHelper.FindType(libs, implStepperClassName);
                MethodInfo implStepperMethod = ReflectionHelper.FindMethod(implStepperType, implStepperMethodName, Type.EmptyTypes, typeof(IStepper));
                IStepper   implStepper       = null;
                try
                {
                    implStepper = (IStepper)implStepperMethod.Invoke(null, null);
                }
                catch (Exception e)
                {
                    throw new ModelProgramUserException("Invocation of '" + settings.iut + "' failed: " + e.ToString());
                }
                #endregion

                #region create a model program for each model using the factory method and compose into product
                string       mpMethodName;
                string       mpClassName;
                ModelProgram mp = null;
                if (settings.model != null && settings.model.Length > 0)
                {
                    ReflectionHelper.SplitFullMethodName(settings.model[0], out mpClassName, out mpMethodName);
                    Type       mpType   = ReflectionHelper.FindType(libs, mpClassName);
                    MethodInfo mpMethod = ReflectionHelper.FindMethod(mpType, mpMethodName, Type.EmptyTypes, typeof(ModelProgram));
                    try
                    {
                        mp = (ModelProgram)mpMethod.Invoke(null, null);
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Invocation of '" + settings.model[0] + "' failed: " + e.ToString());
                    }
                    for (int i = 1; i < settings.model.Length; i++)
                    {
                        ReflectionHelper.SplitFullMethodName(settings.model[i], out mpClassName, out mpMethodName);
                        mpType   = ReflectionHelper.FindType(libs, mpClassName);
                        mpMethod = ReflectionHelper.FindMethod(mpType, mpMethodName, Type.EmptyTypes, typeof(ModelProgram));
                        ModelProgram mp2 = null;
                        try
                        {
                            mp2 = (ModelProgram)mpMethod.Invoke(null, null);
                        }
                        catch (Exception e)
                        {
                            throw new ModelProgramUserException("Invocation of '" + settings.model[i] + "' failed: " + e.ToString());
                        }
                        mp = new ProductModelProgram(mp, mp2);
                    }
                }
                #endregion

                #region create a model program from given namespace and feature names
                if (settings.mp != null && settings.mp.Length > 0)
                {
                    if (libs.Count == 0)
                    {
                        throw new ModelProgramUserException("No reference was provided to load models from.");
                    }
                    //parse the model program name and the feature names for each entry
                    foreach (string mps in settings.mp)
                    {
                        //the first element is the model program, the remaining ones are
                        //feature names
                        string[] mpsSplit = mps.Split(new string[] { "[", "]", "," },
                                                      StringSplitOptions.RemoveEmptyEntries);
                        if (mpsSplit.Length == 0)
                        {
                            throw new ModelProgramUserException("Invalid model program specifier '" + mps + "'.");
                        }
                        string       mpName     = mpsSplit[0];
                        Assembly     mpAssembly = ReflectionHelper.FindAssembly(libs, mpName);
                        Set <string> mpFeatures = new Set <string>(mpsSplit).Remove(mpName);
                        ModelProgram mp1        = new LibraryModelProgram(mpAssembly, mpName, mpFeatures);
                        mp = (mp == null ? mp1 : new ProductModelProgram(mp, mp1));
                    }
                }

                #endregion

                #region load the test cases if any
                Sequence <Sequence <CompoundTerm> > testcases = Sequence <Sequence <CompoundTerm> > .EmptySequence;
                if (!String.IsNullOrEmpty(settings.testSuite))
                {
                    try
                    {
                        System.IO.StreamReader testSuiteReader =
                            new System.IO.StreamReader(settings.testSuite);
                        string testSuiteAsString = testSuiteReader.ReadToEnd();
                        testSuiteReader.Close();
                        CompoundTerm testSuite = (CompoundTerm)Term.Parse(testSuiteAsString);
                        foreach (CompoundTerm testCaseTerm in testSuite.Arguments)
                        {
                            Sequence <CompoundTerm> testCase =
                                testCaseTerm.Arguments.Convert <CompoundTerm>(delegate(Term t) { return((CompoundTerm)t); });
                            testcases = testcases.AddLast(testCase);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Cannot create test suite: " + e.Message);
                    }
                }
                #endregion

                #region load the fsms if any
                Dictionary <string, FSM> fsms = new Dictionary <string, FSM>();
                if (settings.fsm != null && settings.fsm.Length > 0)
                {
                    try
                    {
                        foreach (string fsmFile in settings.fsm)
                        {
                            System.IO.StreamReader fsmReader = new System.IO.StreamReader(fsmFile);
                            string fsmAsString = fsmReader.ReadToEnd();
                            fsmReader.Close();
                            fsms[fsmFile] = FSM.FromTerm(CompoundTerm.Parse(fsmAsString));
                        }
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Cannot create fsm: " + e.Message);
                    }
                }
                #endregion


                // Requirements metrics

                #region load all the requirements from an external file - if any
                if (!String.IsNullOrEmpty(settings.RequirementsFile))
                {
                    try
                    {
                        System.IO.StreamReader reqsReader =
                            new System.IO.StreamReader(settings.RequirementsFile);
                        string   line;
                        char[]   splitchars = { '|' };
                        string[] splitedLine;
                        while ((line = reqsReader.ReadLine()) != null)
                        {
                            if (line.Length > 5)
                            {
                                splitedLine = line.Split(splitchars);
                                // The format of a requirement line is:
                                // action (ignore by the parser) | id | description
                                AllRequirements.Add(new KeyValuePair <string, string>(splitedLine[1].Trim().ToLower(), splitedLine[2].Trim().ToLower()));
                            }
                        }
                        reqsReader.Close();
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Cannot create all-requirements list: " + e.Message);
                    }
                }
                #endregion


                if (mp == null && testcases.IsEmpty && fsms.Count == 0)
                {
                    throw new ModelProgramUserException("No model, fsm, or test suite was given.");
                }

                if (fsms.Count > 0)
                {
                    foreach (string fsmName in fsms.Keys)
                    {
                        ModelProgram fsmmp = new FsmModelProgram(fsms[fsmName], fsmName);
                        if (mp == null)
                        {
                            mp = fsmmp;
                        }
                        else
                        {
                            mp = new ProductModelProgram(mp, fsmmp);
                        }
                    }
                }

                #region create the model stepper
                IStrategy    ms;
                Set <Symbol> obs = new Set <string>(settings.observableAction).Convert <Symbol>(delegate(string s) { return(Symbol.Parse(s)); });
                if (!testcases.IsEmpty)
                {
                    ms = new TestSuiteStepper(settings.startTestAction, testcases, mp);
                }
                else
                {
                    ms = CreateModelStepper(libs, mp, settings.modelStepper, settings.coverage, obs);
                }

                #endregion

                confTester = new ConformanceTester(ms, implStepper);

                #region configure conformance tester settings

                confTester.ContinueOnFailure = settings.continueOnFailure;
                confTester.StepsCnt          = (testcases.IsEmpty ? settings.steps : 0);
                confTester.MaxStepsCnt       = (testcases.IsEmpty ? settings.maxSteps : 0);
                confTester.RunsCnt           = (testcases.IsEmpty ? settings.runs : testcases.Count);
                confTester.WaitAction        = settings.waitAction;
                confTester.TimeoutAction     = settings.timeoutAction;
                confTester.ShowTestCaseCoveredRequirements = settings.showTestCaseCoveredRequirements;
                confTester.showMetrics = settings.showMetrics;

                Symbol waitActionSymbol    = confTester.waitActionSet.Choose();
                Symbol timeoutActionSymbol = confTester.timeoutAction.Symbol;


                confTester.ObservableActionSymbols = obs;

                Set <Symbol> cleanup = new Set <string>(settings.cleanupAction).Convert <Symbol>(delegate(string s) { return(Symbol.Parse(s)); });
                confTester.CleanupActionSymbols = cleanup;

                if (confTester.IsAsync)
                {
                    //remove the wait and timeout action symbol from tester action symbols
                    if (confTester.testerActionSymbols.Contains(waitActionSymbol) ||
                        confTester.testerActionSymbols.Contains(timeoutActionSymbol))
                    {
                        confTester.testerActionSymbols =
                            confTester.testerActionSymbols.Remove(waitActionSymbol).Remove(timeoutActionSymbol);
                    }
                }

                Set <Symbol> internals = new Set <string>(settings.internalAction).Convert <Symbol>(delegate(string s) { return(Symbol.Parse(s)); });

                confTester.InternalActionSymbols =
                    (testcases.IsEmpty || settings.startTestAction != "Test" ?
                     internals :
                     internals.Add(Symbol.Parse("Test")));

                TimeSpan timeout = new TimeSpan(0, 0, 0, 0, settings.timeout);
                confTester.TesterActionTimeout = delegate(IState s, CompoundTerm a) { return(timeout); };
                confTester.Logfile             = settings.logfile;
                confTester.OverwriteLog        = settings.overwriteLog;
                if (settings.randomSeed != 0)
                {
                    confTester.RandomSeed = settings.randomSeed;
                }
                #endregion

                //finally, run the application
                confTester.Run();
            }
            catch (ModelProgramUserException)
            {
                throw;
            }
            catch (ConformanceTesterException e)
            {
                throw new ModelProgramUserException(e.Message);
            }
            finally
            {
                if (confTester != null)
                {
                    confTester.Dispose();
                }
            }
        }
示例#14
0
        /// <summary>
        /// Provides programmatic access to the ModelProgramViewer commandline utility 'mpv.exe'.
        /// </summary>
        /// <param name="args">command line arguments: model program(s), optional settings for the viewer</param>
        /// <remarks>The settings are displayed when 'mpv.exe /?' is executed from the command line without arguments.</remarks>
        public static void RunWithCommandLineArguments(params string[] args)
        {
            ProgramSettings settings = new ProgramSettings();

            if (!Parser.ParseArgumentsWithUsage(args, settings))
            {
                return;
            }

            #region load the libraries
            List <Assembly> libs = new List <Assembly>();
            try
            {
                if (settings.reference != null)
                {
                    foreach (string l in settings.reference)
                    {
                        libs.Add(System.Reflection.Assembly.LoadFrom(l));
                    }
                }
            }
            catch (Exception e)
            {
                throw new ModelProgramUserException(e.Message);
            }
            #endregion

            #region create a model program for each model using the factory method and compose into product
            string       mpMethodName;
            string       mpClassName;
            ModelProgram mp = null;
            if (settings.model != null && settings.model.Length > 0)
            {
                if (libs.Count == 0)
                {
                    throw new ModelProgramUserException("No reference was provided to load models from.");
                }
                ReflectionHelper.SplitFullMethodName(settings.model[0], out mpClassName, out mpMethodName);
                Type       mpType   = ReflectionHelper.FindType(libs, mpClassName);
                MethodInfo mpMethod = ReflectionHelper.FindMethod(mpType, mpMethodName, Type.EmptyTypes, typeof(ModelProgram));
                try
                {
                    mp = (ModelProgram)mpMethod.Invoke(null, null);
                }
                catch (Exception e)
                {
                    throw new ModelProgramUserException("Invocation of '" + settings.model[0] + "' failed: " + e.ToString());
                }
                for (int i = 1; i < settings.model.Length; i++)
                {
                    ReflectionHelper.SplitFullMethodName(settings.model[i], out mpClassName, out mpMethodName);
                    mpType   = ReflectionHelper.FindType(libs, mpClassName);
                    mpMethod = ReflectionHelper.FindMethod(mpType, mpMethodName, Type.EmptyTypes, typeof(ModelProgram));
                    ModelProgram mp2 = null;
                    try
                    {
                        mp2 = (ModelProgram)mpMethod.Invoke(null, null);
                    }
                    catch (Exception e)
                    {
                        throw new ModelProgramUserException("Invocation of '" + settings.model[i] + "' failed: " + e.ToString());
                    }
                    mp = new ProductModelProgram(mp, mp2);
                }
            }
            #endregion

            #region create a model program from given namespace and feature names
            if (settings.mp != null && settings.mp.Length > 0)
            {
                if (libs.Count == 0)
                {
                    throw new ModelProgramUserException("No reference was provided to load models from.");
                }
                //parse the model program name and the feature names for each entry
                foreach (string mps in settings.mp)
                {
                    //the first element is the model program, the remaining ones are
                    //feature names
                    string[] mpsSplit = mps.Split(new string[] { "[", "]", "," },
                                                  StringSplitOptions.RemoveEmptyEntries);
                    if (mpsSplit.Length == 0)
                    {
                        throw new ModelProgramUserException("Invalid model program specifier '" + mps + "'.");
                    }
                    string       mpName     = mpsSplit[0];
                    Assembly     mpAssembly = ReflectionHelper.FindAssembly(libs, mpName);
                    Set <string> mpFeatures = new Set <string>(mpsSplit).Remove(mpName);
                    ModelProgram mp1        = new LibraryModelProgram(mpAssembly, mpName, mpFeatures);
                    mp = (mp == null ? mp1 : new ProductModelProgram(mp, mp1));
                }
            }

            #endregion

            #region load the test cases if any
            Sequence <Sequence <CompoundTerm> > testcases = Sequence <Sequence <CompoundTerm> > .EmptySequence;
            if (!String.IsNullOrEmpty(settings.testSuite))
            {
                try
                {
                    System.IO.StreamReader testSuiteReader =
                        new System.IO.StreamReader(settings.testSuite);
                    string testSuiteAsString = testSuiteReader.ReadToEnd();
                    testSuiteReader.Close();
                    CompoundTerm testSuite = CompoundTerm.Parse(testSuiteAsString);
                    foreach (CompoundTerm testCaseTerm in testSuite.Arguments)
                    {
                        Sequence <CompoundTerm> testCase =
                            testCaseTerm.Arguments.Convert <CompoundTerm>(delegate(Term t) { return((CompoundTerm)t); });
                        testcases = testcases.AddLast(testCase);
                    }
                }
                catch (Exception e)
                {
                    throw new ModelProgramUserException("Cannot create test suite: " + e.Message);
                }
            }
            #endregion

            #region load the fsms if any
            Dictionary <string, FSM> fsms = new Dictionary <string, FSM>();
            if (settings.fsm != null && settings.fsm.Length > 0)
            {
                try
                {
                    foreach (string fsmFile in settings.fsm)
                    {
                        System.IO.StreamReader fsmReader = new System.IO.StreamReader(fsmFile);
                        string fsmAsString = fsmReader.ReadToEnd();
                        fsmReader.Close();
                        fsms[fsmFile] = FSM.FromTerm(CompoundTerm.Parse(fsmAsString));
                    }
                }
                catch (Exception e)
                {
                    throw new ModelProgramUserException("Cannot create fsm: " + e.Message);
                }
            }
            #endregion

            if (mp == null && testcases.IsEmpty && fsms.Count == 0)
            {
                throw new ModelProgramUserException("No model, fsm, or test suite was given.");
            }

            if (!testcases.IsEmpty)
            {
                FSM fa = FsmTraversals.GenerateTestSequenceAutomaton(
                    settings.startTestAction, testcases, GetActionSymbols(testcases));
                ModelProgram famp = new FsmModelProgram(fa, settings.testSuite);
                if (mp == null)
                {
                    mp = famp;
                }
                else
                {
                    mp = new ProductModelProgram(mp, famp);
                }
            }

            if (fsms.Count > 0)
            {
                foreach (string fsmName in fsms.Keys)
                {
                    ModelProgram fsmmp = new FsmModelProgram(fsms[fsmName], fsmName);
                    if (mp == null)
                    {
                        mp = fsmmp;
                    }
                    else
                    {
                        mp = new ProductModelProgram(mp, fsmmp);
                    }
                }
            }

            ModelProgramGraphViewForm form = new ModelProgramGraphViewForm("Model Program Viewer");
            //configure the settings of the viewer
            form.View.AcceptingStatesMarked   = settings.acceptingStatesMarked;
            form.View.TransitionLabels        = settings.transitionLabels;
            form.View.CombineActions          = settings.combineActions;
            form.View.Direction               = settings.direction;
            form.View.UnsafeStateColor        = Color.FromName(settings.unsafeStateColor);
            form.View.HoverColor              = Color.FromName(settings.hoverColor);
            form.View.InitialStateColor       = Color.FromName(settings.initialStateColor);
            form.View.LoopsVisible            = settings.loopsVisible;
            form.View.MaxTransitions          = settings.maxTransitions;
            form.View.NodeLabelsVisible       = settings.nodeLabelsVisible;
            form.View.SelectionColor          = Color.FromName(settings.selectionColor);
            form.View.MergeLabels             = settings.mergeLabels;
            form.View.StateShape              = settings.stateShape;
            form.View.DeadStateColor          = Color.FromName(settings.deadStateColor);
            form.View.InitialTransitions      = settings.initialTransitions;
            form.View.LivenessCheckIsOn       = settings.livenessCheckIsOn;
            form.View.ExcludeIsomorphicStates = settings.excludeIsomorphicStates;
            form.View.SafetyCheckIsOn         = settings.safetyCheckIsOn;
            form.View.DeadstatesVisible       = settings.deadStatesVisible;
            form.View.StateViewVisible        = settings.stateViewVisible;

            //show the view of the product of all the model programs
            form.View.SetModelProgram(mp);

            form.OnSaveSettings += new EventHandler(settings.SaveSettings);
            form.ShowDialog();
        }
示例#15
0
 //do postorder traversal
 private Sequence<ReductName> GetSubFANames(Sequence<FSMBuilder.Branch> treePosition, ModelProgram mp1)
 {
     ProductModelProgram pmp = mp1 as ProductModelProgram;
     if (pmp != null)
     {
         Sequence<ReductName> leftChildren =
             GetSubFANames(treePosition.AddLast(FSMBuilder.Branch.Left),
                           pmp.M1);
         Sequence<ReductName> rightChildren =
             GetSubFANames(treePosition.AddLast(FSMBuilder.Branch.Right),
                           pmp.M2);
         ReductName name = new ReductName(treePosition,
             new FAName(leftChildren.Last.name,rightChildren.Last.name));
         return leftChildren.Concatentate(rightChildren).AddLast(name);
     }
     else
     {
         return new Sequence<ReductName>(new ReductName(treePosition, GetModelName(mp1)));
     }
 }
示例#16
0
        /// <summary>
        /// Gets all enabled actions in the given state that have the given action symbol
        /// </summary>
        /// <param name="state"></param>
        /// <param name="actionSymbol"></param>
        /// <returns></returns>
        public override IEnumerable <CompoundTerm> GetActions(IState state, Symbol actionSymbol)
        {
            PairState ps = state as PairState;

            if (ps == null)
            {
                throw new ArgumentException("Unexpected type-- expected PairState");
            }

            if (actionSymbol == null)
            {
                throw new ArgumentNullException("actionSymbol");
            }


            if (this.signature.IsOnlyInM1(actionSymbol))
            {
                IState M1State = M1Reduct(ps);
                foreach (CompoundTerm a in m1.GetActions(M1State, actionSymbol))
                {
                    yield return(a);
                }
            }
            else if (this.signature.IsOnlyInM2(actionSymbol))
            {
                IState M2State = M2Reduct(ps);
                foreach (CompoundTerm a in m2.GetActions(M2State, actionSymbol))
                {
                    yield return(a);
                }
            }
            else if (this.signature.IsShared(actionSymbol))
            {
                IState m1State = M1Reduct(ps);
                IState m2State = M2Reduct(ps);
                int    arity   = this.ActionArity(actionSymbol);
                if (arity > 0)
                {
                    Sequence <Set <Term> > args = Sequence <Set <Term> > .EmptySequence;
                    for (int i = 0; i < arity; i++)
                    {
                        args = args.AddLast(this.ActionParameterDomain(state, actionSymbol, i));
                    }

                    IEnumerable <Sequence <Term> > cartesianProduct = CartesianProduct(args);

                    foreach (Sequence <Term> arglist in cartesianProduct)
                    {
                        CompoundTerm action = new CompoundTerm(actionSymbol, arglist);
                        if (m1.IsEnabled(m1State, action) && m2.IsEnabled(m2State, action))
                        {
                            yield return(action);
                        }
                    }
                }
                else
                {
                    CompoundTerm action = new CompoundTerm(actionSymbol, Sequence <Term> .EmptySequence);
                    if (m1.IsEnabled(m1State, action) && m2.IsEnabled(m2State, action))
                    {
                        yield return(action);
                    }
                }
            }
            else
            {
                throw new ArgumentException("Invalid argument-- action symbol " + actionSymbol.ToString() + " not in signature.");
            }
        }
示例#17
0
        private CompoundTerm ChooseAction(Sequence <Action> actions, IState iState)
        {
            TransitionProperties tp;
            int               targetId    = -1;
            List <double>     MaxV        = bdt.ReturnValue(true);
            List <double>     MinV        = bdt.ReturnValue(false);
            List <Set <int> > abstractMap = bdt.ReturnLeaves();
            Sequence <Pair <int, Action> > cumulActSum = Sequence <Pair <int, Action> > .EmptySequence;
            double epsilon = 0.1;
            Dictionary <int, int> sumTarget = new Dictionary <int, int>();
            Action maxAct      = null;
            int    targetAbsId = -1;
            int    sum         = 0;

            UpdateRequirementMaps(actions, iState);
            Set <Action> newStateActs = new Set <Action>();
            Set <Action> oldActs      = new Set <Action>(actions.Head);

            foreach (Action a in actions)
            {
                int tState = this.modelProgram.GetTargetState(iState, a, null, out tp).GetHashCode();
                targetAbsId = findAbstractId(tState, abstractMap);
                if (targetAbsId == -1)
                {
                    newStateActs = newStateActs.Add(a);
                }
                else
                {
                    sum = sum + (int)(MaxV[targetAbsId] * Math.Pow(10.0, 9.0));
                    Pair <int, Action> np = new Pair <int, Action>(sum, a);
                    sumTarget.Add(sum, targetAbsId);
                    cumulActSum = cumulActSum.AddLast(np);
                }
            }
            if (!newStateActs.IsEmpty)
            {
                maxAct = newStateActs.Choose();
                System.Console.WriteLine("new action in new state " + maxAct.ToString());
                return(maxAct);
            }
            else
            {
                Random rndNumbers = new Random();
                int    rndNumber  = rndNumbers.Next(sum);
                System.Console.WriteLine(sum + " " + rndNumber);
                foreach (Pair <int, Action> np in cumulActSum)
                {
                    System.Console.WriteLine(np.First + " " + np.Second.ToString());
                    if (rndNumber <= np.First)
                    {
                        maxAct   = np.Second;
                        targetId = sumTarget[np.First];
                        break;
                    }
                    targetId = sumTarget[np.First];
                    maxAct   = np.Second;
                }
                System.Console.WriteLine("old action in old state " + maxAct.ToString());
            }
            // Adaptive Refinement
            if (MaxV[targetId] - MinV[targetId] > epsilon)
            {
                if (i < requirementProperties.Count)
                {
                    string s1 = requirementProperties[i++];
                    bdt = bdt.Refine(s1, requireEnabledStateMap[s1]);
                    bdt.PrintTree(0);
                }
            }
            return(maxAct);
        }
示例#18
0
        public static Sequence <Sequence <CompoundTerm> > GenerateTestSequences(FSM fa)
        {
            //Eliminate dead states from the fa
            Set <Term> deadStates  = GetDeadStates(fa);
            Set <Term> aliveStates = fa.States.Difference(deadStates);
            Set <Triple <Term, CompoundTerm, Term> > aliveTransitions =
                fa.Transitions.Select(delegate(Triple <Term, CompoundTerm, Term> trans)
            {
                return(aliveStates.Contains(trans.First) &&
                       aliveStates.Contains(trans.Third));
            });

            if (aliveTransitions.IsEmpty) //test suite cannot be generated
            {
                return(Sequence <Sequence <CompoundTerm> > .EmptySequence);
            }

            //Build a graph from the alive transitions
            Term[] states = new Term[aliveStates.Count];
            Dictionary <Term, int> stateToVertexMap = new Dictionary <Term, int>();

            states[0] = fa.InitialState;
            stateToVertexMap[fa.InitialState] = 0;
            int i = 1;

            foreach (Term state in aliveStates.Remove(fa.InitialState))
            {
                states[i] = state;
                stateToVertexMap[state] = i++;
            }

            //create edges that must be traversed
            GraphTraversals.Edge[] mustEdges = new GraphTraversals.Edge[aliveTransitions.Count];
            Triple <Term, CompoundTerm, Term>[] mustTransitions = new Triple <Term, CompoundTerm, Term> [aliveTransitions.Count];
            i = 0;
            foreach (Triple <Term, CompoundTerm, Term> trans in aliveTransitions)
            {
                GraphTraversals.Edge edge = new GraphTraversals.Edge(stateToVertexMap[trans.First],
                                                                     stateToVertexMap[trans.Third], i);
                mustEdges[i]         = edge;
                mustTransitions[i++] = trans;
            }

            //add an optional edge with label -1 from every accepting state
            //to the initial state, this corresponds to a reset action
            GraphTraversals.Edge[] optionalEdges =
                new GraphTraversals.Edge[fa.AcceptingStates.Count];
            i = 0;
            foreach (Term accState in fa.AcceptingStates)
            {
                int accVertex = stateToVertexMap[accState];
                optionalEdges[i++] = new GraphTraversals.Edge(accVertex, 0, -1); //-1 = reset
            }

            //at this point it is known that g is strongly connected and has no dead states
            //so a postman tour exists, compute a postman tour
            GraphTraversals.Graph g =
                new GraphTraversals.Graph(0, mustEdges, optionalEdges,
                                          GraphTraversals.WeakClosureEnum.DoNotClose);
            List <GraphTraversals.Edge> postmanTour =
                new List <GraphTraversals.Edge>(g.GetRuralChinesePostmanTour());

            #region normalize the tour so that it ends in an accepting state and has a reset at the end as a "watchdog"
            //if the last edge has not label -1, i.e. the edge leading back
            //to the initial state is not a reset edge from an accepting state
            //and the last state is not an accepting state
            //then extend the path to an accepting state, from the beginning of the path
            //notice that there must be at least one accepting state, so such an extesion
            //is indeed possible
            GraphTraversals.Edge lastEdge = postmanTour[postmanTour.Count - 1];
            if (lastEdge.label >= 0) //if the last edge is a reset, we are done
            {
                //the last edge leads back to the initial state, because this is a tour
                if (fa.AcceptingStates.Contains(fa.InitialState))
                {
                    postmanTour.Add(new GraphTraversals.Edge(0, 0, -1)); //add a watchdog
                }
                else
                {
                    //create an extesion to the tour from the initial state to the first accepting state
                    List <GraphTraversals.Edge> extension = new List <GraphTraversals.Edge>();
                    foreach (GraphTraversals.Edge edge in postmanTour)
                    {
                        extension.Add(edge);
                        if (fa.AcceptingStates.Contains(states[edge.target]))
                        {
                            //the end state of the edge is accepting, so we are done
                            extension.Add(new GraphTraversals.Edge(0, 0, -1)); //add a watchdog
                            break;
                        }
                    }
                    postmanTour.AddRange(extension);
                }
            }
            #endregion

            #region break up the tour into sequences of transition ids separated by the reset edge
            List <List <int> > paths = new List <List <int> >();
            List <int>         path  = new List <int>();
            for (int k = 0; k < postmanTour.Count; k++)
            {
                //presense of the watchdog at the end of the tour is assumed here
                GraphTraversals.Edge edge = postmanTour[k];
                if (edge.label < 0) //encountered reset, end of path
                {
                    paths.Add(path);
                    path = new List <int>();
                }
                else
                {
                    path.Add(edge.label);
                }
            }
            #endregion

            #region map the paths into action sequences
            Sequence <Sequence <CompoundTerm> > res = Sequence <Sequence <CompoundTerm> > .EmptySequence;
            foreach (List <int> path1 in paths)
            {
                Sequence <CompoundTerm> transSeq = Sequence <CompoundTerm> .EmptySequence;
                foreach (int transId in path1)
                {
                    transSeq = transSeq.AddLast(mustTransitions[transId].Second);
                }
                res = res.AddLast(transSeq);
            }
            #endregion

            return(res);
        }
示例#19
0
        private CompoundTerm ChooseAction(Sequence <Action> actions, IState iState)
        {
            Action         maxAct = actions.Head;
            int            sState = iState.GetHashCode();
            int            tState;
            IExtendedState iestate = (IExtendedState)iState;
            int            c       = iestate.LocationValuesCount;

            foreach (Action a in actions)
            {
                foreach (string s in this.modelProgram.GetEnablingConditionDescriptions(iState, a, false))
                {
                    Term                 t     = Term.Parse(s);
                    Sequence <Term>      vars  = (t.Arguments[0].Arguments);
                    Map <Variable, Term> subst = ConstructSubst(a, vars);
                    System.Console.WriteLine(a.ToString() + sState + " enabled string " + t.Arguments[1].Substitute(subst));
                }
            }

            /*
             * for (int i = 0; i < c; i++)
             * {
             *  System.Console.WriteLine("name: "+iestate.GetLocationName(i) + " value : "+
             *      iestate.GetLocationValue(i) + " hash" +
             *      iestate.GetLocationValue(i).GetHashCode());
             *  CompoundValue t  = (CompoundValue)iestate.GetLocationValue(i);
             *  foreach (CompoundValue t1 in t.FieldValues())
             *  {
             *      System.Console.WriteLine(" field " + t1.ToString());
             *  }
             * }
             */

            TransitionProperties tp;
            int sum = 0;
            Sequence <Pair <int, Action> > cumulActSum = Sequence <Pair <int, Action> > .EmptySequence;

            Set <int> coveredActs = findCoveredActs(sState, actions);

            if (!cov.ContainsKey(sState))
            {
                cov[sState] = 0.0;
            }
            Set <Action> newStateActs = new Set <Action>();
            Set <Action> newActs      = new Set <Action>();
            Set <Action> oldActs      = new Set <Action>(actions.Head);

            foreach (Action a in actions)
            {
                tState = this.modelProgram.GetTargetState(iState, a, null, out tp).GetHashCode();
                if (!v.ContainsKey(tState))
                {
                    newStateActs = newStateActs.Add(a);
                }
                else if (!coveredActs.Contains(a.GetHashCode()))
                {
                    newActs = newActs.Add(a);
                }
                else
                {
                    // one greedy approach

                    /*
                     * if (v.ContainsKey(tState) && v[tState] > maxv)
                     * {
                     *  maxv = v[tState];
                     *  oldActs = new Set<Action>(a);
                     * }
                     * else if (v.ContainsKey(tState) && v[tState] == maxv)
                     * {
                     *  oldActs = oldActs.Add(a);
                     * }*/

                    // probabilistic greedy approach
                    if (v.ContainsKey(tState))
                    {
                        sum = sum + (int)(v[tState] * Math.Pow(10.0, 9.0));
                        Pair <int, Action> np = new Pair <int, Action>(sum, a);
                        cumulActSum = cumulActSum.AddLast(np);
                    }
                }
            }
            if (!newStateActs.IsEmpty)
            {
                maxAct = newStateActs.Choose();
                System.Console.WriteLine("new action in new state " + maxAct.ToString());
            }
            else if (!newActs.IsEmpty)
            {
                maxAct = newActs.Choose();
                System.Console.WriteLine("new action in old state " + maxAct.ToString());
            }
            else
            {
                //maxAct = oldActs.Choose();
                Random rndNumbers = new Random();
                int    rndNumber  = rndNumbers.Next(sum);
                System.Console.WriteLine(sum + " " + rndNumber);
                foreach (Pair <int, Action> np in cumulActSum)
                {
                    System.Console.WriteLine(np.First + " " + np.Second.ToString());
                    if (rndNumber <= np.First)
                    {
                        maxAct = np.Second;
                        break;
                    }
                    maxAct = np.Second;
                }
                System.Console.WriteLine("old action in old state " + maxAct.ToString());
            }
            coveredActs = coveredActs.Add(maxAct.GetHashCode());
            cov[sState] = (double)coveredActs.Count / (double)actions.Count;
            return(maxAct);
        }