Storm 2.0.0.3
A Modern Probabilistic Model Checker
Loading...
Searching...
No Matches
SparseDerivativeInstantiationModelChecker.cpp
Go to the documentation of this file.
10#include "storm/logic/Formula.h"
21#include "storm/utility/graph.h"
24
25namespace storm {
26namespace derivative {
27
28template<typename FunctionType>
30template<typename FunctionType>
32
33template<typename FunctionType, typename ConstantType>
34std::unique_ptr<modelchecker::ExplicitQuantitativeCheckResult<ConstantType>> SparseDerivativeInstantiationModelChecker<FunctionType, ConstantType>::check(
36 boost::optional<std::vector<ConstantType>> const& valueVector) {
37 std::vector<ConstantType> reachabilityProbabilities;
38 if (!valueVector.is_initialized()) {
40 instantiationModelChecker.specifyFormula(*currentCheckTask);
41 std::unique_ptr<storm::modelchecker::CheckResult> result = instantiationModelChecker.check(env, valuation);
42 reachabilityProbabilities = result->asExplicitQuantitativeCheckResult<ConstantType>().getFiniteValueVector();
43 } else {
44 STORM_LOG_ASSERT(valueVector->size() == model.getNumberOfStates(), "Size of reachability probability vector must be equal to the size of the model.");
45 reachabilityProbabilities = *valueVector;
46 }
47
48 // Convert reachabilityProbabilities into our format - we only care for the states of which the
49 // bits are 1 in the next vector. The order is kept, so doing this is fine:
50 std::vector<ConstantType> interestingReachabilityProbabilities;
51 for (uint64_t i = 0; i < reachabilityProbabilities.size(); i++) {
52 if (next.get(i)) {
53 interestingReachabilityProbabilities.push_back(reachabilityProbabilities[i]);
54 }
55 }
56 // Instantiate the matrices with the given instantiation
57
58 instantiationWatch.start();
59
60 // STORM_PRINT_AND_LOG(valuation << "\n");
61
62 // Write results into the placeholders
63 for (auto& functionResult : this->functionsUnderived) {
64 functionResult.second = storm::utility::parametric::evaluate<ConstantType>(functionResult.first, valuation);
65 }
66 for (auto& functionResult : this->functionsDerived.at(parameter)) {
67 functionResult.second = storm::utility::parametric::evaluate<ConstantType>(functionResult.first, valuation);
68 }
69
70 auto deltaConstrainedMatrixInstantiated = deltaConstrainedMatricesInstantiated->at(parameter);
71
72 // Write the instantiated values to the matrices and vectors according to the stored mappings
73 for (auto& entryValuePair : this->matrixMappingUnderived) {
74 entryValuePair.first->setValue(*(entryValuePair.second));
75 }
76 for (auto& entryValuePair : this->matrixMappingsDerived.at(parameter)) {
77 entryValuePair.first->setValue(*(entryValuePair.second));
78 }
79
80 std::vector<ConstantType> instantiatedDerivedOutputVec(derivedOutputVecs->at(parameter).size());
81 for (uint_fast64_t i = 0; i < derivedOutputVecs->at(parameter).size(); i++) {
82 instantiatedDerivedOutputVec[i] = storm::utility::parametric::evaluate<ConstantType>(derivedOutputVecs->at(parameter)[i], valuation);
83 }
84
85 instantiationWatch.stop();
86
87 approximationWatch.start();
88
89 std::vector<ConstantType> resultVec(interestingReachabilityProbabilities.size());
90 deltaConstrainedMatrixInstantiated.multiplyWithVector(interestingReachabilityProbabilities, resultVec);
91 for (uint_fast64_t i = 0; i < instantiatedDerivedOutputVec.size(); ++i) {
92 resultVec[i] += instantiatedDerivedOutputVec[i];
93 }
94
95 // Here's where the real magic happens - the solver call!
97 auto solver = factory.create(env);
98
99 // Calculate (1-M)^-1 * resultVec
100 // STORM_PRINT_AND_LOG(constrainedMatrixInstantiated << "\n");
101 // STORM_PRINT_AND_LOG("calling solver\n");
102 solver->setMatrix(constrainedMatrixInstantiated);
103 std::vector<ConstantType> finalResult(resultVec.size());
104 solver->solveEquations(env, finalResult, resultVec);
105
106 approximationWatch.stop();
107
108 return std::make_unique<modelchecker::ExplicitQuantitativeCheckResult<ConstantType>>(finalResult);
109}
110
111template<typename FunctionType, typename ConstantType>
114 this->currentFormula = checkTask.getFormula().asSharedPointer();
115 this->currentCheckTask = std::make_unique<storm::modelchecker::CheckTask<storm::logic::Formula, FunctionType>>(
116 checkTask.substituteFormula(*currentFormula).template convertValueType<FunctionType>());
117 this->parameters = storm::models::sparse::getProbabilityParameters(model);
118 if (checkTask.getFormula().isRewardOperatorFormula()) {
119 for (auto const& rewardParameter : storm::models::sparse::getRewardParameters(model)) {
120 this->parameters.insert(rewardParameter);
121 }
122 }
123 storm::logic::OperatorInformation opInfo(boost::none, boost::none);
124 if (checkTask.getFormula().isRewardOperatorFormula()) {
125 model.reduceToStateBasedRewards();
126 } else {
127 /* this->formulaWithoutBound = std::make_shared<storm::logic::ProbabilityOperatorFormula>( */
128 /* formula->asProbabilityOperatorFormula().getSubformula().asSharedPointer(), opInfo); */
129 }
130
131 generalSetupWatch.start();
132
134
136
137 std::map<VariableType<FunctionType>, storage::SparseMatrix<FunctionType>> equationSystems;
138 // Get initial and target states
140 storage::BitVector target;
141 storage::BitVector avoid(model.getNumberOfStates());
142 if (this->currentFormula->isRewardOperatorFormula()) {
144 this->currentFormula->asRewardOperatorFormula().getSubformula().asEventuallyFormula().getSubformula());
145 target = propositionalChecker.check(subformula)->template asExplicitQualitativeCheckResult<FunctionType>().getTruthValuesVector();
146 } else {
147 if (this->currentFormula->asProbabilityOperatorFormula().getSubformula().isUntilFormula()) {
149 this->currentFormula->asProbabilityOperatorFormula().getSubformula().asUntilFormula().getRightSubformula());
151 this->currentFormula->asProbabilityOperatorFormula().getSubformula().asUntilFormula().getLeftSubformula());
152 target = propositionalChecker.check(rightSubformula)->template asExplicitQualitativeCheckResult<FunctionType>().getTruthValuesVector();
153 avoid = propositionalChecker.check(leftSubformula)->template asExplicitQualitativeCheckResult<FunctionType>().getTruthValuesVector();
154 avoid.complement();
155 } else {
157 this->currentFormula->asProbabilityOperatorFormula().getSubformula().asEventuallyFormula().getSubformula());
158 target = propositionalChecker.check(subformula)->template asExplicitQualitativeCheckResult<FunctionType>().getTruthValuesVector();
159 }
160 }
161 initialStateModel = model.getStates("init").getNextSetIndex(0);
162
163 if (!checkTask.getFormula().isRewardOperatorFormula()) {
164 next = target;
165 next.complement();
166
167 avoid.complement();
168 next &= avoid;
169
170 storm::storage::BitVector atSomePointTarget =
171 storm::utility::graph::performProbGreater0(model.getBackwardTransitions(), storm::storage::BitVector(model.getNumberOfStates(), true), target);
172 next &= atSomePointTarget;
173 } else {
174 next = target;
175 next.complement();
176
177 avoid.complement();
178 next &= avoid;
179
180 storm::storage::BitVector targetProbOne =
181 storm::utility::graph::performProb1(model.getBackwardTransitions(), storm::storage::BitVector(model.getNumberOfStates(), true), target);
182 next &= targetProbOne;
183 }
184
185 auto transitionMatrix = model.getTransitionMatrix();
186 std::map<uint_fast64_t, uint_fast64_t> stateNumToEquationSystemRow;
187 uint_fast64_t newRow = 0;
188 for (uint_fast64_t row = 0; row < transitionMatrix.getRowCount(); ++row) {
189 if (!next.get(row)) {
190 continue;
191 }
192 stateNumToEquationSystemRow[row] = newRow;
193 newRow++;
194 }
195 initialStateEqSystem = stateNumToEquationSystemRow[initialStateModel];
196 storage::SparseMatrix<FunctionType> constrainedMatrix = transitionMatrix.getSubmatrix(false, next, next, true);
197 // If necessary, convert the matrix from the fixpoint notation to the form needed for the equation system.
198 this->constrainedMatrixEquationSystem = constrainedMatrix;
199 if (convertToEquationSystem) {
200 // go from x = A*x + b to (I-A)x = b.
201 constrainedMatrixEquationSystem.convertToEquationSystem();
202 }
203
204 // Setup instantiated constrained matrix
205 storage::SparseMatrixBuilder<ConstantType> instantiatedSystemBuilder;
206 const ConstantType dummyValue = storm::utility::one<ConstantType>();
207 for (uint_fast64_t row = 0; row < constrainedMatrixEquationSystem.getRowCount(); ++row) {
208 for (auto const& entry : constrainedMatrixEquationSystem.getRow(row)) {
209 instantiatedSystemBuilder.addNextValue(row, entry.getColumn(), dummyValue);
210 }
211 }
212 constrainedMatrixInstantiated = instantiatedSystemBuilder.build();
213 initializeInstantiatedMatrix(constrainedMatrixEquationSystem, constrainedMatrixInstantiated, matrixMappingUnderived, functionsUnderived);
214 // The resulting equation systems
215 this->deltaConstrainedMatrices = std::make_unique<std::map<VariableType<FunctionType>, storage::SparseMatrix<FunctionType>>>();
216 this->deltaConstrainedMatricesInstantiated = std::make_unique<std::map<VariableType<FunctionType>, storage::SparseMatrix<ConstantType>>>();
217 this->derivedOutputVecs = std::make_unique<std::map<VariableType<FunctionType>, std::vector<FunctionType>>>();
218
219 // The following is a nessecary optimization for deriving the constrainedMatrix w.r.t. all parameters.
220 // We will traverse the constrainedMatrix once and inspect all entries, counting their number of parameters.
221 // Then, we will insert the correct polynomials into the correct matrix builders.
222 std::map<VariableType<FunctionType>, storage::SparseMatrixBuilder<FunctionType>> matrixBuilders;
223 std::map<VariableType<FunctionType>, storage::SparseMatrixBuilder<ConstantType>> instantiatedMatrixBuilders;
224 for (auto const& var : this->parameters) {
225 matrixBuilders[var] = storage::SparseMatrixBuilder<FunctionType>(constrainedMatrix.getRowCount());
226 instantiatedMatrixBuilders[var] = storage::SparseMatrixBuilder<ConstantType>(constrainedMatrix.getRowCount());
227 }
228
229 for (uint_fast64_t row = 0; row < constrainedMatrix.getRowCount(); ++row) {
230 for (storage::MatrixEntry<uint_fast64_t, storm::RationalFunction> const& entry : constrainedMatrix.getRow(row)) {
231 const storm::RationalFunction rationalFunction = entry.getValue();
232 auto variables = rationalFunction.gatherVariables();
233 for (auto const& var : variables) {
234 matrixBuilders.at(var).addNextValue(row, entry.getColumn(), rationalFunction.derivative(var));
235 instantiatedMatrixBuilders.at(var).addNextValue(row, entry.getColumn(), dummyValue);
236 }
237 }
238 }
239
240 for (auto const& var : this->parameters) {
241 auto builtMatrix = matrixBuilders[var].build();
242 auto builtMatrixInstantiated = instantiatedMatrixBuilders[var].build();
243 initializeInstantiatedMatrix(builtMatrix, builtMatrixInstantiated, matrixMappingsDerived[var], functionsDerived[var]);
244 deltaConstrainedMatrices->emplace(var, std::move(builtMatrix));
245 deltaConstrainedMatricesInstantiated->emplace(var, std::move(builtMatrixInstantiated));
246 }
247
248 for (auto const& var : this->parameters) {
249 (*derivedOutputVecs)[var] = std::vector<FunctionType>(constrainedMatrix.getRowCount());
250 }
251
252 // storage::BitVector constrainedTarget(next.size());
253 // for (uint_fast64_t i = 0; i < transitionMatrix.getRowCount(); i++) {
254 // if (!stateNumToEquationSystemRow.count(i)) continue;
255 // constrainedTarget.set(stateNumToEquationSystemRow[i], target[i]);
256 // }
257
258 for (uint_fast64_t state = 0; state < transitionMatrix.getRowCount(); ++state) {
259 if (!stateNumToEquationSystemRow.count(state)) {
260 continue;
261 }
262 uint_fast64_t row = stateNumToEquationSystemRow[state];
263 // PROBABILITY -> For every state, the one-step probability to reach the target goes into the output vector
264 // REWARD -> For every state, the reward goes into the output vector
265 FunctionType rationalFunction;
266 if (!checkTask.getFormula().isRewardOperatorFormula()) {
267 FunctionType vectorValue = utility::zero<FunctionType>();
268 for (auto const& entry : transitionMatrix.getRow(state)) {
269 if (target.get(entry.getColumn())) {
270 vectorValue += entry.getValue();
271 }
272 }
273 rationalFunction = vectorValue;
274 } else {
275 std::vector<FunctionType> stateRewards;
276 if (checkTask.isRewardModelSet()) {
277 stateRewards = model.getRewardModel(checkTask.getRewardModel()).getStateRewardVector();
278 } else {
279 stateRewards = model.getRewardModel("").getStateRewardVector();
280 }
281
282 rationalFunction = stateRewards[state];
283 }
284 for (auto const& var : rationalFunction.gatherVariables()) {
285 (*derivedOutputVecs)[var][row] = rationalFunction.derivative(var);
286 }
287 }
288
289 generalSetupWatch.stop();
290
291 // for (auto const& param : this->parameters) {
292 // this->linearEquationSolvers[param] = factory.create(env);
293 // // this->linearEquationSolvers[param]->setCachingEnabled(true);
294 // // std::unique_ptr<solver::TerminationCondition<ConstantType>> terminationCondition =
295 // // std::make_unique<SignedGradientDescentTerminationCondition<ConstantType>>(initialState);
296 // // this->linearEquationSolvers[param]->setTerminationCondition(std::move(terminationCondition));
297 // }
298}
299
300template<typename FunctionType, typename ConstantType>
301void SparseDerivativeInstantiationModelChecker<FunctionType, ConstantType>::initializeInstantiatedMatrix(
303 std::vector<std::pair<typename storm::storage::SparseMatrix<ConstantType>::iterator, ConstantType*>>& matrixMapping,
304 std::unordered_map<FunctionType, ConstantType>& functions) {
305 ConstantType dummyValue = storm::utility::one<ConstantType>();
306 auto constantEntryIt = matrixInstantiated.begin();
307 auto parametricEntryIt = matrix.begin();
308 while (parametricEntryIt != matrix.end()) {
309 STORM_LOG_ASSERT(parametricEntryIt->getColumn() == constantEntryIt->getColumn(),
310 "Entries of parametric and constant matrix are not at the same position.");
311 if (storm::utility::isConstant(parametricEntryIt->getValue())) {
312 // Constant entries can be inserted directly
313 constantEntryIt->setValue(storm::utility::convertNumber<ConstantType>(parametricEntryIt->getValue()));
314 // STORM_PRINT_AND_LOG("Setting constant entry\n");
315 } else {
316 // insert the new function and store that the current constantMatrix entry needs to be set to the value of this function
317 auto functionsIt = functions.insert(std::make_pair(parametricEntryIt->getValue(), dummyValue)).first;
318 matrixMapping.emplace_back(std::make_pair(constantEntryIt, &(functionsIt->second)));
319 // Note that references to elements of an unordered map remain valid after calling unordered_map::insert.
320 // STORM_PRINT_AND_LOG("Setting non-constant entry\n");
321 }
322 ++constantEntryIt;
323 ++parametricEntryIt;
324 }
325 STORM_LOG_ASSERT(constantEntryIt == matrixInstantiated.end(), "Parametric matrix seems to have more or less entries then the constant matrix.");
326}
327
330} // namespace derivative
331} // namespace storm
std::unique_ptr< modelchecker::ExplicitQuantitativeCheckResult< ConstantType > > check(Environment const &env, storm::utility::parametric::Valuation< FunctionType > const &valuation, typename utility::parametric::VariableType< FunctionType >::type const &parameter, boost::optional< std::vector< ConstantType > > const &valueVector=boost::none)
check calculates the deriative of the model w.r.t.
void specifyFormula(Environment const &env, modelchecker::CheckTask< logic::Formula, FunctionType > const &checkTask)
specifyFormula specifies a CheckTask.
virtual std::unique_ptr< CheckResult > check(Environment const &env, CheckTask< storm::logic::Formula, SolutionType > const &checkTask)
Checks the provided formula.
CheckTask< NewFormulaType, ValueType > substituteFormula(NewFormulaType const &newFormula) const
Copies the check task from the source while replacing the formula with the new one.
Definition CheckTask.h:54
bool isRewardModelSet() const
Retrieves whether a reward model was set.
Definition CheckTask.h:192
std::string const & getRewardModel() const
Retrieves the reward model over which to perform the checking (if set).
Definition CheckTask.h:199
FormulaType const & getFormula() const
Retrieves the formula from this task.
Definition CheckTask.h:142
Class to efficiently check a formula on a parametric model with different parameter instantiations.
virtual std::unique_ptr< CheckResult > check(Environment const &env, storm::utility::parametric::Valuation< typename SparseModelType::ValueType > const &valuation) override
void specifyFormula(CheckTask< storm::logic::Formula, typename SparseModelType::ValueType > const &checkTask)
virtual std::unique_ptr< LinearEquationSolver< ValueType > > create(Environment const &env) const override
Creates an equation solver with the current settings, but without a matrix.
virtual LinearEquationSolverProblemFormat getEquationProblemFormat(Environment const &env) const
Retrieves the problem format that the solver expects if it was created with the current settings.
A bit vector that is internally represented as a vector of 64-bit values.
Definition BitVector.h:16
void complement()
Negates all bits in the bit vector.
bool get(uint64_t index) const
Retrieves the truth value of the bit at the given index and performs a bound check.
A class that can be used to build a sparse matrix by adding value by value.
void addNextValue(index_type row, index_type column, value_type const &value)
Sets the matrix entry at the given row and column to the given value.
SparseMatrix< value_type > build(index_type overriddenRowCount=0, index_type overriddenColumnCount=0, index_type overriddenRowGroupCount=0)
A class that holds a possibly non-square matrix in the compressed row storage format.
const_rows getRow(index_type row) const
Returns an object representing the given row.
SparseMatrix getSubmatrix(bool useGroups, storm::storage::BitVector const &rowConstraint, storm::storage::BitVector const &columnConstraint, bool insertDiagonalEntries=false, storm::storage::BitVector const &makeZeroColumns=storm::storage::BitVector()) const
Creates a submatrix of the current matrix by dropping all rows and columns whose bits are not set to ...
const_iterator begin(index_type row) const
Retrieves an iterator that points to the beginning of the given row.
const_iterator end(index_type row) const
Retrieves an iterator that points past the end of the given row.
std::vector< MatrixEntry< index_type, value_type > >::iterator iterator
index_type getRowCount() const
Returns the number of rows of the matrix.
#define STORM_LOG_ASSERT(cond, message)
Definition macros.h:9
typename utility::parametric::CoefficientType< FunctionType >::type CoefficientType
typename utility::parametric::VariableType< FunctionType >::type VariableType
std::set< storm::RationalFunctionVariable > getRewardParameters(Model< storm::RationalFunction > const &model)
Get all parameters occurring in rewards.
Definition Model.cpp:736
std::set< storm::RationalFunctionVariable > getProbabilityParameters(Model< storm::RationalFunction > const &model)
Get all probability parameters occurring on transitions.
Definition Model.cpp:732
storm::storage::BitVector performProbGreater0(storm::storage::SparseMatrix< T > const &backwardTransitions, storm::storage::BitVector const &phiStates, storm::storage::BitVector const &psiStates, bool useStepBound, uint_fast64_t maximalSteps)
Performs a backward depth-first search trough the underlying graph structure of the given model to de...
Definition graph.cpp:316
storm::storage::BitVector performProb1(storm::storage::SparseMatrix< T > const &backwardTransitions, storm::storage::BitVector const &, storm::storage::BitVector const &psiStates, storm::storage::BitVector const &statesWithProbabilityGreater0)
Computes the set of states of the given model for which all paths lead to the given set of target sta...
Definition graph.cpp:377
std::map< typename VariableType< FunctionType >::type, typename CoefficientType< FunctionType >::type > Valuation
Definition parametric.h:43
double evaluate(storm::RationalFunction const &function, Valuation< storm::RationalFunction > const &valuation)
bool isConstant(ValueType const &)
ValueType zero()
Definition constants.cpp:26
ValueType one()
Definition constants.cpp:21
TargetType convertNumber(SourceType const &number)
The contract of a DD backend.
carl::RationalFunction< Polynomial, true > RationalFunction