Storm 2.0.0.3
A Modern Probabilistic Model Checker
Loading...
Searching...
No Matches
JaniNextStateGenerator.cpp
Go to the documentation of this file.
2
3#include <memory>
4
33
34namespace storm {
35namespace generator {
36
41template<typename ValueType, typename StateType>
44
45 std::vector<uint64_t> locations;
47 std::vector<typename Generator::AutomataEdgeSets> automataEdgeSets; // one entry for each element of 'edges'
48 std::vector<typename Generator::EdgeSetWithIndices::const_iterator> iteratorList;
49 std::vector<typename Generator::EdgeSetWithIndices const*> edgeSets;
50 std::vector<typename Generator::EdgeSetWithIndices::const_iterator> firstEnabledEdgeIterators;
52 std::vector<storm::jani::EdgeDestination const*> destinations;
53 std::vector<LocationVariableInformation const*> locationVars;
55 // The state whose (non-transient) variable values are currently stored in the evaluator while a state is expanded. See
56 // JaniNextStateGenerator::setEvaluatorState.
58
59 // The expressions of the (non-transient) variables (location, boolean, integer variables in that order).
60 // Only used by evaluatorHoldsState (i.e., in assertions). Caching them avoids that the evaluator has to compile the expressions over and over again.
61 std::vector<storm::expressions::Expression> variableExpressionsForAssertions;
62};
63
64template<typename ValueType, typename StateType>
66 : JaniNextStateGenerator(model.substituteConstantsFunctionsTranscendentals(), options, false) {
67 // Intentionally left empty.
68}
69
70template<typename ValueType, typename StateType>
72 : NextStateGenerator<ValueType, StateType>(model.getExpressionManager(), options),
73 model(model),
74 rewardExpressions(),
75 hasStateActionRewards(false),
76 evaluateRewardExpressionsAtEdges(false),
77 evaluateRewardExpressionsAtDestinations(false),
78 scratch(std::make_unique<JaniNextStateGeneratorScratchMemory<ValueType, StateType>>()) {
79 auto features = this->model.getModelFeatures();
84 // Eliminate arrays if necessary.
85 if (features.hasArrays()) {
86 arrayEliminatorData = this->model.eliminateArrays(true);
87 this->options.substituteExpressions([this](storm::expressions::Expression const& exp) { return arrayEliminatorData.transformExpression(exp); });
88 features.remove(storm::jani::ModelFeature::Arrays);
89 }
90 STORM_LOG_THROW(features.empty(), storm::exceptions::NotSupportedException,
91 "The explicit next-state generator does not support the following model feature(s): " << features.toString() << ".");
92 // Simplify the system compositions so that we can exclude the case where automata appear in the composition multiple times.
93 this->model.simplifyComposition();
94
95 // Get the reward expressions to be build. Also find out whether there is a non-trivial one.
96 bool hasNonTrivialRewardExpressions = false;
97 if (this->options.isBuildAllRewardModelsSet()) {
98 rewardExpressions = this->model.getAllRewardModelExpressions();
99 hasNonTrivialRewardExpressions = this->model.hasNonTrivialRewardExpression();
100 } else {
101 // Extract the reward models from the model based on the names we were given.
102 for (auto const& rewardModelName : this->options.getRewardModelNames()) {
103 rewardExpressions.emplace_back(rewardModelName, this->model.getRewardModelExpression(rewardModelName));
104 hasNonTrivialRewardExpressions = hasNonTrivialRewardExpressions || this->model.isNonTrivialRewardModelExpression(rewardModelName);
105 }
106 }
107 // If a transient variable has a non-zero default value, we also consider that non-trivial.
108 // In those cases, lifting edge destination assignments to the edges would mean that reward is collected twice:
109 // once at the edge (assigned value), once at the edge destinations (default value).
110 if (!hasNonTrivialRewardExpressions) {
111 for (auto const& rewExpr : rewardExpressions) {
112 STORM_LOG_ASSERT(rewExpr.second.isVariable(), "Expected trivial reward expression to be a variable. Got " << rewExpr.second << " instead.");
113 auto const& var = this->model.getGlobalVariables().getVariable(rewExpr.second.getBaseExpression().asVariableExpression().getVariable());
114 if (var.isTransient() && var.hasInitExpression() && !storm::utility::isZero(var.getInitExpression().evaluateAsRational())) {
115 hasNonTrivialRewardExpressions = true;
116 break;
117 }
118 }
119 }
120
121 // We try to lift the edge destination assignments to the edges as this reduces the number of evaluator calls.
122 // However, this will only be helpful if there are no assignment levels and only trivial reward expressions.
123 if (hasNonTrivialRewardExpressions || this->model.usesAssignmentLevels()) {
125 } else {
126 this->model.liftTransientEdgeDestinationAssignments(storm::jani::AssignmentLevelFinder().getLowestAssignmentLevel(this->model));
127 evaluateRewardExpressionsAtEdges = true;
128 }
129
130 // Create all synchronization-related information, e.g. the automata that are put in parallel.
131 this->createSynchronizationInformation();
132
133 // Now we are ready to initialize the variable information.
134 this->checkValid();
135 this->variableInformation =
136 VariableInformation(this->model, this->parallelAutomata, options.getReservedBitsForUnboundedVariables(), options.isAddOutOfBoundsStateSet());
137 this->variableInformation.registerArrayVariableReplacements(arrayEliminatorData);
138 this->transientVariableInformation = TransientVariableInformation<ValueType>(this->model, this->parallelAutomata);
139 this->transientVariableInformation.registerArrayVariableReplacements(arrayEliminatorData);
140 this->initializeSpecialStates();
141
142 // Create a proper evaluator.
143 this->evaluator = std::make_unique<storm::expressions::ExpressionEvaluator<ValueType>>(this->model.getManager());
144 this->transientVariableInformation.setDefaultValuesInEvaluator(*this->evaluator);
145
146 // Build the information structs for the reward models.
147 buildRewardModelInformation();
148
149 // If there are terminal states we need to handle, we now need to translate all labels to expressions.
150 if (this->options.hasTerminalStates()) {
151 for (auto const& expressionOrLabelAndBool : this->options.getTerminalStates()) {
152 if (expressionOrLabelAndBool.first.isExpression()) {
153 this->terminalStates.emplace_back(expressionOrLabelAndBool.first.getExpression(), expressionOrLabelAndBool.second);
154 } else {
155 // If it's a label, i.e. refers to a transient boolean variable we do some sanity checks first
156 if (!this->isSpecialLabel(expressionOrLabelAndBool.first.getLabel())) {
157 STORM_LOG_THROW(this->model.getGlobalVariables().hasVariable(expressionOrLabelAndBool.first.getLabel()),
158 storm::exceptions::InvalidArgumentException,
159 "Terminal states refer to illegal label '" << expressionOrLabelAndBool.first.getLabel() << "'.");
160
161 storm::jani::Variable const& variable = this->model.getGlobalVariables().getVariable(expressionOrLabelAndBool.first.getLabel());
163 storm::exceptions::InvalidArgumentException,
164 "Terminal states refer to non-boolean variable '" << expressionOrLabelAndBool.first.getLabel() << "'.");
165 STORM_LOG_THROW(variable.isTransient(), storm::exceptions::InvalidArgumentException,
166 "Terminal states refer to non-transient variable '" << expressionOrLabelAndBool.first.getLabel() << "'.");
167
168 this->terminalStates.emplace_back(variable.getExpressionVariable().getExpression(), expressionOrLabelAndBool.second);
169 }
170 }
171 }
172 }
173}
174
175// Declared (instead of implicitly defaulted) in the header, because JaniNextStateGeneratorScratchMemory is incomplete there; defined here, where it is
176// complete, so that std::unique_ptr<JaniNextStateGeneratorScratchMemory<...>> can be destructed.
177template<typename ValueType, typename StateType>
178JaniNextStateGenerator<ValueType, StateType>::~JaniNextStateGenerator() = default;
179
180template<typename ValueType, typename StateType>
188 // We do not add Functions as these should ideally be substituted before creating this generator.
189 // This is because functions may also occur in properties and the user of this class should take care of that.
190 return features;
191}
192
193template<typename ValueType, typename StateType>
195 auto features = model.getModelFeatures();
196 features.remove(storm::jani::ModelFeature::Arrays);
198 features.remove(storm::jani::ModelFeature::Functions); // can be substituted
202 if (!features.empty()) {
203 STORM_LOG_INFO("The model can not be build as it contains these unsupported features: " << features.toString());
204 return false;
205 }
206 // There probably are more cases where the model is unsupported. However, checking these is more involved.
207 // As this method is supposed to be a quick check, we just return true at this point.
208 return true;
209}
210
211template<typename ValueType, typename StateType>
213 switch (model.getModelType()) {
215 return ModelType::DTMC;
217 return ModelType::CTMC;
219 return ModelType::MDP;
221 return ModelType::MA;
222 default:
223 STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Invalid model type.");
224 }
225}
226
227template<typename ValueType, typename StateType>
229 return model.isDeterministicModel();
230}
231
232template<typename ValueType, typename StateType>
234 return model.isDiscreteTimeModel();
235}
236
237template<typename ValueType, typename StateType>
241
242template<typename ValueType, typename StateType>
243uint64_t JaniNextStateGenerator<ValueType, StateType>::getLocation(CompressedState const& state, LocationVariableInformation const& locationVariable) const {
244 if (locationVariable.bitWidth == 0) {
245 return 0;
246 } else {
247 return state.getAsInt(locationVariable.bitOffset, locationVariable.bitWidth);
248 }
249}
250
251template<typename ValueType, typename StateType>
252void JaniNextStateGenerator<ValueType, StateType>::setLocation(CompressedState& state, LocationVariableInformation const& locationVariable,
253 uint64_t locationIndex) const {
254 if (locationVariable.bitWidth != 0) {
255 state.setFromInt(locationVariable.bitOffset, locationVariable.bitWidth, locationIndex);
256 }
257}
258
259template<typename ValueType, typename StateType>
260std::vector<uint64_t> JaniNextStateGenerator<ValueType, StateType>::getLocations(CompressedState const& state) const {
261 std::vector<uint64_t> result;
262 getLocations(state, result);
263 return result;
264}
265
266template<typename ValueType, typename StateType>
267void JaniNextStateGenerator<ValueType, StateType>::getLocations(CompressedState const& state, std::vector<uint64_t>& result) const {
268 result.resize(this->variableInformation.locationVariables.size());
269
270 auto resultIt = result.begin();
271 for (auto it = this->variableInformation.locationVariables.begin(), ite = this->variableInformation.locationVariables.end(); it != ite; ++it, ++resultIt) {
272 if (it->bitWidth == 0) {
273 *resultIt = 0;
274 } else {
275 *resultIt = state.getAsInt(it->bitOffset, it->bitWidth);
276 }
277 }
278}
279
280template<typename ValueType, typename StateType>
282 std::vector<StateType> initialStateIndices;
283
284 if (this->model.hasNonTrivialInitialStates()) {
285 // Prepare an SMT solver to enumerate all initial states.
286 std::unique_ptr<storm::solver::SmtSolver> solver = storm::utility::solver::getSmtSolver(model.getExpressionManager());
287
288 std::vector<storm::expressions::Expression> rangeExpressions = model.getAllRangeExpressions(this->parallelAutomata);
289 for (auto const& expression : rangeExpressions) {
290 solver->add(expression);
291 }
292 solver->add(model.getInitialStatesExpression(this->parallelAutomata));
293
294 // Proceed as long as the solver can still enumerate initial states.
296 // Create fresh state.
297 CompressedState initialState(this->variableInformation.getTotalBitOffset(true));
298
299 // Read variable assignment from the solution of the solver. Also, create an expression we can use to
300 // prevent the variable assignment from being enumerated again.
301 storm::expressions::Expression blockingExpression;
302 std::shared_ptr<storm::solver::SmtSolver::ModelReference> model = solver->getModel();
303 for (auto const& booleanVariable : this->variableInformation.booleanVariables) {
304 bool variableValue = model->getBooleanValue(booleanVariable.variable);
305 storm::expressions::Expression localBlockingExpression = variableValue ? !booleanVariable.variable : booleanVariable.variable;
306 blockingExpression = blockingExpression.isInitialized() ? blockingExpression || localBlockingExpression : localBlockingExpression;
307 initialState.set(booleanVariable.bitOffset, variableValue);
308 }
309 for (auto const& integerVariable : this->variableInformation.integerVariables) {
310 int_fast64_t variableValue = model->getIntegerValue(integerVariable.variable);
311 if (integerVariable.forceOutOfBoundsCheck || this->getOptions().isExplorationChecksSet()) {
312 STORM_LOG_THROW(variableValue >= integerVariable.lowerBound, storm::exceptions::WrongFormatException,
313 "The initial value for variable " << integerVariable.variable.getName() << " is lower than the lower bound.");
314 STORM_LOG_THROW(variableValue <= integerVariable.upperBound, storm::exceptions::WrongFormatException,
315 "The initial value for variable " << integerVariable.variable.getName() << " is higher than the upper bound.");
316 }
317 storm::expressions::Expression localBlockingExpression = integerVariable.variable != model->getManager().integer(variableValue);
318 blockingExpression = blockingExpression.isInitialized() ? blockingExpression || localBlockingExpression : localBlockingExpression;
319 initialState.setFromInt(integerVariable.bitOffset, integerVariable.bitWidth,
320 static_cast<uint_fast64_t>(variableValue - integerVariable.lowerBound));
321 }
322
323 // Gather iterators to the initial locations of all the automata.
324 std::vector<std::set<uint64_t>::const_iterator> initialLocationsIts;
325 std::vector<std::set<uint64_t>::const_iterator> initialLocationsItes;
326 for (auto const& automatonRef : this->parallelAutomata) {
327 auto const& automaton = automatonRef.get();
328 initialLocationsIts.push_back(automaton.getInitialLocationIndices().cbegin());
329 initialLocationsItes.push_back(automaton.getInitialLocationIndices().cend());
330 }
332 initialLocationsIts, initialLocationsItes,
333 [this, &initialState](uint64_t index, uint64_t value) { setLocation(initialState, this->variableInformation.locationVariables[index], value); },
334 [&stateToIdCallback, &initialStateIndices, &initialState]() {
335 // Register initial state.
336 StateType id = stateToIdCallback(initialState);
337 initialStateIndices.push_back(id);
338 return true;
339 });
340
341 // Block the current initial state to search for the next one.
342 if (!blockingExpression.isInitialized()) {
343 break;
344 }
345 solver->add(blockingExpression);
346 }
347
348 STORM_LOG_DEBUG("Enumerated " << initialStateIndices.size() << " initial states using SMT solving.");
349 } else {
350 // Create vectors holding all possible values
351 std::vector<std::vector<uint64_t>> allValues;
352 for (auto const& aRef : this->parallelAutomata) {
353 auto const& aInitLocs = aRef.get().getInitialLocationIndices();
354 allValues.emplace_back(aInitLocs.begin(), aInitLocs.end());
355 }
356 uint64_t locEndIndex = allValues.size();
357 for (auto const& intVar : this->variableInformation.integerVariables) {
358 STORM_LOG_ASSERT(intVar.lowerBound <= intVar.upperBound, "Expecting variable with non-empty set of possible values.");
359 // The value of integer variables is shifted so that 0 is always the smallest possible value
360 allValues.push_back(storm::utility::vector::buildVectorForRange<uint64_t>(static_cast<uint64_t>(0), intVar.upperBound + 1 - intVar.lowerBound));
361 }
362 uint64_t intEndIndex = allValues.size();
363 // For boolean variables we consider the values 0 and 1.
364 allValues.resize(allValues.size() + this->variableInformation.booleanVariables.size(),
365 std::vector<uint64_t>({static_cast<uint64_t>(0), static_cast<uint64_t>(1)}));
366
367 std::vector<std::vector<uint64_t>::const_iterator> its;
368 std::vector<std::vector<uint64_t>::const_iterator> ites;
369 for (auto const& valVec : allValues) {
370 its.push_back(valVec.cbegin());
371 ites.push_back(valVec.cend());
372 }
373
374 // Now create an initial state for each combination of values
375 CompressedState initialState(this->variableInformation.getTotalBitOffset(true));
377 its, ites,
378 [this, &initialState, &locEndIndex, &intEndIndex](uint64_t index, uint64_t value) {
379 // Set the value for the variable corresponding to the given index
380 if (index < locEndIndex) {
381 // Location variable
382 setLocation(initialState, this->variableInformation.locationVariables[index], value);
383 } else if (index < intEndIndex) {
384 // Integer variable
385 auto const& intVar = this->variableInformation.integerVariables[index - locEndIndex];
386 initialState.setFromInt(intVar.bitOffset, intVar.bitWidth, value);
387 } else {
388 // Boolean variable
389 STORM_LOG_ASSERT(index - intEndIndex < this->variableInformation.booleanVariables.size(), "Unexpected index.");
390 auto const& boolVar = this->variableInformation.booleanVariables[index - intEndIndex];
391 STORM_LOG_ASSERT(value <= 1u, "Unexpected value for boolean variable.");
392 initialState.set(boolVar.bitOffset, static_cast<bool>(value));
393 }
394 },
395 [&stateToIdCallback, &initialStateIndices, &initialState]() {
396 // Register initial state.
397 StateType id = stateToIdCallback(initialState);
398 initialStateIndices.push_back(id);
399 return true; // Keep on exploring
400 });
401 STORM_LOG_DEBUG("Enumerated " << initialStateIndices.size() << " initial states using brute force enumeration.");
402 }
403 return initialStateIndices;
404}
405
406template<typename ValueType, typename StateType>
407void JaniNextStateGenerator<ValueType, StateType>::applyUpdate(CompressedState& state, storm::jani::EdgeDestination const& destination,
408 storm::generator::LocationVariableInformation const& locationVariable, int64_t assignmentLevel,
409 storm::expressions::ExpressionEvaluator<ValueType> const& expressionEvaluator) {
410 // Update the location of the state.
411 setLocation(state, locationVariable, destination.getLocationIndex());
412
413 // Then perform the assignments.
414 auto const& assignments = destination.getOrderedAssignments().getNonTransientAssignments(assignmentLevel);
415 auto assignmentIt = assignments.begin();
416 auto assignmentIte = assignments.end();
417
418 // Iterate over all boolean assignments and carry them out.
419 auto boolIt = this->variableInformation.booleanVariables.begin();
420 for (; assignmentIt != assignmentIte && assignmentIt->lValueIsVariable() && assignmentIt->getExpressionVariable().hasBooleanType(); ++assignmentIt) {
421 while (assignmentIt->getExpressionVariable() != boolIt->variable) {
422 ++boolIt;
423 }
424 state.set(boolIt->bitOffset, expressionEvaluator.asBool(assignmentIt->getAssignedExpression()));
425 }
426
427 // Iterate over all integer assignments and carry them out.
428 auto integerIt = this->variableInformation.integerVariables.begin();
429 for (; assignmentIt != assignmentIte && assignmentIt->lValueIsVariable() && assignmentIt->getExpressionVariable().hasIntegerType(); ++assignmentIt) {
430 while (assignmentIt->getExpressionVariable() != integerIt->variable) {
431 ++integerIt;
432 }
433 int_fast64_t assignedValue = expressionEvaluator.asInt(assignmentIt->getAssignedExpression());
434 if (this->options.isAddOutOfBoundsStateSet()) {
435 if (assignedValue < integerIt->lowerBound || assignedValue > integerIt->upperBound) {
436 state = this->outOfBoundsState;
437 }
438 } else if (integerIt->forceOutOfBoundsCheck || this->options.isExplorationChecksSet()) {
439 STORM_LOG_THROW(assignedValue >= integerIt->lowerBound, storm::exceptions::WrongFormatException,
440 "The update " << assignmentIt->getExpressionVariable().getName() << " := " << assignmentIt->getAssignedExpression()
441 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
442 << assignmentIt->getExpressionVariable().getName() << "'.");
443 STORM_LOG_THROW(assignedValue <= integerIt->upperBound, storm::exceptions::WrongFormatException,
444 "The update " << assignmentIt->getExpressionVariable().getName() << " := " << assignmentIt->getAssignedExpression()
445 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
446 << assignmentIt->getExpressionVariable().getName() << "'.");
447 }
448 state.setFromInt(integerIt->bitOffset, integerIt->bitWidth, assignedValue - integerIt->lowerBound);
449 STORM_LOG_ASSERT(static_cast<int_fast64_t>(state.getAsInt(integerIt->bitOffset, integerIt->bitWidth)) + integerIt->lowerBound == assignedValue,
450 "Writing to the bit vector bucket failed (read " << state.getAsInt(integerIt->bitOffset, integerIt->bitWidth) << " but wrote "
451 << assignedValue << ").");
452 }
453 // Iterate over all array access assignments and carry them out.
454 for (; assignmentIt != assignmentIte && assignmentIt->lValueIsArrayAccess(); ++assignmentIt) {
455 auto const& arrayIndicesAsExpr = assignmentIt->getLValue().getArrayIndexVector();
456 std::vector<uint64_t> arrayIndices;
457 arrayIndices.reserve(arrayIndicesAsExpr.size());
458 for (auto const& i : arrayIndicesAsExpr) {
459 arrayIndices.push_back(static_cast<uint64_t>(expressionEvaluator.asInt(i)));
460 }
461 if (assignmentIt->getAssignedExpression().hasIntegerType()) {
462 IntegerVariableInformation const& intInfo =
463 this->variableInformation.getIntegerArrayVariableReplacement(assignmentIt->getLValue().getVariable().getExpressionVariable(), arrayIndices);
464 int_fast64_t assignedValue = expressionEvaluator.asInt(assignmentIt->getAssignedExpression());
465
466 if (this->options.isAddOutOfBoundsStateSet()) {
467 if (assignedValue < intInfo.lowerBound || assignedValue > intInfo.upperBound) {
468 state = this->outOfBoundsState;
469 }
470 } else if (this->options.isExplorationChecksSet()) {
471 STORM_LOG_THROW(assignedValue >= intInfo.lowerBound, storm::exceptions::WrongFormatException,
472 "The update " << assignmentIt->getLValue() << " := " << assignmentIt->getAssignedExpression()
473 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
474 << assignmentIt->getExpressionVariable().getName() << "'.");
475 STORM_LOG_THROW(assignedValue <= intInfo.upperBound, storm::exceptions::WrongFormatException,
476 "The update " << assignmentIt->getLValue() << " := " << assignmentIt->getAssignedExpression()
477 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
478 << assignmentIt->getExpressionVariable().getName() << "'.");
479 }
480 state.setFromInt(intInfo.bitOffset, intInfo.bitWidth, assignedValue - intInfo.lowerBound);
481 STORM_LOG_ASSERT(static_cast<int_fast64_t>(state.getAsInt(intInfo.bitOffset, intInfo.bitWidth)) + intInfo.lowerBound == assignedValue,
482 "Writing to the bit vector bucket failed (read " << state.getAsInt(intInfo.bitOffset, intInfo.bitWidth) << " but wrote "
483 << assignedValue << ").");
484 } else if (assignmentIt->getAssignedExpression().hasBooleanType()) {
485 BooleanVariableInformation const& boolInfo =
486 this->variableInformation.getBooleanArrayVariableReplacement(assignmentIt->getLValue().getVariable().getExpressionVariable(), arrayIndices);
487 state.set(boolInfo.bitOffset, expressionEvaluator.asBool(assignmentIt->getAssignedExpression()));
488 } else {
489 STORM_LOG_THROW(false, storm::exceptions::UnexpectedException, "Unhandled type of base variable.");
490 }
491 }
492
493 // Check that we processed all assignments.
494 STORM_LOG_ASSERT(assignmentIt == assignmentIte, "Not all assignments were consumed.");
495}
496
497template<typename ValueType, typename StateType>
498void JaniNextStateGenerator<ValueType, StateType>::applyTransientUpdate(TransientVariableValuation<ValueType>& transientValuation,
499 storm::jani::detail::ConstAssignments const& transientAssignments,
500 storm::expressions::ExpressionEvaluator<ValueType> const& expressionEvaluator) const {
501 auto assignmentIt = transientAssignments.begin();
502 auto assignmentIte = transientAssignments.end();
503
504 // Iterate over all boolean assignments and carry them out.
505 auto boolIt = this->transientVariableInformation.booleanVariableInformation.begin();
506 for (; assignmentIt != assignmentIte && assignmentIt->lValueIsVariable() && assignmentIt->getExpressionVariable().hasBooleanType(); ++assignmentIt) {
507 while (assignmentIt->getExpressionVariable() != boolIt->variable) {
508 ++boolIt;
509 }
510 transientValuation.booleanValues.emplace_back(&(*boolIt), expressionEvaluator.asBool(assignmentIt->getAssignedExpression()));
511 }
512 // Iterate over all integer assignments and carry them out.
513 auto integerIt = this->transientVariableInformation.integerVariableInformation.begin();
514 for (; assignmentIt != assignmentIte && assignmentIt->lValueIsVariable() && assignmentIt->getExpressionVariable().hasIntegerType(); ++assignmentIt) {
515 while (assignmentIt->getExpressionVariable() != integerIt->variable) {
516 ++integerIt;
517 }
518 int64_t assignedValue = expressionEvaluator.asInt(assignmentIt->getAssignedExpression());
519 if (this->options.isExplorationChecksSet()) {
520 STORM_LOG_THROW(!integerIt->lowerBound || assignedValue >= integerIt->lowerBound.get(), storm::exceptions::WrongFormatException,
521 "The update " << assignmentIt->getExpressionVariable().getName() << " := " << assignmentIt->getAssignedExpression()
522 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
523 << assignmentIt->getExpressionVariable().getName() << "'.");
524 STORM_LOG_THROW(!integerIt->upperBound || assignedValue <= integerIt->upperBound.get(), storm::exceptions::WrongFormatException,
525 "The update " << assignmentIt->getExpressionVariable().getName() << " := " << assignmentIt->getAssignedExpression()
526 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
527 << assignmentIt->getExpressionVariable().getName() << "'.");
528 }
529 transientValuation.integerValues.emplace_back(&(*integerIt), assignedValue);
530 }
531 // Iterate over all rational assignments and carry them out.
532 auto rationalIt = this->transientVariableInformation.rationalVariableInformation.begin();
533 for (; assignmentIt != assignmentIte && assignmentIt->lValueIsVariable() && assignmentIt->getExpressionVariable().hasRationalType(); ++assignmentIt) {
534 while (assignmentIt->getExpressionVariable() != rationalIt->variable) {
535 ++rationalIt;
536 }
537 transientValuation.rationalValues.emplace_back(&(*rationalIt), expressionEvaluator.asRational(assignmentIt->getAssignedExpression()));
538 }
539
540 // Iterate over all array access assignments and carry them out.
541 for (; assignmentIt != assignmentIte && assignmentIt->lValueIsArrayAccess(); ++assignmentIt) {
542 auto const& arrayIndicesAsExpr = assignmentIt->getLValue().getArrayIndexVector();
543 std::vector<uint64_t> arrayIndices;
544 arrayIndices.reserve(arrayIndicesAsExpr.size());
545 for (auto const& i : arrayIndicesAsExpr) {
546 arrayIndices.push_back(static_cast<uint64_t>(expressionEvaluator.asInt(i)));
547 }
548 storm::expressions::Type const& baseType = assignmentIt->getLValue().getVariable().getExpressionVariable().getType();
549 if (baseType.isIntegerType()) {
550 auto const& intInfo = this->transientVariableInformation.getIntegerArrayVariableReplacement(
551 assignmentIt->getLValue().getVariable().getExpressionVariable(), arrayIndices);
552 int64_t assignedValue = expressionEvaluator.asInt(assignmentIt->getAssignedExpression());
553 if (this->options.isExplorationChecksSet()) {
554 STORM_LOG_THROW(assignedValue >= intInfo.lowerBound, storm::exceptions::WrongFormatException,
555 "The update " << assignmentIt->getLValue() << " := " << assignmentIt->getAssignedExpression()
556 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
557 << assignmentIt->getExpressionVariable().getName() << "'.");
558 STORM_LOG_THROW(assignedValue <= intInfo.upperBound, storm::exceptions::WrongFormatException,
559 "The update " << assignmentIt->getLValue() << " := " << assignmentIt->getAssignedExpression()
560 << " leads to an out-of-bounds value (" << assignedValue << ") for the variable '"
561 << assignmentIt->getExpressionVariable().getName() << "'.");
562 }
563 transientValuation.integerValues.emplace_back(&intInfo, assignedValue);
564 } else if (baseType.isBooleanType()) {
565 auto const& boolInfo = this->transientVariableInformation.getBooleanArrayVariableReplacement(
566 assignmentIt->getLValue().getVariable().getExpressionVariable(), arrayIndices);
567 transientValuation.booleanValues.emplace_back(&boolInfo, expressionEvaluator.asBool(assignmentIt->getAssignedExpression()));
568 } else if (baseType.isRationalType()) {
569 auto const& rationalInfo = this->transientVariableInformation.getRationalArrayVariableReplacement(
570 assignmentIt->getLValue().getVariable().getExpressionVariable(), arrayIndices);
571 transientValuation.rationalValues.emplace_back(&rationalInfo, expressionEvaluator.asRational(assignmentIt->getAssignedExpression()));
572 } else {
573 STORM_LOG_THROW(false, storm::exceptions::UnexpectedException, "Unhandled type of base variable.");
574 }
575 }
576
577 // Check that we processed all assignments.
578 STORM_LOG_ASSERT(assignmentIt == assignmentIte, "Not all assignments were consumed.");
579}
580
581template<typename ValueType, typename StateType>
582TransientVariableValuation<ValueType> JaniNextStateGenerator<ValueType, StateType>::getTransientVariableValuationAtLocations(
583 std::vector<uint64_t> const& locations, storm::expressions::ExpressionEvaluator<ValueType> const& evaluator) const {
584 TransientVariableValuation<ValueType> transientVariableValuation;
585 getTransientVariableValuationAtLocations(locations, evaluator, transientVariableValuation);
586 return transientVariableValuation;
587}
588
589template<typename ValueType, typename StateType>
590void JaniNextStateGenerator<ValueType, StateType>::getTransientVariableValuationAtLocations(
591 std::vector<uint64_t> const& locations, storm::expressions::ExpressionEvaluator<ValueType> const& evaluator,
592 TransientVariableValuation<ValueType>& transientVariableValuation) const {
593 transientVariableValuation.clear();
594 uint64_t automatonIndex = 0;
595 for (auto const& automatonRef : this->parallelAutomata) {
596 auto const& automaton = automatonRef.get();
597 uint64_t currentLocationIndex = locations[automatonIndex];
598 storm::jani::Location const& location = automaton.getLocation(currentLocationIndex);
599 STORM_LOG_ASSERT(!location.getAssignments().hasMultipleLevels(true), "Indexed assignments at locations are not supported in the jani standard.");
600 applyTransientUpdate(transientVariableValuation, location.getAssignments().getTransientAssignments(), evaluator);
601 ++automatonIndex;
602 }
603}
604
605template<typename ValueType, typename StateType>
608 transientVariableInformation.setDefaultValuesInEvaluator(evaluator);
609 auto transientVariableValuation = getTransientVariableValuationAtLocations(getLocations(state), evaluator);
610 transientVariableValuation.setInEvaluator(evaluator, this->getOptions().isExplorationChecksSet());
611}
612
613template<typename ValueType, typename StateType>
616 if (this->variableInformation.hasOutOfBoundsBit()) {
617 builder.addBooleanVariable(this->variableInformation.outOfBoundsBit->variable);
618 }
619 for (auto const& v : this->variableInformation.locationVariables) {
620 builder.addIntegerVariable(v.variable, 0, v.highestValue);
621 }
622 for (auto const& v : this->variableInformation.booleanVariables) {
623 builder.addBooleanVariable(v.variable);
624 }
625 for (auto const& v : this->variableInformation.integerVariables) {
626 builder.addIntegerVariable(v.variable, v.lowerBound, v.upperBound);
627 }
628 // Also add information for transient variables
629 for (auto const& varInfo : transientVariableInformation.booleanVariableInformation) {
630 builder.addBooleanVariable(varInfo.variable);
631 }
632 for (auto const& varInfo : transientVariableInformation.integerVariableInformation) {
633 builder.addIntegerVariable(varInfo.variable, varInfo.lowerBound.value_or(std::numeric_limits<int64_t>::min()),
634 varInfo.upperBound.value_or(std::numeric_limits<int64_t>::max()));
635 }
636 for (auto const& varInfo : transientVariableInformation.rationalVariableInformation) {
637 if (std::is_same_v<ValueType, storm::RationalNumber>) {
638 uint64_t const bitSize = std::max<uint64_t>(64, this->getOptions().getReservedBitsForUnboundedVariables());
639 builder.addRationalVariable(varInfo.variable, bitSize * 2); // reserve bits for numerator and denominator
640 } else {
641 STORM_LOG_THROW((std::is_same_v<ValueType, double>), storm::exceptions::NotSupportedException,
642 "State valuations for transient variables of the given value type are not supported.");
643 builder.addDoubleVariable(varInfo.variable);
644 }
645 }
646 return storm::storage::sparse::Valuations(builder.buildClassDescription(), builder.getManager().shared_from_this());
647}
648
649template<typename ValueType, typename StateType>
651 storm::storage::sparse::Valuations& valuations) const {
652 // Add values for non-transient variables
653 unpackStateAppendToValuations(*this->state, this->variableInformation, valuations.getStorage());
654
655 auto transientVariableValuation = getTransientVariableValuationAtLocations(getLocations(*this->state), *this->evaluator);
656 transientVariableValuation.setInValuations(currentStateIndex, transientVariableInformation, valuations.getStorage());
657}
658
659template<typename ValueType, typename StateType>
660bool JaniNextStateGenerator<ValueType, StateType>::evaluatorHoldsState(CompressedState const& state) const {
661 auto const& info = this->variableInformation;
662 // Compiling expressions is expensive, so we do it only once (the compiled expressions are stored within the Expression objects)
663 if (scratch->variableExpressionsForAssertions.empty()) {
664 for (auto const& v : info.locationVariables) {
665 scratch->variableExpressionsForAssertions.push_back(v.variable.getExpression());
666 }
667 for (auto const& v : info.booleanVariables) {
668 scratch->variableExpressionsForAssertions.push_back(v.variable.getExpression());
669 }
670 for (auto const& v : info.integerVariables) {
671 scratch->variableExpressionsForAssertions.push_back(v.variable.getExpression());
672 }
673 }
674 auto const expected = unpackStateIntoValuation(state, info, *this->expressionManager);
675 // Values that can not be represented exactly by the evaluator (e.g., double-based) are not compared.
676 auto const exactlyRepresentable = [](int64_t value) { return value > -(int64_t(1) << 52) && value < (int64_t(1) << 52); };
677 auto const holdsInteger = [&](storm::expressions::Variable const& variable, storm::expressions::Expression const& expression) {
678 int64_t const expectedValue = expected.getIntegerValue(variable);
679 return !exactlyRepresentable(expectedValue) || this->evaluator->asInt(expression) == expectedValue;
680 };
681 auto expressionIt = scratch->variableExpressionsForAssertions.begin();
682 for (auto const& v : info.locationVariables) {
683 if (!holdsInteger(v.variable, *expressionIt++)) {
684 return false;
685 }
686 }
687 for (auto const& v : info.booleanVariables) {
688 if (this->evaluator->asBool(*expressionIt++) != expected.getBooleanValue(v.variable)) {
689 return false;
690 }
691 }
692 for (auto const& v : info.integerVariables) {
693 if (!holdsInteger(v.variable, *expressionIt++)) {
694 return false;
695 }
696 }
697 return true;
698}
699
700template<typename ValueType, typename StateType>
701void JaniNextStateGenerator<ValueType, StateType>::setEvaluatorState(CompressedState const& state) {
702 STORM_LOG_ASSERT(state.size() == scratch->evaluatorState.size(), "Unexpected state size.");
703 STORM_LOG_ASSERT(evaluatorHoldsState(scratch->evaluatorState), "The evaluator does not hold the expected state.");
704 unpackStateDifferenceIntoEvaluator(state, scratch->evaluatorState, this->variableInformation, *this->evaluator);
705 scratch->evaluatorState = state;
706}
707
708template<typename ValueType, typename StateType>
710 // The evaluator should have the default values of the transient variables right now.
711
712 // Prepare the result, in case we return early.
714 result.clear();
715
716 // The evaluator currently holds the values of the state that is expanded (see NextStateGenerator::load)
717 scratch->evaluatorState = *this->state;
718 STORM_LOG_ASSERT(evaluatorHoldsState(*this->state), "The state to expand must be loaded into the evaluator (see load).");
719
720 // Retrieve the locations from the state.
721 std::vector<uint64_t>& locations = scratch->locations;
722 getLocations(*this->state, locations);
723
724 // First, construct the state rewards, as we may return early if there are no choices later and we already
725 // need the state rewards then.
726 getTransientVariableValuationAtLocations(locations, *this->evaluator, scratch->transientValuation);
727 scratch->transientValuation.setInEvaluator(*this->evaluator, this->getOptions().isExplorationChecksSet());
728 evaluateRewardExpressions(result.getStateRewards());
729
730 // If a terminal expression was set and we must not expand this state, return now.
731 // Terminal state expressions do not consider transient variables.
732 if (!this->terminalStates.empty()) {
733 for (auto const& expressionBool : this->terminalStates) {
734 if (this->evaluator->asBool(expressionBool.first) == expressionBool.second) {
735 // Set back transient variables to default values so we are ready to process the next state
736 this->transientVariableInformation.setDefaultValuesInEvaluator(*this->evaluator);
737 return result;
738 }
739 }
740 }
741
742 // Set back transient variables to default values so we are ready to process the transition assignments
743 this->transientVariableInformation.setDefaultValuesInEvaluator(*this->evaluator);
744
745 // Get all choices for the state.
746 result.setExpanded();
747 if (this->getOptions().isApplyMaximalProgressAssumptionSet()) {
748 // First explore only edges without a rate
749 getActionChoices(locations, *this->state, stateToIdCallback, EdgeFilter::WithoutRate, result);
750 if (result.empty()) {
751 // Expand the Markovian edges if there are no probabilistic ones.
752 getActionChoices(locations, *this->state, stateToIdCallback, EdgeFilter::WithRate, result);
753 }
754 } else {
755 getActionChoices(locations, *this->state, stateToIdCallback, EdgeFilter::All, result);
756 }
757 std::size_t totalNumberOfChoices = result.getNumberOfChoices();
758
759 // If there is not a single choice, we return immediately, because the state has no behavior (other than
760 // the state reward).
761 if (totalNumberOfChoices == 0) {
762 return result;
763 }
764
765 // If the model is a deterministic model, we need to fuse the choices into one.
766 if (this->isDeterministicModel() && totalNumberOfChoices > 1) {
767 Choice<ValueType> globalChoice;
768
769 if (this->options.isAddOverlappingGuardLabelSet()) {
770 this->overlappingGuardStates->push_back(stateToIdCallback(*this->state));
771 }
772
773 // For CTMCs, we need to keep track of the total exit rate to scale the action rewards later. For DTMCs
774 // this is equal to the number of choices, which is why we initialize it like this here.
775 ValueType totalExitRate = this->isDiscreteTimeModel() ? static_cast<ValueType>(totalNumberOfChoices) : storm::utility::zero<ValueType>();
776
777 // Iterate over all choices and combine the probabilities/rates into one choice.
778 for (auto const& choice : result) {
779 for (auto const& stateProbabilityPair : choice) {
780 if (this->isDiscreteTimeModel()) {
781 globalChoice.addProbability(stateProbabilityPair.first, stateProbabilityPair.second / totalNumberOfChoices);
782 } else {
783 globalChoice.addProbability(stateProbabilityPair.first, stateProbabilityPair.second);
784 }
785 }
786
787 if (hasStateActionRewards && !this->isDiscreteTimeModel()) {
788 totalExitRate += choice.getTotalMass();
789 }
790 }
791
792 std::vector<ValueType> stateActionRewards(rewardExpressions.size(), storm::utility::zero<ValueType>());
793 for (auto const& choice : result) {
794 if (hasStateActionRewards) {
795 for (uint_fast64_t rewardVariableIndex = 0; rewardVariableIndex < rewardExpressions.size(); ++rewardVariableIndex) {
796 stateActionRewards[rewardVariableIndex] += choice.getRewards()[rewardVariableIndex] * choice.getTotalMass() / totalExitRate;
797 }
798 }
799
800 if (this->options.isBuildChoiceOriginsSet() && choice.hasOriginData()) {
801 globalChoice.addOriginData(choice.getOriginData());
802 }
803 }
804 globalChoice.addRewards(std::move(stateActionRewards));
805
806 // Move the newly fused choice in place.
807 result.clearChoices();
808 result.addChoice(std::move(globalChoice));
809 }
810
811 this->postprocess(result);
812
813 return result;
814}
815
816template<typename ValueType, typename StateType>
817Choice<ValueType>& JaniNextStateGenerator<ValueType, StateType>::expandNonSynchronizingEdge(storm::jani::Edge const& edge, uint64_t outputActionIndex,
818 uint64_t automatonIndex, CompressedState const& state,
819 StateToIdCallback const& stateToIdCallback,
821 // Determine the exit rate if it's a Markovian edge.
822 boost::optional<ValueType> exitRate = boost::none;
823 if (edge.hasRate()) {
824 exitRate = this->evaluator->asRational(edge.getRate());
825 }
826
827 Choice<ValueType>& choice = behavior.startNewChoice(outputActionIndex, static_cast<bool>(exitRate));
828 std::vector<ValueType>& stateActionRewards = choice.getRewards();
829
830 // Perform the transient edge assignments and create the state action rewards
831 TransientVariableValuation<ValueType>& transientVariableValuation = scratch->transientValuation;
832 transientVariableValuation.clear();
833 if (!evaluateRewardExpressionsAtEdges || edge.getAssignments().empty()) {
834 stateActionRewards.resize(rewardModelInformation.size(), storm::utility::zero<ValueType>());
835 } else {
836 for (int64_t assignmentLevel = edge.getAssignments().getLowestLevel(true); assignmentLevel <= edge.getAssignments().getHighestLevel(true);
837 ++assignmentLevel) {
838 transientVariableValuation.clear();
839 applyTransientUpdate(transientVariableValuation, edge.getAssignments().getTransientAssignments(assignmentLevel), *this->evaluator);
840 transientVariableValuation.setInEvaluator(*this->evaluator, this->getOptions().isExplorationChecksSet());
841 }
842 evaluateRewardExpressions(stateActionRewards);
843 transientVariableInformation.setDefaultValuesInEvaluator(*this->evaluator);
844 }
845
846 // Iterate over all updates of the current command.
848 for (auto const& destination : edge.getDestinations()) {
849 ValueType probability = this->evaluator->asRational(destination.getProbability());
850
851 if (probability != storm::utility::zero<ValueType>()) {
852 bool evaluatorChanged = false;
853 // Obtain target state index and add it to the list of known states. If it has not yet been
854 // seen, we also add it to the set of states that have yet to be explored.
855 int64_t assignmentLevel = edge.getLowestAssignmentLevel(); // Might be the largest possible integer, if there is no assignment
856 int64_t const& highestLevel = edge.getHighestAssignmentLevel();
857 bool hasTransientAssignments = destination.hasTransientAssignment();
858 CompressedState& newState = scratch->successorState;
859 newState = state;
860 applyUpdate(newState, destination, this->variableInformation.locationVariables[automatonIndex], assignmentLevel, *this->evaluator);
861 if (hasTransientAssignments) {
863 "Transition rewards are not supported and scaling to action rewards is disabled.");
864 transientVariableValuation.clear();
865 applyTransientUpdate(transientVariableValuation, destination.getOrderedAssignments().getTransientAssignments(assignmentLevel),
866 *this->evaluator);
867 transientVariableValuation.setInEvaluator(*this->evaluator, this->getOptions().isExplorationChecksSet());
868 evaluatorChanged = true;
869 }
870 if (assignmentLevel < highestLevel) {
871 while (assignmentLevel < highestLevel) {
872 ++assignmentLevel;
873 setEvaluatorState(newState);
874 evaluatorChanged = true;
875 applyUpdate(newState, destination, this->variableInformation.locationVariables[automatonIndex], assignmentLevel, *this->evaluator);
876 if (hasTransientAssignments) {
877 transientVariableValuation.clear();
878 applyTransientUpdate(transientVariableValuation, destination.getOrderedAssignments().getTransientAssignments(assignmentLevel),
879 *this->evaluator);
880 transientVariableValuation.setInEvaluator(*this->evaluator, this->getOptions().isExplorationChecksSet());
881 evaluatorChanged = true;
882 }
883 }
884 }
885 if (evaluateRewardExpressionsAtDestinations) {
886 setEvaluatorState(newState);
887 evaluatorChanged = true;
888 addEvaluatedRewardExpressions(stateActionRewards, probability);
889 }
890
891 if (evaluatorChanged) {
892 // Restore the old variable valuation
893 setEvaluatorState(state);
894 if (hasTransientAssignments) {
895 this->transientVariableInformation.setDefaultValuesInEvaluator(*this->evaluator);
896 }
897 }
898
899 StateType stateIndex = stateToIdCallback(newState);
900
901 // Update the choice by adding the probability/target state to it.
902 probability = exitRate ? exitRate.get() * probability : probability;
903 choice.addProbability(stateIndex, probability);
904
905 if (this->options.isExplorationChecksSet()) {
906 probabilitySum += probability;
907 }
908 }
909 }
910
911 if (this->options.isExplorationChecksSet()) {
912 // Check that the resulting distribution is in fact a distribution.
913 STORM_LOG_THROW(!this->isDiscreteTimeModel() || (!storm::utility::isConstant(probabilitySum) || this->comparator.isOne(probabilitySum)),
914 storm::exceptions::WrongFormatException, "Probabilities do not sum to one for edge (actually sum to " << probabilitySum << ").");
915 }
916
917 return choice;
918}
919
920template<typename ValueType, typename StateType>
921void JaniNextStateGenerator<ValueType, StateType>::generateSynchronizedDistribution(storm::storage::BitVector const& state,
922 AutomataEdgeSets const& edgeCombination,
923 std::vector<EdgeSetWithIndices::const_iterator> const& iteratorList,
924 storm::generator::Distribution<StateType, ValueType>& distribution,
925 std::vector<ValueType>& stateActionRewards, EdgeIndexSet& edgeIndices,
926 StateToIdCallback const& stateToIdCallback) {
927 // Collect some information of the edges.
928 int64_t lowestDestinationAssignmentLevel = std::numeric_limits<int64_t>::max();
929 int64_t highestDestinationAssignmentLevel = std::numeric_limits<int64_t>::min();
930 int64_t lowestEdgeAssignmentLevel = std::numeric_limits<int64_t>::max();
931 int64_t highestEdgeAssignmentLevel = std::numeric_limits<int64_t>::min();
932 uint64_t numDestinations = 1;
933 for (uint_fast64_t i = 0; i < iteratorList.size(); ++i) {
934 if (this->getOptions().isBuildChoiceOriginsSet()) {
935 auto automatonIndex = model.getAutomatonIndex(parallelAutomata[edgeCombination[i].first].get().getName());
936 edgeIndices.insert(storm::jani::Model::encodeAutomatonAndEdgeIndices(automatonIndex, iteratorList[i]->first));
937 }
938 storm::jani::Edge const& edge = *iteratorList[i]->second;
939 lowestDestinationAssignmentLevel = std::min(lowestDestinationAssignmentLevel, edge.getLowestAssignmentLevel());
940 highestDestinationAssignmentLevel = std::max(highestDestinationAssignmentLevel, edge.getHighestAssignmentLevel());
941 if (!edge.getAssignments().empty(true)) {
942 lowestEdgeAssignmentLevel = std::min(lowestEdgeAssignmentLevel, edge.getAssignments().getLowestLevel(true));
943 highestEdgeAssignmentLevel = std::max(highestEdgeAssignmentLevel, edge.getAssignments().getHighestLevel(true));
944 }
945 numDestinations *= edge.getNumberOfDestinations();
946 }
947
948 // Perform the edge assignments (if there are any)
949 TransientVariableValuation<ValueType>& transientVariableValuation = scratch->transientValuation;
950 transientVariableValuation.clear();
951 if (evaluateRewardExpressionsAtEdges && lowestEdgeAssignmentLevel <= highestEdgeAssignmentLevel) {
952 for (int64_t assignmentLevel = lowestEdgeAssignmentLevel; assignmentLevel <= highestEdgeAssignmentLevel; ++assignmentLevel) {
953 transientVariableValuation.clear();
954 for (uint_fast64_t i = 0; i < iteratorList.size(); ++i) {
955 storm::jani::Edge const& edge = *iteratorList[i]->second;
956 applyTransientUpdate(transientVariableValuation, edge.getAssignments().getTransientAssignments(assignmentLevel), *this->evaluator);
957 }
958 transientVariableValuation.setInEvaluator(*this->evaluator, this->getOptions().isExplorationChecksSet());
959 }
960 addEvaluatedRewardExpressions(stateActionRewards, storm::utility::one<ValueType>());
961 transientVariableInformation.setDefaultValuesInEvaluator(*this->evaluator);
962 }
963
964 std::vector<storm::jani::EdgeDestination const*>& destinations = scratch->destinations;
965 std::vector<LocationVariableInformation const*>& locationVars = scratch->locationVars;
966
967 for (uint64_t destinationId = 0; destinationId < numDestinations; ++destinationId) {
968 // First assignment level
969 destinations.clear();
970 locationVars.clear();
971 transientVariableValuation.clear();
972 CompressedState& successorState = scratch->successorState;
973 successorState = state;
974 ValueType successorProbability = storm::utility::one<ValueType>();
975
976 uint64_t destinationIndex = destinationId;
977 for (uint64_t i = 0; i < iteratorList.size(); ++i) {
978 storm::jani::Edge const& edge = *iteratorList[i]->second;
979 STORM_LOG_ASSERT(edge.getNumberOfDestinations() > 0, "Found an edge with zero destinations. This is not expected.");
980 uint64_t localDestinationIndex = destinationIndex % edge.getNumberOfDestinations();
981 destinations.push_back(&edge.getDestination(localDestinationIndex));
982 locationVars.push_back(&this->variableInformation.locationVariables[edgeCombination[i].first]);
983 destinationIndex /= edge.getNumberOfDestinations();
984 ValueType probability = this->evaluator->asRational(destinations.back()->getProbability());
985 if (edge.hasRate()) {
986 successorProbability *= probability * this->evaluator->asRational(edge.getRate());
987 } else {
988 successorProbability *= probability;
989 }
990 if (storm::utility::isZero(successorProbability)) {
991 break;
992 }
993
994 applyUpdate(successorState, *destinations.back(), *locationVars.back(), lowestDestinationAssignmentLevel, *this->evaluator);
995 applyTransientUpdate(transientVariableValuation,
996 destinations.back()->getOrderedAssignments().getTransientAssignments(lowestDestinationAssignmentLevel), *this->evaluator);
997 }
998
999 if (!storm::utility::isZero(successorProbability)) {
1000 bool evaluatorChanged = false;
1001 // remaining assignment levels (if there are any)
1002 for (int64_t assignmentLevel = lowestDestinationAssignmentLevel + 1; assignmentLevel <= highestDestinationAssignmentLevel; ++assignmentLevel) {
1003 setEvaluatorState(successorState);
1004 transientVariableValuation.setInEvaluator(*this->evaluator, this->getOptions().isExplorationChecksSet());
1005 transientVariableValuation.clear();
1006 evaluatorChanged = true;
1007 auto locationVarIt = locationVars.begin();
1008 for (auto const& destPtr : destinations) {
1009 applyUpdate(successorState, *destPtr, **locationVarIt, assignmentLevel, *this->evaluator);
1010 applyTransientUpdate(transientVariableValuation, destPtr->getOrderedAssignments().getTransientAssignments(assignmentLevel),
1011 *this->evaluator);
1012 ++locationVarIt;
1013 }
1014 }
1015 if (!transientVariableValuation.empty()) {
1016 evaluatorChanged = true;
1017 transientVariableValuation.setInEvaluator(*this->evaluator, this->getOptions().isExplorationChecksSet());
1018 }
1019 if (evaluateRewardExpressionsAtDestinations) {
1020 setEvaluatorState(successorState);
1021 evaluatorChanged = true;
1022 addEvaluatedRewardExpressions(stateActionRewards, successorProbability);
1023 }
1024 if (evaluatorChanged) {
1025 // Restore the old state information
1026 setEvaluatorState(state);
1027 this->transientVariableInformation.setDefaultValuesInEvaluator(*this->evaluator);
1028 }
1029
1030 StateType id = stateToIdCallback(successorState);
1031 distribution.add(id, successorProbability);
1032 }
1033 }
1034}
1035
1036template<typename ValueType, typename StateType>
1037void JaniNextStateGenerator<ValueType, StateType>::expandSynchronizingEdgeCombination(AutomataEdgeSets const& edgeCombination, uint64_t outputActionIndex,
1038 CompressedState const& state, StateToIdCallback const& stateToIdCallback,
1039 StateBehavior<ValueType, StateType>& behavior) {
1040 if (this->options.isExplorationChecksSet()) {
1041 // Check whether a global variable is written multiple times in any combination.
1042 checkGlobalVariableWritesValid(edgeCombination);
1043 }
1044
1045 std::vector<EdgeSetWithIndices::const_iterator>& iteratorList = scratch->iteratorList;
1046 iteratorList.resize(edgeCombination.size());
1047
1048 // Initialize the list of iterators.
1049 for (size_t i = 0; i < edgeCombination.size(); ++i) {
1050 iteratorList[i] = edgeCombination[i].second.cbegin();
1051 }
1052
1053 storm::generator::Distribution<StateType, ValueType>& distribution = scratch->distribution;
1054
1055 // As long as there is one feasible combination of commands, keep on expanding it.
1056 bool done = false;
1057 while (!done) {
1058 distribution.clear();
1059
1060 EdgeIndexSet edgeIndices;
1061 Choice<ValueType>& choice = behavior.startNewChoice(outputActionIndex);
1062 std::vector<ValueType>& stateActionRewards = choice.getRewards();
1063 stateActionRewards.assign(rewardExpressions.size(), storm::utility::zero<ValueType>());
1064 // old version without assignment levels generateSynchronizedDistribution(state, storm::utility::one<ValueType>(), 0, edgeCombination, iteratorList,
1065 // distribution, stateActionRewards, edgeIndices, stateToIdCallback);
1066 generateSynchronizedDistribution(state, edgeCombination, iteratorList, distribution, stateActionRewards, edgeIndices, stateToIdCallback);
1067 distribution.compress();
1068
1069 // At this point, we applied all commands of the current command combination and the distribution
1070 // contains all target states and their respective probabilities. The choice (which has already been added
1071 // to the behavior above) and its rewards are already set. That means we are now ready to
1072 // fill in the origin data, the probabilities/rates and the labels of the choice.
1073
1074 // Add the edge indices if requested.
1075 if (this->getOptions().isBuildChoiceOriginsSet()) {
1076 choice.addOriginData(boost::any(std::move(edgeIndices)));
1077 }
1078
1079 // Add the probabilities/rates to the newly created choice.
1080 ValueType probabilitySum = storm::utility::zero<ValueType>();
1081 choice.reserve(std::distance(distribution.begin(), distribution.end()));
1082 for (auto const& stateProbability : distribution) {
1083 choice.addProbability(stateProbability.getState(), stateProbability.getValue());
1084
1085 if (this->options.isExplorationChecksSet()) {
1086 probabilitySum += stateProbability.getValue();
1087 }
1088 }
1089
1090 if (this->options.isExplorationChecksSet()) {
1091 // Check that the resulting distribution is in fact a distribution.
1092 STORM_LOG_THROW(!this->isDiscreteTimeModel() || !storm::utility::isConstant(probabilitySum) || this->comparator.isOne(probabilitySum),
1093 storm::exceptions::WrongFormatException,
1094 "Sum of update probabilities do not sum to one for some edge (actually sum to " << probabilitySum << ").");
1095 }
1096
1097 if (this->options.isBuildChoiceLabelsSet()) {
1098 if (outputActionIndex != storm::jani::Model::SILENT_ACTION_INDEX) {
1099 choice.addLabel(model.getAction(outputActionIndex).getName());
1100 }
1101 }
1102
1103 // Now, check whether there is one more command combination to consider.
1104 bool movedIterator = false;
1105 for (uint64_t j = 0; !movedIterator && j < iteratorList.size(); ++j) {
1106 ++iteratorList[j];
1107 if (iteratorList[j] != edgeCombination[j].second.end()) {
1108 movedIterator = true;
1109 } else {
1110 // Reset the iterator to the beginning of the list.
1111 iteratorList[j] = edgeCombination[j].second.begin();
1112 }
1113 }
1114
1115 done = !movedIterator;
1116 }
1117}
1118
1119template<typename ValueType, typename StateType>
1120void JaniNextStateGenerator<ValueType, StateType>::getActionChoices(std::vector<uint64_t> const& locations, CompressedState const& state,
1121 StateToIdCallback const& stateToIdCallback, EdgeFilter const& edgeFilter,
1122 StateBehavior<ValueType, StateType>& behavior) {
1123 scratch->automataEdgeSets.resize(edges.size());
1124
1125 // To avoid reallocations, we reuse some scratch memory.
1126 // This vector will store for each automaton the set of edges with the current output and the current source location
1127 std::vector<EdgeSetWithIndices const*>& edgeSetsMemory = scratch->edgeSets;
1128 // This vector will store the 'first' combination of edges that is productive.
1129 std::vector<typename EdgeSetWithIndices::const_iterator>& edgeIteratorMemory = scratch->firstEnabledEdgeIterators;
1130
1131 uint64_t outputAndEdgesIndex = 0;
1132 for (OutputAndEdges const& outputAndEdges : edges) {
1133 auto const& edges = outputAndEdges.second;
1134 AutomataEdgeSets& automataEdgeSets = scratch->automataEdgeSets[outputAndEdgesIndex++];
1135 if (edges.size() == 1) {
1136 // If the synch consists of just one element, it's non-synchronizing.
1137 auto const& nonsychingEdges = edges.front();
1138 uint64_t automatonIndex = nonsychingEdges.first;
1139
1140 auto edgesIt = nonsychingEdges.second.find(locations[automatonIndex]);
1141 if (edgesIt != nonsychingEdges.second.end()) {
1142 for (auto const& indexAndEdge : edgesIt->second) {
1143 if (edgeFilter != EdgeFilter::All) {
1144 STORM_LOG_ASSERT(edgeFilter == EdgeFilter::WithRate || edgeFilter == EdgeFilter::WithoutRate, "Unexpected edge filter.");
1145 if ((edgeFilter == EdgeFilter::WithRate) != indexAndEdge.second->hasRate()) {
1146 continue;
1147 }
1148 }
1149 if (!this->evaluator->asBool(indexAndEdge.second->getGuard())) {
1150 continue;
1151 }
1152
1153 uint64_t actionIndex = outputAndEdges.first ? outputAndEdges.first.get() : indexAndEdge.second->getActionIndex();
1154 Choice<ValueType>& choice =
1155 expandNonSynchronizingEdge(*indexAndEdge.second, actionIndex, automatonIndex, state, stateToIdCallback, behavior);
1156
1157 if (this->getOptions().isBuildChoiceOriginsSet()) {
1158 auto modelAutomatonIndex = model.getAutomatonIndex(parallelAutomata[automatonIndex].get().getName());
1159 EdgeIndexSet edgeIndex{storm::jani::Model::encodeAutomatonAndEdgeIndices(modelAutomatonIndex, indexAndEdge.first)};
1160 choice.addOriginData(boost::any(std::move(edgeIndex)));
1161 }
1162
1163 if (this->getOptions().isBuildChoiceLabelsSet()) {
1164 if (actionIndex != storm::jani::Model::SILENT_ACTION_INDEX) {
1165 choice.addLabel(model.getAction(actionIndex).getName());
1166 }
1167 }
1168 }
1169 }
1170 } else {
1171 // If the element has more than one set of edges, we need to perform a synchronization.
1172 // We require that some output action for the synchronisation must have been set before.
1173 // This might be the silent action, if the Jani model does not specify an output action.
1174 STORM_LOG_ASSERT(outputAndEdges.first, "Need output action index for synchronization.");
1175
1176 uint64_t outputActionIndex = outputAndEdges.first.get();
1177
1178 // Find out whether this combination is productive
1179 bool productiveCombination = true;
1180 // First check, whether each automaton has at least one edge with the current output and the current source location
1181 // We will also store the edges of each automaton with the current outputAction
1182 edgeSetsMemory.clear();
1183 for (auto const& automatonAndEdges : outputAndEdges.second) {
1184 uint64_t automatonIndex = automatonAndEdges.first;
1185 LocationsAndEdges const& locationsAndEdges = automatonAndEdges.second;
1186 auto edgesIt = locationsAndEdges.find(locations[automatonIndex]);
1187 if (edgesIt == locationsAndEdges.end()) {
1188 productiveCombination = false;
1189 break;
1190 }
1191 edgeSetsMemory.push_back(&edgesIt->second);
1192 }
1193
1194 if (productiveCombination) {
1195 // second, check whether each automaton has at least one enabled action
1196 edgeIteratorMemory.clear(); // Store the first enabled edge in each automaton.
1197 for (auto const& edgesIt : edgeSetsMemory) {
1198 bool atLeastOneEdge = false;
1199 EdgeSetWithIndices const& edgeSetWithIndices = *edgesIt;
1200 for (auto indexAndEdgeIt = edgeSetWithIndices.begin(), indexAndEdgeIte = edgeSetWithIndices.end(); indexAndEdgeIt != indexAndEdgeIte;
1201 ++indexAndEdgeIt) {
1202 // check whether we do not consider this edge
1203 if (edgeFilter != EdgeFilter::All) {
1204 STORM_LOG_ASSERT(edgeFilter == EdgeFilter::WithRate || edgeFilter == EdgeFilter::WithoutRate, "Unexpected edge filter.");
1205 if ((edgeFilter == EdgeFilter::WithRate) != indexAndEdgeIt->second->hasRate()) {
1206 continue;
1207 }
1208 }
1209
1210 if (!this->evaluator->asBool(indexAndEdgeIt->second->getGuard())) {
1211 continue;
1212 }
1213
1214 // If we reach this point, the edge is considered enabled.
1215 atLeastOneEdge = true;
1216 edgeIteratorMemory.push_back(indexAndEdgeIt);
1217 break;
1218 }
1219
1220 // If there is no enabled edge of this automaton, the whole combination is not productive.
1221 if (!atLeastOneEdge) {
1222 productiveCombination = false;
1223 break;
1224 }
1225 }
1226 }
1227
1228 // produce the combination
1229 if (productiveCombination) {
1230 // Reuse the memory of the edge sets (resizing is a no-op except for the first time this synchronization is reached)
1231 automataEdgeSets.resize(outputAndEdges.second.size());
1232 STORM_LOG_ASSERT(edgeSetsMemory.size() == outputAndEdges.second.size(), "Unexpected number of edge sets stored.");
1233 STORM_LOG_ASSERT(edgeIteratorMemory.size() == outputAndEdges.second.size(), "Unexpected number of edge iterators stored.");
1234 auto edgeSetIt = edgeSetsMemory.begin();
1235 auto edgeIteratorIt = edgeIteratorMemory.begin();
1236 auto automatonEdgeSetsIt = automataEdgeSets.begin();
1237 for (auto const& automatonAndEdges : outputAndEdges.second) {
1238 EdgeSetWithIndices& enabledEdgesOfAutomaton = automatonEdgeSetsIt->second;
1239 enabledEdgesOfAutomaton.clear();
1240 automatonEdgeSetsIt->first = automatonAndEdges.first;
1241 EdgeSetWithIndices const& edgeSetWithIndices = **edgeSetIt;
1242 auto indexAndEdgeIt = *edgeIteratorIt;
1243 // The first edge where the edgeIterator points to is always enabled.
1244 enabledEdgesOfAutomaton.emplace_back(*indexAndEdgeIt);
1245 auto indexAndEdgeIte = edgeSetWithIndices.end();
1246 for (++indexAndEdgeIt; indexAndEdgeIt != indexAndEdgeIte; ++indexAndEdgeIt) {
1247 // check whether we do not consider this edge
1248 if (edgeFilter != EdgeFilter::All) {
1249 STORM_LOG_ASSERT(edgeFilter == EdgeFilter::WithRate || edgeFilter == EdgeFilter::WithoutRate, "Unexpected edge filter.");
1250 if ((edgeFilter == EdgeFilter::WithRate) != indexAndEdgeIt->second->hasRate()) {
1251 continue;
1252 }
1253 }
1254
1255 if (!this->evaluator->asBool(indexAndEdgeIt->second->getGuard())) {
1256 continue;
1257 }
1258 // If we reach this point, the edge is considered enabled.
1259 enabledEdgesOfAutomaton.emplace_back(*indexAndEdgeIt);
1260 }
1261 ++automatonEdgeSetsIt;
1262 ++edgeSetIt;
1263 ++edgeIteratorIt;
1264 }
1265 // insert choices in the result vector.
1266 expandSynchronizingEdgeCombination(automataEdgeSets, outputActionIndex, state, stateToIdCallback, behavior);
1267 }
1268 }
1269 }
1270}
1271
1272template<typename ValueType, typename StateType>
1273void JaniNextStateGenerator<ValueType, StateType>::checkGlobalVariableWritesValid(AutomataEdgeSets const& enabledEdges) const {
1274 // Todo: this also throws if the writes are on different assignment level
1275 // Todo: this also throws if the writes are on different elements of the same array
1276 std::map<storm::expressions::Variable, uint64_t> writtenGlobalVariables;
1277 for (auto edgeSetIt = enabledEdges.begin(), edgeSetIte = enabledEdges.end(); edgeSetIt != edgeSetIte; ++edgeSetIt) {
1278 for (auto const& indexAndEdge : edgeSetIt->second) {
1279 for (auto const& globalVariable : indexAndEdge.second->getWrittenGlobalVariables()) {
1280 auto it = writtenGlobalVariables.find(globalVariable);
1281
1282 auto index = std::distance(enabledEdges.begin(), edgeSetIt);
1283 if (it != writtenGlobalVariables.end()) {
1284 STORM_LOG_THROW(it->second == static_cast<uint64_t>(index), storm::exceptions::WrongFormatException,
1285 "Multiple writes to global variable '" << globalVariable.getName() << "' in synchronizing edges.");
1286 } else {
1287 writtenGlobalVariables.emplace(globalVariable, index);
1288 }
1289 }
1290 }
1291 }
1292}
1293
1294template<typename ValueType, typename StateType>
1296 return rewardExpressions.size();
1297}
1298
1299template<typename ValueType, typename StateType>
1301 return rewardModelInformation[index];
1302}
1303
1304template<typename ValueType, typename StateType>
1306 std::vector<StateType> const& initialStateIndices,
1307 std::vector<StateType> const& deadlockStateIndices,
1308 std::vector<StateType> const& unexploredStateIndices) {
1309 // As in JANI we can use transient boolean variable assignments in locations to identify states, we need to
1310 // create a list of boolean transient variables and the expressions that define them.
1311 std::vector<std::pair<std::string, storm::expressions::Expression>> transientVariableExpressions;
1312 for (auto const& variable : model.getGlobalVariables().getTransientVariables()) {
1313 if (variable.getType().isBasicType() && variable.getType().asBasicType().isBooleanType()) {
1314 if (this->options.isBuildAllLabelsSet() || this->options.getLabelNames().find(variable.getName()) != this->options.getLabelNames().end()) {
1315 transientVariableExpressions.emplace_back(variable.getName(), variable.getExpressionVariable().getExpression());
1316 }
1317 }
1318 }
1319 return NextStateGenerator<ValueType, StateType>::label(stateStorage, initialStateIndices, deadlockStateIndices, unexploredStateIndices,
1320 transientVariableExpressions);
1321}
1322
1323template<typename ValueType, typename StateType>
1324std::vector<ValueType> JaniNextStateGenerator<ValueType, StateType>::evaluateRewardExpressions() const {
1325 std::vector<ValueType> result;
1326 evaluateRewardExpressions(result);
1327 return result;
1328}
1329
1330template<typename ValueType, typename StateType>
1331void JaniNextStateGenerator<ValueType, StateType>::evaluateRewardExpressions(std::vector<ValueType>& result) const {
1332 result.clear();
1333 result.reserve(rewardExpressions.size());
1334 for (auto const& rewardExpression : rewardExpressions) {
1335 result.push_back(this->evaluator->asRational(rewardExpression.second));
1336 }
1337}
1338
1339template<typename ValueType, typename StateType>
1340void JaniNextStateGenerator<ValueType, StateType>::addEvaluatedRewardExpressions(std::vector<ValueType>& rewards, ValueType const& factor) const {
1341 STORM_LOG_ASSERT(rewards.size() == rewardExpressions.size(), "Reward count mismatch.");
1342 auto rewIt = rewards.begin();
1343 for (auto const& rewardExpression : rewardExpressions) {
1344 (*rewIt) += factor * this->evaluator->asRational(rewardExpression.second);
1345 ++rewIt;
1346 }
1347}
1348
1349template<typename ValueType, typename StateType>
1350void JaniNextStateGenerator<ValueType, StateType>::buildRewardModelInformation() {
1351 for (auto const& rewardModel : rewardExpressions) {
1352 storm::jani::RewardModelInformation info(this->model, rewardModel.second);
1353 rewardModelInformation.emplace_back(rewardModel.first, info.hasStateRewards(), false, false);
1354 STORM_LOG_THROW(this->options.isScaleAndLiftTransitionRewardsSet() || !info.hasTransitionRewards(), storm::exceptions::NotSupportedException,
1355 "Transition rewards are not supported and a reduction to action-based rewards was not possible.");
1356 if (info.hasTransitionRewards()) {
1357 evaluateRewardExpressionsAtDestinations = true;
1358 }
1359 if (info.hasActionRewards() || (this->options.isScaleAndLiftTransitionRewardsSet() && info.hasTransitionRewards())) {
1360 hasStateActionRewards = true;
1361 rewardModelInformation.back().setHasStateActionRewards();
1362 }
1363 }
1364 if (!hasStateActionRewards) {
1365 evaluateRewardExpressionsAtDestinations = false;
1366 evaluateRewardExpressionsAtEdges = false;
1367 }
1368}
1369
1370template<typename ValueType, typename StateType>
1371void JaniNextStateGenerator<ValueType, StateType>::createSynchronizationInformation() {
1372 // Create synchronizing edges information.
1373 storm::jani::Composition const& topLevelComposition = this->model.getSystemComposition();
1374 if (topLevelComposition.isAutomatonComposition()) {
1375 auto const& automaton = this->model.getAutomaton(topLevelComposition.asAutomatonComposition().getAutomatonName());
1376 this->parallelAutomata.push_back(automaton);
1377
1378 LocationsAndEdges locationsAndEdges;
1379 uint64_t edgeIndex = 0;
1380 for (auto const& edge : automaton.getEdges()) {
1381 locationsAndEdges[edge.getSourceLocationIndex()].emplace_back(std::make_pair(edgeIndex, &edge));
1382 ++edgeIndex;
1383 }
1384
1385 AutomataAndEdges automataAndEdges;
1386 automataAndEdges.emplace_back(std::make_pair(0, std::move(locationsAndEdges)));
1387
1388 this->edges.emplace_back(std::make_pair(boost::none, std::move(automataAndEdges)));
1389 } else {
1390 STORM_LOG_THROW(topLevelComposition.isParallelComposition(), storm::exceptions::WrongFormatException, "Expected parallel composition.");
1391 storm::jani::ParallelComposition const& parallelComposition = topLevelComposition.asParallelComposition();
1392
1393 uint64_t automatonIndex = 0;
1394 for (auto const& composition : parallelComposition.getSubcompositions()) {
1395 STORM_LOG_THROW(composition->isAutomatonComposition(), storm::exceptions::WrongFormatException, "Expected flat parallel composition.");
1396 STORM_LOG_THROW(composition->asAutomatonComposition().getInputEnabledActions().empty(), storm::exceptions::NotSupportedException,
1397 "Input-enabled actions are not supported right now.");
1398
1399 this->parallelAutomata.push_back(this->model.getAutomaton(composition->asAutomatonComposition().getAutomatonName()));
1400
1401 // Add edges with silent action.
1402 LocationsAndEdges locationsAndEdges;
1403 uint64_t edgeIndex = 0;
1404 for (auto const& edge : parallelAutomata.back().get().getEdges()) {
1406 locationsAndEdges[edge.getSourceLocationIndex()].emplace_back(std::make_pair(edgeIndex, &edge));
1407 }
1408 ++edgeIndex;
1409 }
1410
1411 if (!locationsAndEdges.empty()) {
1412 AutomataAndEdges automataAndEdges;
1413 automataAndEdges.emplace_back(std::make_pair(automatonIndex, std::move(locationsAndEdges)));
1414 this->edges.emplace_back(std::make_pair(boost::none, std::move(automataAndEdges)));
1415 }
1416 ++automatonIndex;
1417 }
1418
1419 for (auto const& vector : parallelComposition.getSynchronizationVectors()) {
1420 uint64_t outputActionIndex = this->model.getActionIndex(vector.getOutput());
1421
1422 AutomataAndEdges automataAndEdges;
1423 bool atLeastOneEdge = true;
1424 uint64_t automatonIndex = 0;
1425 for (auto const& element : vector.getInput()) {
1427 LocationsAndEdges locationsAndEdges;
1428 uint64_t actionIndex = this->model.getActionIndex(element);
1429 uint64_t edgeIndex = 0;
1430 for (auto const& edge : parallelAutomata[automatonIndex].get().getEdges()) {
1431 if (edge.getActionIndex() == actionIndex) {
1432 locationsAndEdges[edge.getSourceLocationIndex()].emplace_back(std::make_pair(edgeIndex, &edge));
1433 }
1434 ++edgeIndex;
1435 }
1436 if (locationsAndEdges.empty()) {
1437 atLeastOneEdge = false;
1438 break;
1439 }
1440 automataAndEdges.emplace_back(std::make_pair(automatonIndex, std::move(locationsAndEdges)));
1441 }
1442 ++automatonIndex;
1443 }
1444
1445 if (atLeastOneEdge) {
1446 this->edges.emplace_back(std::make_pair(outputActionIndex, std::move(automataAndEdges)));
1447 }
1448 }
1449 }
1450
1451 STORM_LOG_TRACE("Number of synchronizations: " << this->edges.size() << ".");
1452}
1453
1454template<typename ValueType, typename StateType>
1455std::shared_ptr<storm::storage::sparse::ChoiceOrigins> JaniNextStateGenerator<ValueType, StateType>::generateChoiceOrigins(
1456 std::vector<boost::any>& dataForChoiceOrigins) const {
1457 if (!this->getOptions().isBuildChoiceOriginsSet()) {
1458 return nullptr;
1459 }
1460
1461 std::vector<uint_fast64_t> identifiers;
1462 identifiers.reserve(dataForChoiceOrigins.size());
1463
1464 std::map<EdgeIndexSet, uint_fast64_t> edgeIndexSetToIdentifierMap;
1465 // The empty edge set (i.e., the choices without origin) always has to get identifier getIdentifierForChoicesWithNoOrigin() -- which is assumed to be 0
1466 STORM_LOG_ASSERT(storm::storage::sparse::ChoiceOrigins::getIdentifierForChoicesWithNoOrigin() == 0, "The no origin identifier is assumed to be zero.");
1467 edgeIndexSetToIdentifierMap.insert(std::make_pair(EdgeIndexSet(), 0));
1468 uint_fast64_t currentIdentifier = 1;
1469 for (boost::any& originData : dataForChoiceOrigins) {
1470 STORM_LOG_ASSERT(originData.empty() || boost::any_cast<EdgeIndexSet>(&originData) != nullptr,
1471 "Origin data has unexpected type: " << originData.type().name() << ".");
1472
1473 EdgeIndexSet currentEdgeIndexSet = originData.empty() ? EdgeIndexSet() : boost::any_cast<EdgeIndexSet>(std::move(originData));
1474 auto insertionRes = edgeIndexSetToIdentifierMap.emplace(std::move(currentEdgeIndexSet), currentIdentifier);
1475 identifiers.push_back(insertionRes.first->second);
1476 if (insertionRes.second) {
1477 ++currentIdentifier;
1478 }
1479 }
1480
1481 std::vector<EdgeIndexSet> identifierToEdgeIndexSetMapping(currentIdentifier);
1482 for (auto const& setIdPair : edgeIndexSetToIdentifierMap) {
1483 identifierToEdgeIndexSetMapping[setIdPair.second] = setIdPair.first;
1484 }
1485
1486 return std::make_shared<storm::storage::sparse::JaniChoiceOrigins>(std::make_shared<storm::jani::Model>(model), std::move(identifiers),
1487 std::move(identifierToEdgeIndexSetMapping));
1488}
1489
1490template<typename ValueType, typename StateType>
1491storm::storage::BitVector JaniNextStateGenerator<ValueType, StateType>::evaluateObservationLabels(CompressedState const& /*state*/) const {
1492 STORM_LOG_WARN("There are no observation labels in JANI currenty");
1493 return storm::storage::BitVector(0);
1494}
1495
1496template<typename ValueType, typename StateType>
1497void JaniNextStateGenerator<ValueType, StateType>::checkValid() const {
1498 // If the program still contains undefined constants and we are not in a parametric setting, assemble an appropriate error message.
1499 if (!std::is_same<ValueType, storm::RationalFunction>::value && model.hasUndefinedConstants()) {
1500 std::vector<std::reference_wrapper<storm::jani::Constant const>> undefinedConstants = model.getUndefinedConstants();
1501 std::stringstream stream;
1502 bool printComma = false;
1503 for (auto const& constant : undefinedConstants) {
1504 if (printComma) {
1505 stream << ", ";
1506 } else {
1507 printComma = true;
1508 }
1509 stream << constant.get().getName() << " (" << constant.get().getType() << ")";
1510 }
1511 stream << ".";
1512 STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Program still contains these undefined constants: " + stream.str() + ".");
1513 } else if (std::is_same<ValueType, storm::RationalFunction>::value && !model.undefinedConstantsAreGraphPreserving()) {
1514 STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException,
1515 "The input model contains undefined constants that influence the graph structure of the underlying model, which is not allowed.");
1516 }
1517}
1518
1519template class JaniNextStateGenerator<double>;
1520template class JaniNextStateGenerator<storm::RationalNumber>;
1521template class JaniNextStateGenerator<storm::RationalFunction>;
1522} // namespace generator
1523} // namespace storm
uint64_t getReservedBitsForUnboundedVariables() const
std::set< std::string > const & getRewardModelNames() const
Which reward models are built.
std::vector< std::pair< LabelOrExpression, bool > > const & getTerminalStates() const
ExpressionManager const & getManager() const
Retrieves the manager responsible for this expression.
bool isInitialized() const
Checks whether the object encapsulates a base-expression.
Expression integer(int_fast64_t value) const
Creates an expression that characterizes the given integer literal.
bool isBooleanType() const
Checks whether this type is a boolean type.
Definition Type.cpp:194
bool isIntegerType() const
Checks whether this type is an integral type.
Definition Type.cpp:198
bool isRationalType() const
Checks whether this type is a rational type.
Definition Type.cpp:234
Type const & getType() const
Retrieves the type of the variable.
Definition Variable.cpp:50
storm::expressions::Expression getExpression() const
Retrieves an expression that represents the variable.
Definition Variable.cpp:34
std::string const & getName() const
Retrieves the name of the variable.
Definition Variable.cpp:46
void clear()
Clears this distribution.
ContainerType::iterator begin()
Access to iterators over the entries of the distribution.
void compress()
Compresses the internal storage by summing the values of entries which agree on the index.
ContainerType::iterator end()
void add(DistributionEntry< IndexType, ValueType > const &entry)
Adds the given entry to the distribution.
storm::storage::FlatSet< uint_fast64_t > EdgeIndexSet
virtual ModelType getModelType() const override
static storm::jani::ModelFeatures getSupportedJaniFeatures()
Returns the jani features with which this builder can deal natively.
virtual std::shared_ptr< storm::storage::sparse::ChoiceOrigins > generateChoiceOrigins(std::vector< boost::any > &dataForChoiceOrigins) const override
virtual std::vector< StateType > getInitialStates(StateToIdCallback const &stateToIdCallback) override
JaniNextStateGenerator(storm::jani::Model const &model, NextStateGeneratorOptions const &options=NextStateGeneratorOptions())
virtual storm::builder::RewardModelInformation getRewardModelInformation(uint64_t const &index) const override
virtual StateBehavior< ValueType, StateType > const & expand(StateToIdCallback const &stateToIdCallback) override
virtual bool isPartiallyObservable() const override
virtual std::size_t getNumberOfRewardModels() const override
static bool canHandle(storm::jani::Model const &model)
A quick check to detect whether the given model is not supported.
NextStateGenerator< ValueType, StateType >::StateToIdCallback StateToIdCallback
virtual storm::models::sparse::StateLabeling label(storm::storage::sparse::StateStorage< StateType > const &stateStorage, std::vector< StateType > const &initialStateIndices={}, std::vector< StateType > const &deadlockStateIndices={}, std::vector< StateType > const &unexploredStateIndices={}) override
virtual void addStateValuation(storm::storage::sparse::state_type const &currentStateIndex, storm::storage::sparse::Valuations &valuations) const override
Adds the valuation for the currently loaded state to the given builder.
virtual void unpackTransientVariableValuesIntoEvaluator(CompressedState const &state, storm::expressions::ExpressionEvaluator< ValueType > &evaluator) const override
Sets the values of all transient variables in the current state to the given evaluator.
virtual storm::storage::sparse::Valuations initializeStateValuations() const override
Initializes state valuations by adding the appropriate variables.
std::unique_ptr< storm::expressions::ExpressionEvaluator< BaseValueType > > evaluator
void postprocess(StateBehavior< ValueType, uint32_t > &result)
boost::optional< std::vector< uint64_t > > overlappingGuardStates
std::vector< std::pair< storm::expressions::Expression, bool > > terminalStates
virtual storm::models::sparse::StateLabeling label(storm::storage::sparse::StateStorage< StateType > const &stateStorage, std::vector< StateType > const &initialStateIndices={}, std::vector< StateType > const &deadlockStateIndices={}, std::vector< StateType > const &unexploredStateIndices={})=0
bool empty() const
Retrieves whether the behavior is empty in the sense that there are no available choices.
std::vector< ValueType > const & getStateRewards() const
Retrieves the list of state rewards under selected reward models.
void clear()
Resets this to an empty behavior, i.e.
std::size_t getNumberOfChoices() const
Retrieves the number of choices in the behavior.
void setExpanded(bool newValue=true)
Sets whether the state was expanded.
Choice< ValueType, StateType > & startNewChoice(uint_fast64_t actionIndex=0, bool markovian=false)
Adds a new empty choice with the given action index and returns a reference to it.
std::string const & getName() const
Returns the name of the location.
Definition Action.cpp:9
std::string const & getAutomatonName() const
Retrieves the name of the automaton this composition element refers to.
bool isBooleanType() const
Definition BasicType.cpp:20
virtual bool isAutomatonComposition() const
virtual bool isParallelComposition() const
AutomatonComposition const & asAutomatonComposition() const
ParallelComposition const & asParallelComposition() const
storm::expressions::Expression const & getProbability() const
Retrieves the probability of choosing this destination.
bool hasTransientAssignment() const
Retrieves whether this destination has transient assignments.
OrderedAssignments const & getOrderedAssignments() const
Retrieves the assignments to make when choosing this destination.
uint64_t getLocationIndex() const
Retrieves the id of the destination location.
uint64_t getActionIndex() const
Retrieves the id of the action with which this edge is labeled.
Definition Edge.cpp:45
std::vector< EdgeDestination > const & getDestinations() const
Retrieves the destinations of this edge.
Definition Edge.cpp:77
bool hasRate() const
Retrieves whether this edge has an associated rate.
Definition Edge.cpp:49
uint64_t getSourceLocationIndex() const
Retrieves the index of the source location.
Definition Edge.cpp:41
OrderedAssignments const & getAssignments() const
Retrieves the assignments of this edge.
Definition Edge.cpp:89
storm::expressions::Expression const & getRate() const
Retrieves the rate of this edge.
Definition Edge.cpp:53
int64_t const & getHighestAssignmentLevel() const
Retrieves the highest assignment level occurring in a destination assignment If no assignment exists,...
Definition Edge.cpp:147
std::size_t getNumberOfDestinations() const
Retrieves the number of destinations of this edge.
Definition Edge.cpp:85
int64_t const & getLowestAssignmentLevel() const
Retrieves the lowest assignment level occurring in a destination assignment.
Definition Edge.cpp:143
EdgeDestination const & getDestination(uint64_t index) const
Retrieves the destination with the given index.
Definition Edge.cpp:73
virtual bool isBasicType() const
Definition JaniType.cpp:11
BasicType const & asBasicType() const
Definition JaniType.cpp:31
OrderedAssignments const & getAssignments() const
Retrieves the assignments of this location.
Definition Location.cpp:23
ModelFeatures & add(ModelFeature const &modelFeature)
void remove(ModelFeature const &modelFeature)
bool hasUndefinedConstants() const
Retrieves whether the model still has undefined constants.
Definition Model.cpp:1079
storm::expressions::ExpressionManager & getManager() const
Retrieves the expression manager responsible for the expressions in the model.
Definition Model.cpp:109
VariableSet & getGlobalVariables()
Retrieves the variables of this automaton.
Definition Model.cpp:717
storm::expressions::Expression getRewardModelExpression(std::string const &identifier) const
Retrieves the defining reward expression of the reward model with the given identifier.
Definition Model.cpp:809
static uint64_t encodeAutomatonAndEdgeIndices(uint64_t automatonIndex, uint64_t edgeIndex)
Encode and decode a tuple of automaton and edge index in one 64-bit index.
Definition Model.cpp:1600
Composition const & getSystemComposition() const
Retrieves the system composition expression.
Definition Model.cpp:945
void liftTransientEdgeDestinationAssignments(int64_t maxLevel=0)
Lifts the common edge destination assignments of transient variables to edge assignments.
Definition Model.cpp:1556
static const uint64_t SILENT_ACTION_INDEX
The index of the silent action.
Definition Model.h:658
bool hasNonTrivialRewardExpression() const
Returns true iff there is a non-trivial reward model, i.e., a reward model that does not consist of a...
Definition Model.cpp:789
bool undefinedConstantsAreGraphPreserving() const
Checks that undefined constants (parameters) of the model preserve the graph of the underlying model.
Definition Model.cpp:1497
void pushEdgeAssignmentsToDestinations()
Definition Model.cpp:1550
Action const & getAction(uint64_t index) const
Retrieves the action with the given index.
Definition Model.cpp:624
std::vector< std::pair< std::string, storm::expressions::Expression > > getAllRewardModelExpressions() const
Retrieves all available reward model names and expressions of the model.
Definition Model.cpp:837
bool isNonTrivialRewardModelExpression(std::string const &identifier) const
Returns true iff the given identifier corresponds to a non-trivial reward expression i....
Definition Model.cpp:793
void simplifyComposition()
Attempts to simplify the composition.
Definition Model.cpp:981
ModelFeatures const & getModelFeatures() const
Retrieves the enabled model features.
Definition Model.cpp:125
Automaton & getAutomaton(std::string const &name)
Retrieves the automaton with the given name.
Definition Model.cpp:884
bool hasNonTrivialInitialStates() const
Retrieves whether there are non-trivial initial states in the model or any of the contained automata.
Definition Model.cpp:1303
uint64_t getActionIndex(std::string const &name) const
Get the index of the action.
Definition Model.cpp:632
bool usesAssignmentLevels(bool onlyTransient=false) const
Retrieves whether the model uses an assignment level other than zero.
Definition Model.cpp:1571
uint64_t getAutomatonIndex(std::string const &name) const
Retrieves the index of the given automaton.
Definition Model.cpp:904
std::vector< std::reference_wrapper< Constant const > > getUndefinedConstants() const
Retrieves all undefined constants of the model.
Definition Model.cpp:1088
bool hasMultipleLevels(bool onlyTransient=false) const
Checks whether the assignments have several levels.
bool empty(bool onlyTransient=false) const
Retrieves whether this set of assignments is empty.
int64_t getLowestLevel(bool onlyTransient=false) const
Retrieves the lowest level among all assignments.
detail::ConstAssignments getNonTransientAssignments() const
Returns all non-transient assignments in this set of assignments.
detail::ConstAssignments getTransientAssignments() const
Returns all transient assignments in this set of assignments.
int64_t getHighestLevel(bool onlyTransient=false) const
Retrieves the highest level among all assignments.
std::vector< SynchronizationVector > const & getSynchronizationVectors() const
Retrieves the synchronization vectors of the parallel composition.
std::vector< std::shared_ptr< Composition > > const & getSubcompositions() const
Retrieves the subcompositions of the parallel composition.
static bool isNoActionInput(std::string const &action)
storm::expressions::Variable const & getExpressionVariable() const
Retrieves the associated expression variable.
Definition Variable.cpp:26
JaniType & getType()
Definition Variable.cpp:67
bool isTransient() const
Definition Variable.cpp:42
bool hasVariable(std::string const &name) const
Retrieves whether this variable set contains a variable with the given name.
Variable const & getVariable(std::string const &name) const
Retrieves the variable with the given name.
This class manages the labeling of the state space with a number of (atomic) labels.
A bit vector that is internally represented as a vector of 64-bit values.
Definition BitVector.h:16
void setFromInt(uint64_t bitIndex, uint64_t numberOfBits, uint64_t value)
Sets the selected number of lowermost bits of the provided value at the given bit index.
void set(uint64_t index, bool value=true)
Sets the given truth value at the given index.
uint64_t getAsInt(uint64_t bitIndex, uint64_t numberOfBits) const
Retrieves the content of the current bit vector at the given index for the given number of bits as an...
static uint_fast64_t getIdentifierForChoicesWithNoOrigin()
Helper to incrementally build a ValuationClassDescription, i.e.
Provides access to valuations of variables for a set of entities (e.g.
Definition Valuations.h:28
ValuationsStorage const & getStorage() const
#define STORM_LOG_INFO(message)
Definition logging.h:34
#define STORM_LOG_WARN(message)
Definition logging.h:35
#define STORM_LOG_DEBUG(message)
Definition logging.h:28
#define STORM_LOG_TRACE(message)
Definition logging.h:22
#define STORM_LOG_ASSERT(cond, message)
Definition macros.h:9
#define STORM_LOG_THROW(cond, exception, message)
Definition macros.h:39
SFTBDDChecker::ValueType ValueType
void unpackStateAppendToValuations(CompressedState const &state, VariableInformation const &variableInformation, storm::storage::sparse::ValuationsStorage &valuations)
Appends the values of the variables in the given state to the valuations object.
storm::expressions::SimpleValuation unpackStateIntoValuation(CompressedState const &state, VariableInformation const &variableInformation, storm::expressions::ExpressionManager const &manager)
Converts the compressed state into an explicit representation in the form of a valuation.
void unpackStateDifferenceIntoEvaluator(CompressedState const &newState, CompressedState const &oldState, VariableInformation const &variableInformation, storm::expressions::ExpressionEvaluator< ValueType > &evaluator)
Updates the (non-transient) variable values in the given evaluator from the values of oldState to the...
storm::storage::BitVector CompressedState
storm::builder::BuilderOptions NextStateGeneratorOptions
storm::adapters::DereferenceIteratorAdapter< std::vector< std::shared_ptr< Assignment > > const > ConstAssignments
bool isDiscreteTimeModel(ModelType const &modelType)
Definition ModelType.cpp:89
void forEach(std::vector< IteratorType > const &its, std::vector< IteratorType > const &ites, std::function< void(uint64_t, decltype(*std::declval< IteratorType >()))> const &setValueCallback, std::function< bool()> const &newCombinationCallback)
std::unique_ptr< storm::solver::SmtSolver > getSmtSolver(storm::expressions::ExpressionManager &manager)
Creates a new SMT solver instance.
Definition solver.cpp:215
std::vector< T > buildVectorForRange(T min, T max)
Constructs a vector [min, min+1, ...., max-1].
Definition vector.h:130
bool isConstant(ValueType const &)
bool isZero(ValueType const &a)
Definition constants.cpp:44
ValueType zero()
Definition constants.cpp:26
ValueType one()
Definition constants.cpp:21
The contract of a DD backend.
void addOriginData(boost::any const &data)
Adds the given data that specifies the origin of this choice w.r.t.
Definition Choice.cpp:129
void addRewards(std::vector< ValueType > &&values)
Adds the given choices rewards to this choice.
Definition Choice.cpp:182
void addProbability(StateType const &state, ValueType const &value)
Adds the given probability value to the given state in the underlying distribution.
Definition Choice.cpp:171
The actual (private) implementation of JaniNextStateGeneratorScratchMemory, see the corresponding mem...
TransientVariableValuation< ValueType > transientValuation
std::vector< typename Generator::EdgeSetWithIndices const * > edgeSets
std::vector< typename Generator::AutomataEdgeSets > automataEdgeSets
JaniNextStateGenerator< ValueType, StateType > Generator
std::vector< typename Generator::EdgeSetWithIndices::const_iterator > iteratorList
std::vector< typename Generator::EdgeSetWithIndices::const_iterator > firstEnabledEdgeIterators
std::vector< LocationVariableInformation const * > locationVars
storm::generator::Distribution< StateType, ValueType > distribution
std::vector< storm::jani::EdgeDestination const * > destinations
std::vector< storm::expressions::Expression > variableExpressionsForAssertions