public override InvariantAnalysisResult[] CheckInvariants(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, params Formula[] invariants)
        {
            var checker = new QualitativeChecker <SafetySharpRuntimeModel>(createModel);

            checker.Configuration = _analysisConfiguration;
            return(checker.CheckInvariants(invariants));
        }
Example #2
0
 /// <summary>
 ///   Computes the minimal critical sets for the <paramref name="hazard" />.
 /// </summary>
 /// <param name="createModel">The creator for the model that should be checked.</param>
 /// <param name="hazard">The hazard the minimal critical sets should be computed for.</param>
 /// <param name="maxCardinality">
 ///   The maximum cardinality of the fault sets that should be checked. By default, all minimal
 ///   critical fault sets are determined.
 /// </param>
 /// <param name="backend">Determines the safety analysis backend that is used during the analysis.</param>
 public static SafetyAnalysisResults <TExecutableModel> AnalyzeHazard(CoupledExecutableModelCreator <TExecutableModel> createModel, Formula hazard, int maxCardinality = Int32.MaxValue,
                                                                      SafetyAnalysisBackend backend = SafetyAnalysisBackend.FaultOptimizedOnTheFly)
 {
     return(new SafetyAnalysis <TExecutableModel> {
         Backend = backend
     }.ComputeMinimalCriticalSets(createModel, hazard, maxCardinality));
 }
Example #3
0
        /// <summary>
        ///   Checks whether the <paramref name="formula" /> holds in all states of the <paramref name="model" />.
        /// </summary>
        /// <param name="createModel">The creator for the model that should be checked.</param>
        /// <param name="checkArgument">The argument passed to LtsMin that indicates which kind of check to perform.</param>
        private AnalysisResult <SafetySharpRuntimeModel> Check(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, string checkArgument)
        {
            try
            {
                using (var modelFile = new TemporaryFile("ssharp"))
                {
                    File.WriteAllBytes(modelFile.FilePath, RuntimeModelSerializer.Save((ModelBase)createModel.SourceModel, createModel.StateFormulasToCheckInBaseModel));

                    try
                    {
                        CreateProcess(modelFile.FilePath, checkArgument);
                        Run();
                    }
                    catch (Win32Exception e)
                    {
                        throw new InvalidOperationException(
                                  "Failed to start LTSMin. Ensure that pins2lts-seq.exe can be found by either copying it next " +
                                  "to the executing assembly or by adding it to the system path. The required cygwin dependencies " +
                                  $"must also be available. The original error message was: {e.Message}", e);
                    }

                    var success = InterpretExitCode(_ltsMin.ExitCode);
                    return(new AnalysisResult <SafetySharpRuntimeModel> {
                        FormulaHolds = success
                    });
                }
            }
            finally
            {
                _ltsMin = null;
            }
        }
Example #4
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
        /// <param name="configuration">The analysis configuration that should be used.</param>
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal LtmdpExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, AnalysisConfiguration configuration)
            : base(runtimeModelCreator, 0, configuration)
        {
            var formulas = RuntimeModel.Formulas.Select(formula => FormulaCompilationVisitor <TExecutableModel> .Compile(RuntimeModel, formula)).ToArray();

            _stepGraph = new LtmdpStepGraph();

            _cachedLabeledStates = new LtmdpCachedLabeledStates <TExecutableModel>(TemporaryStateStorage, configuration.SuccessorCapacity, _stepGraph, formulas);

            bool useForwardOptimization;

            switch (configuration.MomentOfIndependentFaultActivation)
            {
            case MomentOfIndependentFaultActivation.AtStepBeginning:
            case MomentOfIndependentFaultActivation.OnFirstMethodWithoutUndo:
                useForwardOptimization = false;
                break;

            case MomentOfIndependentFaultActivation.OnFirstMethodWithUndo:
                useForwardOptimization = true;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            _ltmdpChoiceResolver = new LtmdpChoiceResolver(_stepGraph, useForwardOptimization);
            ChoiceResolver       = _ltmdpChoiceResolver;
            RuntimeModel.SetChoiceResolver(ChoiceResolver);

            _allowFaultsOnInitialTransitions = configuration.AllowFaultsOnInitialTransitions;

            _activateIndependentFaultsAtStepBeginning =
                configuration.MomentOfIndependentFaultActivation == MomentOfIndependentFaultActivation.AtStepBeginning;
        }
        protected void GenerateStateSpace(params IComponent[] components)
        {
            _modelCreator = SafetySharpRuntimeModel.CreateExecutedModelCreator(TestModel.InitializeModel(components), new ExecutableStateFormula(() => true));

            var configuration = AnalysisConfiguration.Default;

            configuration.ModelCapacity      = ModelCapacityByMemorySize.Small;
            configuration.StackCapacity      = 10000;
            configuration.CpuCount           = 1;
            configuration.DefaultTraceOutput = Output.TextWriterAdapter();
            configuration.AllowFaultsOnInitialTransitions = AllowFaultsOnInitialTransitions;

            var analysisModelCreator = new AnalysisModelCreator(() => new ActivationMinimalExecutedModel <SafetySharpRuntimeModel>(_modelCreator, 0, configuration));

            var checker = new InvariantChecker(analysisModelCreator,
                                               configuration,
                                               formulaIndex: 0);

            _result = checker.Check();
            CounterExample.ShouldBe(null);

            Output.Log($"States: {_result.StateCount}");
            Output.Log($"Actual Transitions: {_result.TransitionCount}");
            Output.Log($"Computed Transitions: {_result.ComputedTransitionCount}");
        }
Example #6
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
        /// <param name="formulas">The formulas that should be evaluated for each state.</param>
        /// <param name="configuration">The analysis configuration that should be used.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal ActivationMinimalExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, int stateHeaderBytes, Func <bool>[] formulas, AnalysisConfiguration configuration)
            : base(runtimeModelCreator, stateHeaderBytes, configuration)
        {
            formulas = formulas ?? RuntimeModel.Formulas.Select(formula => FormulaCompilationVisitor <TExecutableModel> .Compile(RuntimeModel, formula)).ToArray();

            _transitions      = new ActivationMinimalTransitionSetBuilder <TExecutableModel>(TemporaryStateStorage, configuration.SuccessorCapacity, formulas);
            _stateConstraints = RuntimeModel.StateConstraints;

            bool useForwardOptimization;

            switch (configuration.MomentOfIndependentFaultActivation)
            {
            case MomentOfIndependentFaultActivation.AtStepBeginning:
            case MomentOfIndependentFaultActivation.OnFirstMethodWithoutUndo:
                useForwardOptimization = false;
                break;

            case MomentOfIndependentFaultActivation.OnFirstMethodWithUndo:
                useForwardOptimization = true;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            ChoiceResolver = new NondeterministicChoiceResolver(useForwardOptimization);
            FaultSet.CheckFaultCount(RuntimeModel.Faults.Length);

            RuntimeModel.SetChoiceResolver(ChoiceResolver);

            _allowFaultsOnInitialTransitions = configuration.AllowFaultsOnInitialTransitions;
        }
Example #7
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="createModel">A factory function that creates the model instance that should be executed.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal ExecutedModel(CoupledExecutableModelCreator <TExecutableModel> createModel, int stateHeaderBytes)
        {
            Requires.NotNull(createModel, nameof(createModel));

            RuntimeModelCreator = createModel;
            RuntimeModel        = createModel.Create(stateHeaderBytes);
        }
Example #8
0
        /// <summary>
        ///   Initizializes the model that should be analyzed.
        /// </summary>
        /// <param name="configuration">The configuration that should be used for the analyses.</param>
        /// <param name="createFreshModel">The creator for the model that should be checked.</param>
        /// <param name="hazard">The hazard that should be analyzed.</param>
        internal void InitializeModel(AnalysisConfiguration configuration, CoupledExecutableModelCreator <TExecutableModel> createFreshModel, Formula hazard)
        {
            RuntimeModelCreator = createFreshModel;
            ForcedFaults        = new FaultSet(createFreshModel.FaultsInBaseModel.Where(fault => fault.Activation == Activation.Forced));
            SuppressedFaults    = new FaultSet(createFreshModel.FaultsInBaseModel.Where(fault => fault.Activation == Activation.Suppressed));

            InitializeModel(configuration, hazard);
        }
Example #9
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="createModel">A factory function that creates the model instance that should be executed.</param>
        /// <param name="configuration">The analysis configuration that should be used.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal ExecutedModel(CoupledExecutableModelCreator <TExecutableModel> createModel, int stateHeaderBytes, AnalysisConfiguration configuration)
        {
            Requires.NotNull(createModel, nameof(createModel));

            RuntimeModelCreator   = createModel;
            RuntimeModel          = createModel.Create(stateHeaderBytes);
            TemporaryStateStorage = new TemporaryStateStorage(ModelStateVectorSize, configuration.SuccessorCapacity);
        }
Example #10
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="counterExample">The counter example that should be simulated.</param>
        public Simulator(CoupledExecutableModelCreator <TExecutableModel> modelCreator, CounterExample counterExample)
        {
            Requires.NotNull(counterExample, nameof(counterExample));

            RuntimeModel    = modelCreator.Create(0);
            _counterExample = new ExecutableCounterExample <TExecutableModel>(RuntimeModel, counterExample);

            Reset();
        }
Example #11
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
        /// <param name="successorStateCapacity">The maximum number of successor states supported per state.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal LtmcExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, int stateHeaderBytes, long successorStateCapacity)
            : base(runtimeModelCreator, stateHeaderBytes)
        {
            var formulas = RuntimeModel.Formulas.Select(formula => FormulaCompilationVisitor <TExecutableModel> .Compile(RuntimeModel, formula)).ToArray();

            _transitions = new LtmcTransitionSetBuilder <TExecutableModel>(RuntimeModel, successorStateCapacity, formulas);

            _ltmcChoiceResolver = new LtmcChoiceResolver();
            ChoiceResolver      = _ltmcChoiceResolver;
            RuntimeModel.SetChoiceResolver(ChoiceResolver);
        }
 /// <summary>
 ///   Initializes a new instance.
 /// </summary>
 /// <param name="createModel">The creator for the model that should be checked.</param>
 /// <param name="hazard">The hazard the analysis was conducated for.</param>
 /// <param name="suppressedFaults">The faults whose activations have been completely suppressed during analysis.</param>
 /// <param name="forcedFaults">The faults whose activations have been forced during analysis.</param>
 /// <param name="heuristics">The heuristics that are used during the analysis.</param>
 /// <param name="activationBehavior">The fault acitvation behavior used during the analysis.</param>
 internal SafetyAnalysisResults(CoupledExecutableModelCreator <TExecutableModel> createModel, Formula hazard,
                                IEnumerable <Fault> suppressedFaults, IEnumerable <Fault> forcedFaults,
                                IEnumerable <IFaultSetHeuristic> heuristics, FaultActivationBehavior activationBehavior)
 {
     RuntimeModelCreator = createModel;
     Hazard                  = hazard;
     SuppressedFaults        = suppressedFaults;
     ForcedFaults            = forcedFaults;
     Heuristics              = heuristics.ToArray(); // make a copy so that later changes to the heuristics don't affect the results
     FaultActivationBehavior = activationBehavior;
 }
Example #13
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="createModel">A factory function that creates the model instance that should be executed.</param>
        /// <param name="configuration">The analysis configuration that should be used.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal ExecutedModel(CoupledExecutableModelCreator <TExecutableModel> createModel, int stateHeaderBytes, AnalysisConfiguration configuration)
        {
            Requires.NotNull(createModel, nameof(createModel));

            RuntimeModelCreator = createModel;
            var runtimeModel = createModel.Create(stateHeaderBytes);

            RuntimeModel = runtimeModel;

            TemporaryStateStorage = new TemporaryStateStorage(ModelStateVectorSize, configuration.SuccessorCapacity);
            SavedActivations      = runtimeModel.NondeterministicFaults.Select(fault => fault.Activation).ToArray();
        }
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
        /// <param name="formulas">The formulas that should be evaluated for each state.</param>
        /// <param name="successorStateCapacity">The maximum number of successor states supported per state.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal ActivationMinimalExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, int stateHeaderBytes, Func <bool>[] formulas, long successorStateCapacity)
            : base(runtimeModelCreator, stateHeaderBytes)
        {
            formulas = formulas ?? RuntimeModel.Formulas.Select(formula => FormulaCompilationVisitor <TExecutableModel> .Compile(RuntimeModel, formula)).ToArray();

            _transitions      = new ActivationMinimalTransitionSetBuilder <TExecutableModel>(RuntimeModel, successorStateCapacity, formulas);
            _stateConstraints = RuntimeModel.StateConstraints;

            ChoiceResolver = new NondeterministicChoiceResolver();

            RuntimeModel.SetChoiceResolver(ChoiceResolver);
        }
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
        /// <param name="successorStateCapacity">The maximum number of successor states supported per state.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal LtmdpExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, int stateHeaderBytes, long successorStateCapacity)
            : base(runtimeModelCreator, stateHeaderBytes)
        {
            var formulas = RuntimeModel.Formulas.Select(formula => FormulaCompilationVisitor <TExecutableModel> .Compile(RuntimeModel, formula)).ToArray();

            _stepGraph = new LtmdpStepGraph();

            _cachedLabeledStates = new LtmdpCachedLabeledStates <TExecutableModel>(RuntimeModel, successorStateCapacity, _stepGraph, formulas);

            _ltmdpChoiceResolver = new LtmdpChoiceResolver(_stepGraph);
            ChoiceResolver       = _ltmdpChoiceResolver;
            RuntimeModel.SetChoiceResolver(ChoiceResolver);
        }
Example #16
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
        /// <param name="configuration">The analysis configuration that should be used.</param>
        internal LtmcExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, AnalysisConfiguration configuration)
            : base(runtimeModelCreator, 0, configuration)
        {
            var formulas = RuntimeModel.Formulas.Select(formula => FormulaCompilationVisitor <TExecutableModel> .Compile(RuntimeModel, formula)).ToArray();

            _transitions = new LtmcTransitionSetBuilder <TExecutableModel>(TemporaryStateStorage, configuration.SuccessorCapacity, formulas);

            var useForwardOptimization = configuration.EnableStaticPruningOptimization;

            _ltmcChoiceResolver = new LtmcChoiceResolver(useForwardOptimization);
            ChoiceResolver      = _ltmcChoiceResolver;
            RuntimeModel.SetChoiceResolver(ChoiceResolver);

            _allowFaultsOnInitialTransitions = configuration.AllowFaultsOnInitialTransitions;
        }
        /// <summary>
        ///   Checks the invariant encoded into the model created by <paramref name="createModel" />.
        /// </summary>
        public AnalysisResult <TExecutableModel> CheckInvariant(CoupledExecutableModelCreator <TExecutableModel> createModel, int formulaIndex)
        {
            // We have to track the state vector layout here; this will nondeterministically store some model instance of
            // one of the workers; but since all state vectors are the same, we don't care
            ExecutedModel <TExecutableModel>         model = null;
            Func <AnalysisModel <TExecutableModel> > createAnalysisModelFunc = () =>
                                                                               model = new ActivationMinimalExecutedModel <TExecutableModel>(createModel, 0, Configuration.SuccessorCapacity);
            var createAnalysisModel = new AnalysisModelCreator <TExecutableModel>(createAnalysisModelFunc);

            using (var checker = new InvariantChecker <TExecutableModel>(createAnalysisModel, OutputWritten, Configuration, formulaIndex))
            {
                var result = checker.Check();
                return(result);
            }
        }
        /// <summary>
        ///   Generates a <see cref="StateGraph{TExecutableModel}" /> for the model created by <paramref name="createModel" />.
        /// </summary>
        internal StateGraph <TExecutableModel> GenerateStateGraph(CoupledExecutableModelCreator <TExecutableModel> createModel)
        {
            // We have to track the state vector layout here; this will nondeterministically store some model instance of
            // one of the workers; but since all state vectors are the same, we don't care
            ExecutedModel <TExecutableModel>         model = null;
            Func <AnalysisModel <TExecutableModel> > createAnalysisModelFunc = () =>
                                                                               model = new ActivationMinimalExecutedModel <TExecutableModel>(createModel, 0, Configuration.SuccessorCapacity);
            var createAnalysisModel = new AnalysisModelCreator <TExecutableModel>(createAnalysisModelFunc);

            using (var checker = new StateGraphGenerator <TExecutableModel>(createAnalysisModel, OutputWritten, Configuration))
            {
                var stateGraph = checker.GenerateStateGraph();
                return(stateGraph);
            }
        }
Example #19
0
        public override AnalysisResult <SafetySharpRuntimeModel> CheckInvariant(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, Formula formula)
        {
            var formulaIndex = Array.FindIndex(createModel.StateFormulasToCheckInBaseModel, stateFormula =>
            {
                var isEqual = IsFormulasStructurallyEquivalentVisitor.Compare(stateFormula, formula);
                return(isEqual);
            }
                                               );

            if (formulaIndex == -1)
            {
                throw new Exception($"Input formula is not checked directly. Use {nameof(AnalysisTestsWithQualitative)} instead");
            }

            return(modelChecker.CheckInvariant(createModel, formulaIndex));
        }
Example #20
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
        /// <param name="formulas">The formulas that should be evaluated for each state.</param>
        /// <param name="configuration">The analysis configuration that should be used.</param>
        /// <param name="stateHeaderBytes">
        ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
        /// </param>
        internal ActivationMinimalExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, int stateHeaderBytes, Func <bool>[] formulas, AnalysisConfiguration configuration)
            : base(runtimeModelCreator, stateHeaderBytes, configuration)
        {
            formulas = formulas ?? RuntimeModel.Formulas.Select(formula => FormulaCompilationVisitor <TExecutableModel> .Compile(RuntimeModel, formula)).ToArray();

            _transitions      = new ActivationMinimalTransitionSetBuilder <TExecutableModel>(TemporaryStateStorage, configuration.SuccessorCapacity, formulas);
            _stateConstraints = RuntimeModel.StateConstraints;

            var useForwardOptimization = configuration.EnableStaticPruningOptimization;

            ChoiceResolver = new NondeterministicChoiceResolver(useForwardOptimization);
            FaultSet.CheckFaultCount(RuntimeModel.Faults.Length);

            RuntimeModel.SetChoiceResolver(ChoiceResolver);

            _allowFaultsOnInitialTransitions = configuration.AllowFaultsOnInitialTransitions;
        }
Example #21
0
        /// <summary>
        ///   Checks whether the <paramref name="formula" /> holds in all states of the <paramref name="model" />.
        /// </summary>
        /// <param name="createModel">The creator for the model that should be checked.</param>
        /// <param name="invariant">The invariant that should be checked.</param>
        internal InvariantAnalysisResult CheckInvariant(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, Formula invariant)
        {
            Requires.NotNull(createModel, nameof(createModel));
            Requires.NotNull(invariant, nameof(invariant));

            if (!invariant.IsStateFormula())
            {
                throw new InvalidOperationException("Invariants must be non-temporal state formulas.");
            }

            var transformationVisitor = new LtsMinLtlTransformer();

            transformationVisitor.Visit(invariant);

            return(Check(createModel,
                         $"--invariant=\"({ConstructionStateName} == 1) || ({transformationVisitor.TransformedFormula})\""));
        }
Example #22
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="context">The context of the traversal process.</param>
        /// <param name="transitionSizeInBytes">The size of a transition in bytes.</param>
        /// <param name="model">The runtime model the state graph is generated for.</param>
        /// <param name="createModel">
        ///   The factory function that should be used to create instances of the <see cref="RuntimeModel" />
        ///   the state graph is generated for.
        /// </param>
        internal StateGraph(TraversalContext context, int transitionSizeInBytes,
                            TExecutableModel model, CoupledExecutableModelCreator <TExecutableModel> createModel)
        {
            Requires.NotNull(context, nameof(context));

            TransitionSize      = transitionSizeInBytes;
            RuntimeModel        = model;
            RuntimeModelCreator = createModel;

            _stateStorage       = context.States;
            _transitionCapacity = context.ModelCapacity.MemoryLimitTransitions.Value;

            _transitionsBuffer.Resize(_transitionCapacity, zeroMemory: false);
            _stateMapBuffer.Resize(context.ModelCapacity.NumberOfStates * sizeof(TransitionRange), zeroMemory: false);

            _transitions = _transitionsBuffer.Pointer;
            _stateMap    = (TransitionRange *)_stateMapBuffer.Pointer;
        }
Example #23
0
        /// <summary>
        ///   Checks whether the <paramref name="formula" /> holds in all states of the <paramref name="model" />.
        /// </summary>
        /// <param name="createModel">The creator for the model that should be checked.</param>
        /// <param name="formula">The formula that should be checked.</param>
        public AnalysisResult <SafetySharpRuntimeModel> Check(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, Formula formula)
        {
            Requires.NotNull(createModel, nameof(createModel));
            Requires.NotNull(formula, nameof(formula));

            var visitor = new IsLtlFormulaVisitor();

            visitor.Visit(formula);

            if (!visitor.IsLtlFormula)
            {
                throw new NotSupportedException("CTL model checking is currently not supported with LtsMin.");
            }

            var transformationVisitor = new LtsMinLtlTransformer();

            transformationVisitor.Visit(new UnaryFormula(formula, UnaryOperator.Next));

            return(Check(createModel, $"--ltl=\"{transformationVisitor.TransformedFormula}\""));
        }
 public abstract InvariantAnalysisResult Check(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, Formula formula);
 /// <summary>
 ///   Initializes a new instance.
 /// </summary>
 /// <param name="runtimeModelCreator">A factory function that creates the model instance that should be executed.</param>
 /// <param name="stateHeaderBytes">
 ///   The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
 /// </param>
 /// <param name="successorStateCapacity">The maximum number of successor states supported per state.</param>
 internal ActivationMinimalExecutedModel(CoupledExecutableModelCreator <TExecutableModel> runtimeModelCreator, int stateHeaderBytes, long successorStateCapacity)
     : this(runtimeModelCreator, stateHeaderBytes, null, successorStateCapacity)
 {
 }
Example #26
0
        /// <summary>
        ///   Computes the minimal critical sets for the <paramref name="hazard" />.
        /// </summary>
        /// <param name="createModel">The creator for the model that should be checked.</param>
        /// <param name="hazard">The hazard the minimal critical sets should be computed for.</param>
        /// <param name="maxCardinality">
        ///   The maximum cardinality of the fault sets that should be checked. By default, all minimal
        ///   critical fault sets are determined.
        /// </param>
        public SafetyAnalysisResults <TExecutableModel> ComputeMinimalCriticalSets(CoupledExecutableModelCreator <TExecutableModel> createModel, Formula hazard, int maxCardinality = Int32.MaxValue)
        {
            Requires.NotNull(createModel, nameof(createModel));
            Requires.NotNull(hazard, nameof(hazard));

            ConsoleHelpers.WriteLine("Running Deductive Cause Consequence Analysis.");

            var heuristicWatch = new Stopwatch();
            var stopwatch      = new Stopwatch();

            stopwatch.Start();

            var allFaults = createModel.FaultsInBaseModel;

            FaultSet.CheckFaultCount(allFaults.Length);

            var forcedFaults           = allFaults.Where(fault => fault.Activation == Activation.Forced).ToArray();
            var suppressedFaults       = allFaults.Where(fault => fault.Activation == Activation.Suppressed).ToArray();
            var nondeterministicFaults = allFaults.Where(fault => fault.Activation == Activation.Nondeterministic).ToArray();
            var nonSuppressedFaults    = allFaults.Where(fault => fault.Activation != Activation.Suppressed).ToArray();

            ConsoleHelpers.WriteLine();
            ConsoleHelpers.WriteLine($"Of the {allFaults.Length} faults contained in the model,");
            ConsoleHelpers.WriteLine($"   {suppressedFaults.Length} faults are suppressed,");
            ConsoleHelpers.WriteLine($"   {forcedFaults.Length} faults are forced, and");
            ConsoleHelpers.WriteLine($"   {nondeterministicFaults.Length} faults are nondeterministically activated.");
            ConsoleHelpers.WriteLine();

            _suppressedSet = new FaultSet(suppressedFaults);
            _forcedSet     = new FaultSet(forcedFaults);

            var isComplete = true;

            // Remove information from previous analyses
            Reset(createModel.FaultsInBaseModel);

            // Initialize the backend, the model, and the analysis results
            switch (Backend)
            {
            case SafetyAnalysisBackend.FaultOptimizedOnTheFly:
                _backend = new FaultOptimizationBackend <TExecutableModel>();
                break;

            case SafetyAnalysisBackend.FaultOptimizedStateGraph:
                _backend = new StateGraphBackend <TExecutableModel>();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            _backend.Output = Output;
            _backend.InitializeModel(Configuration, createModel, hazard);
            _results = new SafetyAnalysisResults <TExecutableModel>(createModel, hazard, suppressedFaults, forcedFaults, Heuristics, FaultActivationBehavior);

            // Remember all safe sets of current cardinality - we need them to generate the next power set level
            var currentSafe = new HashSet <FaultSet>();

            // We check fault sets by increasing cardinality; this is, we check the empty set first, then
            // all singleton sets, then all sets with two elements, etc. We don't check sets that we
            // know are going to be critical sets due to monotonicity
            for (var cardinality = 0; cardinality <= nonSuppressedFaults.Length; ++cardinality)
            {
                // Generate the sets for the current level that we'll have to check
                var sets = GeneratePowerSetLevel(cardinality, nonSuppressedFaults, currentSafe);
                currentSafe.Clear();

                // Remove all sets that conflict with the forced or suppressed faults; these sets are considered to be safe.
                // If no sets remain, skip to the next level
                sets = RemoveInvalidSets(sets, currentSafe);
                if (sets.Count == 0)
                {
                    continue;
                }

                // Abort if we've exceeded the maximum fault set cardinality; doing the check here allows us
                // to report the analysis as complete if the maximum cardinality is never reached
                if (cardinality > maxCardinality)
                {
                    isComplete = false;
                    break;
                }

                if (cardinality == 0)
                {
                    ConsoleHelpers.WriteLine("Checking the empty fault set...");
                }
                else
                {
                    ConsoleHelpers.WriteLine($"Checking {sets.Count} sets of cardinality {cardinality}...");
                }

                // use heuristics
                var setsToCheck = new LinkedList <FaultSet>(sets);
                foreach (var heuristic in Heuristics)
                {
                    var count = setsToCheck.Count;

                    heuristicWatch.Restart();
                    heuristic.Augment((uint)cardinality, setsToCheck);

                    count = setsToCheck.Count - count;
                    if (count > 0)
                    {
                        ConsoleHelpers.WriteLine($"    {heuristic.GetType().Name} made {count} suggestions in {heuristicWatch.Elapsed.TotalMilliseconds}ms.");
                    }
                }

                // We have to check each set - heuristics may add further during the loop
                while (setsToCheck.Count > 0)
                {
                    var set = setsToCheck.First.Value;

                    var isCurrentLevel = sets.Remove(set);                     // returns true if set was actually contained
                    setsToCheck.RemoveFirst();

                    // for current level, we already know the set is valid
                    var isValid = isCurrentLevel || IsValid(set);

                    // the set is invalid if it exceeds the maximum cardinality level
                    isValid &= set.Cardinality <= maxCardinality;

                    var isSafe = true;
                    if (isValid)
                    {
                        isSafe = CheckSet(set, allFaults, !isCurrentLevel);
                    }

                    if (isSafe && isCurrentLevel)
                    {
                        currentSafe.Add(set);
                    }

                    // inform heuristics about result and give them the opportunity to add further sets
                    foreach (var heuristic in Heuristics)
                    {
                        heuristic.Update(setsToCheck, set, isSafe);
                    }

                    if (StopOnFirstException && _exceptions.Count > 0)
                    {
                        goto returnResult;
                    }
                }

                // in case heuristics removed a set (they shouldn't)
                foreach (var set in sets)
                {
                    var isSafe = CheckSet(set, allFaults, false);
                    if (isSafe)
                    {
                        currentSafe.Add(set);
                    }

                    if (StopOnFirstException && _exceptions.Count > 0)
                    {
                        goto returnResult;
                    }
                }
            }

returnResult:

            // Reset the nondeterministic faults so as to not influence subsequent analyses
            foreach (var fault in nondeterministicFaults)
            {
                fault.Activation = Activation.Nondeterministic;
            }

            // due to heuristics usage, we may have informatiuon on non-minimal critical sets
            var minimalCritical = RemoveNonMinimalCriticalSets();

            _results.IsComplete = isComplete;
            _results.Time       = stopwatch.Elapsed;
            _results.SetResult(minimalCritical, _checkedSetCount, _checkedSets, _counterExamples, _exceptions);

            return(_results);
        }
Example #27
0
 public QualitativeChecker(CoupledExecutableModelCreator <TExecutableModel> createModel)
 {
     ModelCreator = createModel;
 }
 public static ExecutableCounterExample <TExecutableModel> ExecutableCounterExample <TExecutableModel>(this InvariantAnalysisResult result, CoupledExecutableModelCreator <TExecutableModel> modelCreator) where TExecutableModel : ExecutableModel <TExecutableModel>
 {
     if (result.CounterExample != null)
     {
         return(new ExecutableCounterExample <TExecutableModel>(modelCreator.Create(0), result.CounterExample));
     }
     return(null);
 }
 public override InvariantAnalysisResult CheckInvariant(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, Formula formula)
 {
     return(_modelChecker.CheckInvariant(createModel, formula));
 }
 public override InvariantAnalysisResult[] CheckInvariants(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, params Formula[] invariants)
 {
     throw new NotImplementedException();
 }