Esempio n. 1
0
 /// <summary>
 /// Check if the term represented by goal is reachable in the given model program.
 /// Empty string as goal results in traversing the whole state space.
 /// </summary>
 /// <param name="mp">The model program to be checked.</param>
 /// <param name="goal">The goal term involving the model program name as outer function symbol.</param>
 /// <param name="excludeIsomorphicStates">Whether to use the symmetry reduction. Default is false.</param>
 public static ReachabilityResult Check(ModelProgram mp, string goal, bool excludeIsomorphicStates = false)
 {
     Reachability reach = new Reachability();
     reach.ModelProgram = mp;
     reach.excludeIsomorphicStates = excludeIsomorphicStates;
     return reach.CheckReachability(goal);
 }
Esempio n. 2
0
 public MDPStrategy(ModelProgram modelProgram)
     : base(modelProgram)
 {
     cov = new Dictionary<IState, double>();
     v = new Dictionary<IState, double>();
     cps = new Dictionary<int, Set<int>>();
 }
Esempio n. 3
0
 /// <summary>
 /// Construct a strategy with random action selection from the given model program.
 /// </summary>
 /// <param name="modelProgram">model program</param>
 public Strategy(ModelProgram modelProgram)
 {
     if (modelProgram == null)
         throw new ArgumentNullException("modelProgram");
     this.modelProgram = modelProgram;
     this.currState = modelProgram.InitialState;
     this.initialState = modelProgram.InitialState;
 }
Esempio n. 4
0
        /// <summary>
        ///   Инициализация модели.
        /// </summary>
        /// <param name = "program">Модель программы.</param>
        /// <exception cref = "ArgumentNullException"><paramref name = "program" /> является <c>null</c>.</exception>
        /// <remarks>
        ///   При инициализации модели совершается полный обход пространства
        ///   состояний. Состояния должны иметь тип <see cref = "SimpleState" />.
        ///   Списком атомарных высказываний назначается список всевозможных
        ///   существующих пар <c>x=y</c>, где <c>x</c> - имя переменной,
        ///   <c>y</c> - её значение.
        /// </remarks>
        public Model (ModelProgram program) {
            if (program == null)
                throw new ArgumentNullException ("program");

            this.states = new Dictionary <int, List <string>> ();
            this.transitions = new Dictionary <int, List <int>> ();

            this.Prepare (program);
        }
Esempio n. 5
0
            internal ComposedSignature(ModelProgram m1, ModelProgram m2)
            {
                Set <Symbol> allActionSymbols = m1.ActionSymbols().Union(m2.ActionSymbols());

                this.actionSymbols       = allActionSymbols;
                this.m1ActionSymbols     = allActionSymbols.Difference(m2.ActionSymbols());
                this.m2ActionSymbols     = allActionSymbols.Difference(m1.ActionSymbols());
                this.sharedActionSymbols = m1.ActionSymbols().Intersect(m2.ActionSymbols());
            }
Esempio n. 6
0
 public MDPNewStrategy(ModelProgram modelProgram)
     : base(modelProgram)
 {
     cov = new Dictionary<int, double>();
     v = new Dictionary<int, double>();
     cps = new Dictionary<int, Set<int>>();
     activeEdges = new Dictionary<int, Set<int>>();
     passiveEdges = new Dictionary<int, Bag<int>>();
     v[this.currState.GetHashCode()] = 1.0;
     cov[this.currState.GetHashCode()] = 0.0;
 }
Esempio n. 7
0
        private void Prepare (ModelProgram program) {
            var actionSymbols = program.ActionSymbols ();
            var _states = new Dictionary <SimpleState, int> ();
            var _trans = new Dictionary <SimpleState, List <SimpleState>> ();
            var frontier = new LinkedList <IState> (new [] { program.InitialState });
            var stateIndex = 0;

            while (frontier.Count > 0) {
                var state = (SimpleState) frontier.First.Value;
                frontier.RemoveFirst ();

                if (! _states.ContainsKey (state))
                    _states.Add (state, stateIndex ++);

                foreach (var action in actionSymbols.
                    Where (symbol => program.IsPotentiallyEnabled (state, symbol)).
                    SelectMany (symbol => program.GetActions (state, symbol))) {
                    TransitionProperties properties;
                    var target =
                        (SimpleState) program.GetTargetState (state, action, Set <string>.EmptySet, out properties);

                    if (! _trans.ContainsKey (state))
                        _trans.Add (state, new List <SimpleState> ());
                    _trans [state].Add (target);

                    if (! (_states.ContainsKey (target) || frontier.Contains (target)))
                        frontier.AddFirst (target);
                }
            }

            foreach (var state in _states) {
                var list = new List <string> ();

                for (var i = 0; i < state.Key.LocationValuesCount; ++ i)
                    list.Add (string.Format ("{0}={1}", state.Key.GetLocationName (i), state.Key.GetLocationValue (i)));

                this.states.Add (state.Value, list);
            }

            foreach (var transition in _trans) {
                this.transitions.Add (_states [transition.Key],
                                      transition.Value.Select (state => _states [state]).ToList ());
            }

            for (var i = 0; i < stateIndex; ++ i) {
                if (! this.transitions.ContainsKey (i))
                    this.transitions.Add (i, new List <int> ());
            }
        }
Esempio n. 8
0
 /// <summary>
 /// Constructs a model stepper for a given test suite and a given model program,
 /// using the product of the test suite and the model program.
 /// </summary>
 /// <param name="startTest">name of start action of a test case</param>
 /// <param name="testsuite">given test suite as a nonempty sequence of test cases</param>
 /// <param name="mp">given model program</param>
 public TestSuiteStepper(string startTest, Sequence<Sequence<CompoundTerm>> testsuite, ModelProgram mp)
     : base(CreateModelProgram(startTest, testsuite, mp))
 {
     if (testsuite == null ||
         testsuite.IsEmpty ||
         testsuite.Exists(delegate(Sequence<CompoundTerm> testcase)
             {
                 return (testcase == null || testcase.IsEmpty);
             }))
         throw new ConformanceTesterException("Invalid test suite, the test suite must be a nonempty sequence of nonempty action sequences.");
     this.currentTest = testsuite.Head.AddFirst((CompoundTerm)Term.Parse(startTest + "(" + 0 + ")"));
     this.testsuite = testsuite.Tail;
     this.currentTestInProgress = false;
     this.testnr = 1;
     this.startTest = startTest;
 }
Esempio n. 9
0
            internal ComposedSignature(ModelProgram m1, ModelProgram m2)
            {
                Set<Symbol> allActionSymbols = m1.ActionSymbols().Union(m2.ActionSymbols());

                this.actionSymbols = allActionSymbols;
                this.m1ActionSymbols = allActionSymbols.Difference(m2.ActionSymbols());
                this.m2ActionSymbols = allActionSymbols.Difference(m1.ActionSymbols());
                this.sharedActionSymbols = m1.ActionSymbols().Intersect(m2.ActionSymbols());
            }
Esempio n. 10
0
        /// <summary>
        /// Used internally by the derived viewer that may also set the modelprogram
        /// </summary>
        internal void SetStateMachine(FSM fa, StateProvider stateProvider, ModelProgram mp1, Set<Transition> groupingTransitions)
        {
            // Clear the node and transition tables and the cache
            this.mp = mp1;
            // nodes.Clear(); // not needed for mp2dot, I believe
            // transitions.Clear(); // ditto
            //reductCache.Clear();
            //this.faInfo = new FAInfo(this.stateViewer1.DefaultModelName, fa, stateProvider, mp1);
            this.faInfo = new FAInfo("Fsm", fa, stateProvider, mp1); // defined in StateView.cs
            this.finiteAutomatonContext = new FAContext(fa, stateProvider, faInfo.ReductNames.Last, mp1);
            this.finiteAutomatonContext.groupingTransitions = groupingTransitions;
            //this.reductCache[this.faInfo.ReductNames.Last] = this.finiteAutomatonContext;

            // removed code here
        }
Esempio n. 11
0
 static ModelProgram CreateModelProgram(string startTest, Sequence<Sequence<CompoundTerm>> testsuite, ModelProgram mp)
 {
     Set<Symbol> symbs = Set<Symbol>.EmptySet;
     foreach (Sequence<CompoundTerm> testcase in testsuite)
         foreach (CompoundTerm action in testcase)
             symbs = symbs.Add(action.Symbol);
     FSM fa = FsmTraversals.GenerateTestSequenceAutomaton(startTest, testsuite, symbs);
     FsmModelProgram fsmmp = new FsmModelProgram(fa, "TestSuite");
     if (mp == null)
         return fsmmp;
     else
         return new ProductModelProgram(fsmmp, mp);
 }
Esempio n. 12
0
 FAName GetModelName(ModelProgram mp1)
 {
     IName nameProvider = mp1 as IName;
     if (nameProvider != null)
         return new FAName(Disambiguate(nameProvider.Name));
     return new FAName(Disambiguate(this.defaultModelName));
 }
Esempio n. 13
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)));
     }
 }
Esempio n. 14
0
 /// <summary>
 /// Builder that can create a finite automaton by exploring the possible steps of a model program.
 /// </summary>
 /// <param name="m">Model program to be explored</param>
 public FSMBuilder(ModelProgram m) : this(m, null)
 {
 }
Esempio n. 15
0
 internal FAInfo(string defaultModelName,
     FSM fa, StateProvider stateProvider, ModelProgram mp)
 {
     this.fa = fa;
     this.stateProvider = stateProvider;
     this.defaultModelName = defaultModelName;
     this.nameDisambiguator = new Dictionary<string, int>();
     this.mp = mp;
 }
Esempio n. 16
0
 /// <summary>
 /// Builder that can create a finite automaton by exploring the possible steps of a model program.
 /// </summary>
 /// <param name="m">Model program to be explored</param>
 /// <param name="transitionPredicate">User defined predicate that returns true if a
 /// transition is to be included in the gererated finite automaton</param>
 public FSMBuilder(ModelProgram m, TransitionPredicate transitionPredicate)
 {
     this.modelProgram        = m;
     this.transitionPredicate = transitionPredicate;
 }
Esempio n. 17
0
 internal ExploredTransitions(ModelProgram modelProgram, int initTransitions, int maxTransitions)
 {
     this.modelProgram = modelProgram;
     this.transitions = Set<Transition>.EmptySet;
     this.groupingTransitions = Set<Transition>.EmptySet;
     Node initNode = new Literal(0);
     this.initialNode = initNode;
     this.nodes = new Set<Node>(initNode);
     this.acceptingNodes = (modelProgram.IsAccepting(modelProgram.InitialState) ?
         new Set<Node>(initNode) :
         Set<Node>.EmptySet);
     //this.errorNodes = (!modelProgram.SatisfiesStateInvariant(modelProgram.InitialState) ?
     //    new Set<Node>(initNode) :
     //    Set<Node>.EmptySet);
     Dictionary<Node, IState> initialStateMap =
         new Dictionary<Node, IState>();
     initialStateMap[initNode] = modelProgram.InitialState;
     this.stateMap = initialStateMap;
     actionsExploredFromNode = new Dictionary<Node, Dictionary<CompoundTerm,Node>>();
     Dictionary<IState, Node> initialNodeMap =
         new Dictionary<IState, Node>();
     initialNodeMap[modelProgram.InitialState] = initNode;
     this.nodeMap = initialNodeMap;
     this.hiddenTransitions = Set<Transition>.EmptySet;
     this.maxTransitions = maxTransitions;
     this.initTransitions = initTransitions;
 }
Esempio n. 18
0
 /// <summary>
 /// Construct a model stepper that records coverage points.
 /// </summary>
 /// <param name="modelProgram">model program</param>
 /// <param name="policy">reward policy</param>
 /// <param name="coveragePointProvider">(optional) coverage point provider</param>
 public StrategyWithCoverage(ModelProgram modelProgram, RewardPolicy policy, CoveragePointDelegate coveragePointProvider)
     : base(modelProgram)
 {
     this.policy = policy;
     this.coveragePointProvider = coveragePointProvider;
 }
Esempio n. 19
0
 /// <summary>
 /// Process the goal in the format "ModelProgramName1(stateName1(value1)),ModelProgramName2(stateName2(value2)" to a compound term of the corresponding model program.
 /// In the case of FSMs the format is "ModelProgramName(stateNumber)".
 /// </summary>
 /// <param name="mp">model program</param>
 /// <param name="goalString">goal as string</param>
 /// <returns>A set of compound terms corresponding to the goal string.</returns>
 internal Set<CompoundTerm> processGoal(ModelProgram mp, string goalString)
 {
     Set<CompoundTerm> processedGoals = Set<CompoundTerm>.EmptySet;
     if (goalString == "") return processedGoals;
     string[] subgoals = goalString.Split(',');
     Set<CompoundTerm> goals = Set<CompoundTerm>.EmptySet;
     try
     {
         foreach (string g in subgoals)
         {
             CompoundTerm ct = CompoundTerm.Parse(g);
             goals = goals.Add(ct);
         }
     }
     catch (Exception e)
     {
         Console.Error.WriteLine("The goal '" + goalString + "' seems not to be a term. " +
             "Goal should be in the form ModelProgramName(state) " +
             "(or several such terms separated by commas).");
         Console.Error.WriteLine("The error message: ", e.Message);
         return processedGoals;
     }
     return processGoal(mp, goals);
 }
Esempio n. 20
0
 /// <summary>
 /// Construct a model stepper that records coverage points.
 /// Coverage points of interest are provided by <paramref name="transitionPropertyNames"/>
 /// </summary>
 /// <param name="modelProgram">model program</param>
 /// <param name="policy">reward policy</param>
 /// <param name="transitionPropertyNames">(optional) coverage points of interest</param>
 public StrategyWithCoverage(ModelProgram modelProgram, RewardPolicy policy, Set<string> transitionPropertyNames)
     : base(modelProgram)
 {
     this.policy = policy;
     this.coveragePointProvider = new CoveragePointProvider(modelProgram, transitionPropertyNames).GetCoveragePoints;
 }
Esempio n. 21
0
        ComposedSignature signature; // cache: equals m1.ActionSymbols union m2.ActionSymbols

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructs m1 * m2
        /// </summary>
        public ProductModelProgram(ModelProgram m1, ModelProgram m2)
        {
            this.signature = new ComposedSignature(m1, m2);
            this.m1 = m1;
            this.m2 = m2;
        }
Esempio n. 22
0
 public MDPNewAbstractStrategy(ModelProgram modelProgram):
     base(modelProgram)
 {
     requirementProperties = Sequence<string>.EmptySequence;
     requireEnabledStateMap = Map<string, Set<int>>.EmptyMap;
     activeEdges = new Dictionary<int, Set<int>>();
     passiveEdges = new Dictionary<int, Bag<int>>();
     bdt = new BinaryDecisionTree("root", null, null,1,1, new Set<int>(currState.GetHashCode()));
 }
Esempio n. 23
0
        private static IStrategy CreateModelStepper(List<Assembly> libs, ModelProgram mp,
            string/*?*/ msName, string[]/*?*/ coverage, Set<Symbol> obs)
        {
            //if no model stepper name is provided, use the default one and ignore coverage
            if (msName == null)
                return new Strategy(mp);

            //check if one of the supported model steppers is used
            if (msName.Equals(typeof(StrategyWithCoverage).FullName + ".CreateWithMaximumReward"))
                return StrategyWithCoverage.CreateWithMaximumReward(mp, coverage);
            //check if one of the supported model steppers is used
            if (msName.Equals(typeof(StrategyWithCoverage).FullName + ".CreateWithProbableReward"))
                return StrategyWithCoverage.CreateWithProbableReward(mp, coverage);

            string msMethodName;
            string msClassName;
            ReflectionHelper.SplitFullMethodName(msName, out msClassName, out msMethodName);
            Type msType = ReflectionHelper.FindType(libs, msClassName);
            MethodInfo msMethod = ReflectionHelper.FindMethod(msType, msMethodName, new Type[] { typeof(ModelProgram), typeof(string[]) } , typeof(IStrategy));
            IStrategy ms = null;
            try
            {
                ms = (IStrategy)msMethod.Invoke(null, new object[] { mp, coverage });
                ms.ObservableActionSymbols = obs;
            }
            catch (Exception e)
            {
                throw new ModelProgramUserException("Invocation of '" + msName + "' failed: " + e.ToString());
            }
            return ms;
        }
Esempio n. 24
0
 /// <summary>
 /// Used internally by the derived viewer that may also set the modelprogram
 /// </summary>
 internal void SetStateMachine(FSM fa, StateProvider stateProvider, ModelProgram mp1, Set<Transition> groupingTransitions)
 {
     // Clear the node and transition tables and the cache
     this.mp = mp1;
     nodes.Clear();
     transitions.Clear();
     //reductCache.Clear();
     this.faInfo = new FAInfo(this.stateViewer1.DefaultModelName, fa, stateProvider, mp1);
     this.finiteAutomatonContext = new FAContext(fa, stateProvider, faInfo.ReductNames.Last, mp1);
     this.finiteAutomatonContext.groupingTransitions = groupingTransitions;
     //this.reductCache[this.faInfo.ReductNames.Last] = this.finiteAutomatonContext;
     this.projectionButton.Text = "     " + faInfo.ReductNames.Last.name.ToString();
     this.projectionButton.ToolTipText = faInfo.ReductNames.Last.name.ToString();
     if (faInfo.IsProduct)
     {
         this.projectionButton.Enabled = true;
         EnableProjection();
     }
     else
     {
         this.projectionButton.Enabled = false;
     }
     graphChanged = true;
     PerformLayout();
 }
Esempio n. 25
0
 /// <summary>
 /// Creates a model stepper that uses coverage points (when != null) to direct the selection of actions.
 /// If coverage == null, uses default coverage points that are (state.GetHashCode(), action.GetHashCode()) pairs.
 /// Uses RewardPolicy.ProbableReward for action selection.
 /// </summary>
 /// <param name="modelProgram">given model program</param>
 /// <param name="coverage">given coverage point names (may be null)</param>
 public static StrategyWithCoverage CreateWithProbableReward(ModelProgram modelProgram, string[]/*?*/ coverage)
 {
     if (coverage == null)
         return new StrategyWithCoverage(modelProgram, RewardPolicy.ProbableReward);
     else
         return new StrategyWithCoverage(modelProgram, RewardPolicy.ProbableReward, new Set<string>(coverage));
 }
Esempio n. 26
0
 /// <summary>
 /// Builder that can create a finite automaton by exploring the possible steps of a model program.
 /// </summary>
 /// <param name="m">Model program to be explored</param>
 public FSMBuilder(ModelProgram m)
     : this(m,null)
 {
 }
Esempio n. 27
0
 /// <summary>
 /// Construct a model stepper that records coverage points.
 /// Defines the coverage point for a given action a and state s 
 /// as the bag containig the pair (s.GetHashCode(),a.GetHashCode())
 /// </summary>
 /// <param name="modelProgram">model program</param>
 /// <param name="policy">reward policy</param>
 public StrategyWithCoverage(ModelProgram modelProgram, RewardPolicy policy)
     : base(modelProgram)
 {
     this.policy = policy;
     this.coveragePointProvider = DefaultCoveragePointProvider;
 }
Esempio n. 28
0
 /// <summary>
 /// Builder that can create a finite automaton by exploring the possible steps of a model program.
 /// </summary>
 /// <param name="m">Model program to be explored</param>
 /// <param name="transitionPredicate">User defined predicate that returns true if a 
 /// transition is to be included in the gererated finite automaton</param>
 public FSMBuilder(ModelProgram m, TransitionPredicate transitionPredicate)
 {
     this.modelProgram = m;
     this.transitionPredicate = transitionPredicate;
 }
Esempio n. 29
0
        internal Set<CompoundTerm> processGoal(ModelProgram mp, Set<CompoundTerm> goals)
        {
            Set<CompoundTerm> processedGoals = Set<CompoundTerm>.EmptySet;
            if (typeof(LibraryModelProgram) == mp.GetType())
            {
                //we ignore it for the moment
                Console.Error.WriteLine("Goals involving LibraryModelPrograms currently not supported. ");
                Console.Error.WriteLine("Currently searching for a match for '" + goals.ToString() + "'. ");
            }
            else if (typeof(FsmModelProgram) == mp.GetType()) {
                FsmModelProgram fsm = (FsmModelProgram)mp;
                foreach (CompoundTerm ct in goals)
                {
                    Console.WriteLine("Checking FSM: " + ct.ToString() + "; " + fsm.Name);
                    if (ct.FunctionSymbol.ToString() == fsm.Name) {
                        processedGoals = processedGoals.Add(CompoundTerm.Parse("FsmState(Set(" + ct.Arguments[0].ToString() + "))"));
                        goals = goals.Remove(ct);
                    }
                    Console.WriteLine("Current processedGoals: " + processedGoals.ToString());
                }

            }
            else if (typeof(ProductModelProgram) == mp.GetType())
            {
                ProductModelProgram pmp = (ProductModelProgram)mp;
                processedGoals = processedGoals.Union(processGoal(pmp.M1,goals));
                processedGoals = processedGoals.Union(processGoal(pmp.M2,goals));

            }
            return processedGoals;
        }
Esempio n. 30
0
 /// <summary>
 /// Creates a model stepper that uses coverage points (when != null) to direct the selection of actions.
 /// If coverage == null, uses default coverage points that are (state.GetHashCode(), action.GetHashCode()) pairs.
 /// Uses RewardPolicy.MaximumReward for action selection.
 /// </summary>
 /// <param name="modelProgram">given model program</param>
 /// <param name="coverage">given coverage point names (may be null)</param>
 public static MDPStrategy CreateMDPStrategy(ModelProgram modelProgram, string[]/*?*/ coverage)
 {
     //return new MDPStrategy(modelProgram,new Set<string>(coverage));
     return new MDPStrategy(modelProgram);
 }
Esempio n. 31
0
 /// <summary>
 /// Create a coverage point provider for a model program and a given set of property names
 /// </summary>
 /// <param name="mp">given model program</param>
 /// <param name="transitionPropertyNames">property names of interest</param>
 public CoveragePointProvider(ModelProgram mp, Set<string> transitionPropertyNames)
 {
     this.mp = mp;
     this.transitionPropertyNames = transitionPropertyNames;
 }
Esempio n. 32
0
 internal FAContext(FSM fa, StateProvider stateProvider, ReductName reductName, ModelProgram mp)
 {
     this.fa = fa;
     this.stateProvider = stateProvider;
     this.reductName = reductName;
     this.mp = mp;
     this.deadNodes = FsmTraversals.GetDeadStates(fa);
     this.unsafeNodes = Set<Node>.EmptySet;
     this.groupingTransitions = Set<Transition>.EmptySet;
 }
Esempio n. 33
0
 /// <summary>
 /// Sets the initial state of the view 
 /// </summary>
 /// <param name="modelProgram">given model program to be viewed</param>
 public void SetModelProgram(ModelProgram modelProgram1)
 {
     this.modelProgram = modelProgram1;
     this.exploredTransitions = new ExploredTransitions(modelProgram1, this.initialTransitions, this.maxTransitions);
     this.exploredTransitions.excludeIsomorphicStates = this.ExcludeIsomorphicStates;
     this.exploredTransitions.collapseExcludedIsomorphicStates = this.collapseExcludedIsomorphicStates;
     this.exploredTransitions.ShowReachable(this.exploredTransitions.initialNode);
     this.InitializeViewer();
 }
Esempio n. 34
0
        ComposedSignature signature;           // cache: equals m1.ActionSymbols union m2.ActionSymbols

        /// <summary>
        /// Constructs m1 * m2
        /// </summary>
        public ProductModelProgram(ModelProgram m1, ModelProgram m2)
        {
            this.signature = new ComposedSignature(m1, m2);
            this.m1        = m1;
            this.m2        = m2;
        }