Storm 2.0.0.3
A Modern Probabilistic Model Checker
Loading...
Searching...
No Matches
Z3ExpressionAdapter.cpp
Go to the documentation of this file.
2
3#include <cstdint>
4
12
13namespace storm {
14namespace adapters {
15
16#ifdef STORM_HAVE_Z3
17
18typedef int64_t Z3_SIGNED_INTEGER;
19typedef uint64_t Z3_UNSIGNED_INTEGER;
20
21Z3ExpressionAdapter::Z3ExpressionAdapter(storm::expressions::ExpressionManager& manager, z3::context& context)
22 : manager(manager), context(context), additionalAssertions(), variableToExpressionMapping() {
23 // Intentionally left empty.
24}
25
26z3::expr Z3ExpressionAdapter::translateExpression(storm::expressions::Expression const& expression) {
27 STORM_LOG_ASSERT(expression.getManager() == this->manager, "Invalid expression for solver.");
28
29 z3::expr result = boost::any_cast<z3::expr>(expression.getBaseExpression().accept(*this, boost::none));
30 expressionCache.clear();
31
32 for (z3::expr const& assertion : additionalAssertions) {
33 result = result && assertion;
34 }
35 additionalAssertions.clear();
36 return result.simplify();
37}
38
39z3::expr Z3ExpressionAdapter::translateExpression(storm::expressions::Variable const& variable) {
40 STORM_LOG_ASSERT(variable.getManager() == this->manager, "Invalid expression for solver.");
41
42 auto const& variableExpressionPair = variableToExpressionMapping.find(variable);
43 if (variableExpressionPair == variableToExpressionMapping.end()) {
44 return createVariable(variable);
45 }
46
47 return variableExpressionPair->second;
48}
49
50storm::expressions::Variable const& Z3ExpressionAdapter::getVariable(z3::func_decl z3Declaration) {
51 auto const& declarationVariablePair = declarationToVariableMapping.find(z3Declaration);
52 STORM_LOG_ASSERT(declarationVariablePair != declarationToVariableMapping.end(), "Unable to find declaration.");
53 return declarationVariablePair->second;
54}
55
56storm::expressions::Expression Z3ExpressionAdapter::translateExpression(z3::expr const& expr) {
57 if (expr.is_app()) {
58 switch (expr.decl().decl_kind()) {
59 case Z3_OP_TRUE:
60 return manager.boolean(true);
61 case Z3_OP_FALSE:
62 return manager.boolean(false);
63 case Z3_OP_EQ:
64 return this->translateExpression(expr.arg(0)) == this->translateExpression(expr.arg(1));
65 case Z3_OP_DISTINCT: {
66 unsigned args = expr.num_args();
67 STORM_LOG_THROW(args != 0, storm::exceptions::ExpressionEvaluationException,
68 "Failed to convert Z3 expression. DISTINCT (mutual != ) operator with 0-arity is assumed to be an error.");
69 if (args == 1) {
70 return manager.boolean(true);
71 } else {
72 storm::expressions::Expression retVal = this->translateExpression(expr.arg(0)) != this->translateExpression(expr.arg(1));
73 for (unsigned arg2 = 2; arg2 < args; ++arg2) {
74 retVal = retVal && (this->translateExpression(expr.arg(0)) != this->translateExpression(expr.arg(arg2)));
75 }
76 for (unsigned arg1 = 1; arg1 < args; ++arg1) {
77 for (unsigned arg2 = arg1 + 1; arg2 < args; ++arg2) {
78 retVal = retVal && (this->translateExpression(expr.arg(arg1)) != this->translateExpression(expr.arg(arg2)));
79 }
80 }
81 return retVal;
82 }
83 }
84 case Z3_OP_ITE:
85 return storm::expressions::ite(this->translateExpression(expr.arg(0)), this->translateExpression(expr.arg(1)),
86 this->translateExpression(expr.arg(2)));
87 case Z3_OP_AND: {
88 unsigned args = expr.num_args();
89 STORM_LOG_THROW(args != 0, storm::exceptions::ExpressionEvaluationException,
90 "Failed to convert Z3 expression. 0-ary AND is assumed to be an error.");
91 if (args == 1) {
92 return this->translateExpression(expr.arg(0));
93 } else {
94 storm::expressions::Expression retVal = this->translateExpression(expr.arg(0));
95 for (unsigned i = 1; i < args; i++) {
96 retVal = retVal && this->translateExpression(expr.arg(i));
97 }
98 return retVal;
99 }
100 }
101 case Z3_OP_OR: {
102 unsigned args = expr.num_args();
103 STORM_LOG_THROW(args != 0, storm::exceptions::ExpressionEvaluationException,
104 "Failed to convert Z3 expression. 0-ary OR is assumed to be an error.");
105 if (args == 1) {
106 return this->translateExpression(expr.arg(0));
107 } else {
108 storm::expressions::Expression retVal = this->translateExpression(expr.arg(0));
109 for (unsigned i = 1; i < args; i++) {
110 retVal = retVal || this->translateExpression(expr.arg(i));
111 }
112 return retVal;
113 }
114 }
115 case Z3_OP_IFF:
116 return storm::expressions::iff(this->translateExpression(expr.arg(0)), this->translateExpression(expr.arg(1)));
117 case Z3_OP_XOR:
118 return storm::expressions::xclusiveor(this->translateExpression(expr.arg(0)), this->translateExpression(expr.arg(1)));
119 case Z3_OP_NOT:
120 return !this->translateExpression(expr.arg(0));
121 case Z3_OP_IMPLIES:
122 return storm::expressions::implies(this->translateExpression(expr.arg(0)), this->translateExpression(expr.arg(1)));
123 case Z3_OP_LE:
124 return this->translateExpression(expr.arg(0)) <= this->translateExpression(expr.arg(1));
125 case Z3_OP_GE:
126 return this->translateExpression(expr.arg(0)) >= this->translateExpression(expr.arg(1));
127 case Z3_OP_LT:
128 return this->translateExpression(expr.arg(0)) < this->translateExpression(expr.arg(1));
129 case Z3_OP_GT:
130 return this->translateExpression(expr.arg(0)) > this->translateExpression(expr.arg(1));
131 case Z3_OP_ADD:
132 case Z3_OP_MUL: {
133 // These operators may have more than two arguments. We build a balanced expression to avoid deep recursion on large terms.
134 std::vector<storm::expressions::Expression> operands;
135 operands.reserve(expr.num_args());
136 for (unsigned i = 0; i < expr.num_args(); ++i) {
137 operands.push_back(this->translateExpression(expr.arg(i)));
138 }
139 STORM_LOG_THROW(!operands.empty(), storm::exceptions::ExpressionEvaluationException,
140 "Failed to convert Z3 expression. Encountered an addition or multiplication without arguments.");
141 return expr.decl().decl_kind() == Z3_OP_ADD ? storm::expressions::sum(operands) : storm::expressions::product(operands);
142 }
143 case Z3_OP_SUB:
144 return this->translateExpression(expr.arg(0)) - this->translateExpression(expr.arg(1));
145 case Z3_OP_UMINUS:
146 return -this->translateExpression(expr.arg(0));
147 case Z3_OP_DIV:
148 return this->translateExpression(expr.arg(0)) / this->translateExpression(expr.arg(1));
149 case Z3_OP_IDIV:
150 // Storm has no integer division, and translating this to Storm's division would silently change the semantics.
151 STORM_LOG_THROW_UNCONDITIONALLY(storm::exceptions::NotImplementedException,
152 "Failed to convert Z3 expression. Integer division is not supported.");
153 case Z3_OP_ANUM:
154 // Arithmetic numeral.
155 if (expr.is_int() && expr.is_const()) {
156 Z3_SIGNED_INTEGER value;
157 if (Z3_get_numeral_int64(expr.ctx(), expr, &value)) {
158 return manager.integer(value);
159 } else {
160 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException,
161 "Failed to convert Z3 expression. Expression is constant integer and value does not fit into 64-bit integer.");
162 }
163 } else {
164 STORM_LOG_ASSERT(expr.is_real() && expr.is_const(), "Cannot handle numerical expression.");
165 Z3_SIGNED_INTEGER num;
166 Z3_SIGNED_INTEGER den;
167 if (Z3_get_numeral_rational_int64(expr.ctx(), expr, &num, &den)) {
168 return manager.rational(storm::utility::convertNumber<storm::RationalNumber>(static_cast<int_fast64_t>(num)) /
169 storm::utility::convertNumber<storm::RationalNumber>(static_cast<int_fast64_t>(den)));
170 } else {
171 return manager.rational(storm::utility::convertNumber<storm::RationalNumber>(std::string(Z3_get_numeral_string(expr.ctx(), expr))));
172 }
173 }
174 break;
175 case Z3_OP_AGNUM:
176 STORM_LOG_WARN("Interpreting algebraic numbers as rational numbers. This is not an exact computation.");
177 // Get the value of an algebraic number, converted to a rational, with precision 1/10^16.
179 std::string(Z3_get_numeral_string(expr.ctx(), Z3_get_algebraic_number_lower(expr.ctx(), expr, 16)))));
180 case Z3_OP_UNINTERPRETED:
181 // Currently, we only support uninterpreted constant functions.
182 STORM_LOG_THROW(expr.is_const(), storm::exceptions::ExpressionEvaluationException,
183 "Failed to convert Z3 expression. Encountered non-constant uninterpreted function.");
184 return manager.getVariable(expr.decl().name().str()).getExpression();
185 default:
186 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException,
187 "Failed to convert Z3 expression. Encountered unhandled Z3_decl_kind " << expr.decl().decl_kind() << ".");
188 break;
189 }
190 } else {
191 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException, "Failed to convert Z3 expression. Encountered unknown expression type.");
192 }
193}
194
195boost::any Z3ExpressionAdapter::visit(storm::expressions::BinaryBooleanFunctionExpression const& expression, boost::any const& data) {
196 auto cacheIt = expressionCache.find(&expression);
197 if (cacheIt != expressionCache.end()) {
198 return cacheIt->second;
199 }
200
201 z3::expr leftResult = boost::any_cast<z3::expr>(expression.getFirstOperand()->accept(*this, data));
202 z3::expr rightResult = boost::any_cast<z3::expr>(expression.getSecondOperand()->accept(*this, data));
203
204 z3::expr result(context);
205 switch (expression.getOperatorType()) {
207 result = leftResult && rightResult;
208 break;
210 result = leftResult || rightResult;
211 break;
213 result = z3::expr(context, Z3_mk_xor(context, leftResult, rightResult));
214 break;
216 result = z3::expr(context, Z3_mk_implies(context, leftResult, rightResult));
217 break;
219 result = z3::expr(context, Z3_mk_iff(context, leftResult, rightResult));
220 break;
221 default:
222 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException,
223 "Cannot evaluate expression: unknown boolean binary operator '" << static_cast<int>(expression.getOperatorType())
224 << "' in expression " << expression << ".");
225 }
226
227 expressionCache.emplace(&expression, result);
228 return result;
229}
230
231boost::any Z3ExpressionAdapter::visit(storm::expressions::BinaryNumericalFunctionExpression const& expression, boost::any const& data) {
232 auto cacheIt = expressionCache.find(&expression);
233 if (cacheIt != expressionCache.end()) {
234 return cacheIt->second;
235 }
236
237 z3::expr leftResult = boost::any_cast<z3::expr>(expression.getFirstOperand()->accept(*this, data));
238 z3::expr rightResult = boost::any_cast<z3::expr>(expression.getSecondOperand()->accept(*this, data));
239
240 z3::expr result(context);
241 switch (expression.getOperatorType()) {
243 result = leftResult + rightResult;
244 break;
246 result = leftResult - rightResult;
247 break;
249 result = leftResult * rightResult;
250 break;
252 if (leftResult.is_int() && rightResult.is_int()) {
253 leftResult = z3::expr(context, Z3_mk_int2real(context, leftResult));
254 }
255 result = leftResult / rightResult;
256 break;
258 result = ite(leftResult <= rightResult, leftResult, rightResult);
259 break;
261 result = ite(leftResult >= rightResult, leftResult, rightResult);
262 break;
264 result = pw(leftResult, rightResult);
265 break;
266 default:
267 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException,
268 "Cannot evaluate expression: unknown numerical binary operator '" << static_cast<int>(expression.getOperatorType())
269 << "' in expression " << expression << ".");
270 }
271
272 expressionCache.emplace(&expression, result);
273 return result;
274}
275
276boost::any Z3ExpressionAdapter::visit(storm::expressions::BinaryRelationExpression const& expression, boost::any const& data) {
277 auto cacheIt = expressionCache.find(&expression);
278 if (cacheIt != expressionCache.end()) {
279 return cacheIt->second;
280 }
281
282 z3::expr leftResult = boost::any_cast<z3::expr>(expression.getFirstOperand()->accept(*this, data));
283 z3::expr rightResult = boost::any_cast<z3::expr>(expression.getSecondOperand()->accept(*this, data));
284
285 z3::expr result(context);
286 switch (expression.getRelationType()) {
288 result = leftResult == rightResult;
289 break;
291 result = leftResult != rightResult;
292 break;
294 result = leftResult < rightResult;
295 break;
297 result = leftResult <= rightResult;
298 break;
300 result = leftResult > rightResult;
301 break;
303 result = leftResult >= rightResult;
304 break;
305 default:
306 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException,
307 "Cannot evaluate expression: unknown boolean binary operator '" << static_cast<int>(expression.getRelationType())
308 << "' in expression " << expression << ".");
309 }
310
311 expressionCache.emplace(&expression, result);
312 return result;
313}
314
315boost::any Z3ExpressionAdapter::visit(storm::expressions::BooleanLiteralExpression const& expression, boost::any const&) {
316 auto cacheIt = expressionCache.find(&expression);
317 if (cacheIt != expressionCache.end()) {
318 return cacheIt->second;
319 }
320
321 z3::expr result = context.bool_val(expression.getValue());
322
323 expressionCache.emplace(&expression, result);
324 return result;
325}
326
327boost::any Z3ExpressionAdapter::visit(storm::expressions::RationalLiteralExpression const& expression, boost::any const&) {
328 auto cacheIt = expressionCache.find(&expression);
329 if (cacheIt != expressionCache.end()) {
330 return cacheIt->second;
331 }
332
333 std::stringstream fractionStream;
334 fractionStream << expression.getValue();
335 z3::expr result = context.real_val(fractionStream.str().c_str());
336
337 expressionCache.emplace(&expression, result);
338 return result;
339}
340
341boost::any Z3ExpressionAdapter::visit(storm::expressions::IntegerLiteralExpression const& expression, boost::any const&) {
342 auto cacheIt = expressionCache.find(&expression);
343 if (cacheIt != expressionCache.end()) {
344 return cacheIt->second;
345 }
346
347 z3::expr result = context.int_val(static_cast<Z3_SIGNED_INTEGER>(expression.getValue()));
348
349 expressionCache.emplace(&expression, result);
350 return result;
351}
352
353boost::any Z3ExpressionAdapter::visit(storm::expressions::UnaryBooleanFunctionExpression const& expression, boost::any const& data) {
354 auto cacheIt = expressionCache.find(&expression);
355 if (cacheIt != expressionCache.end()) {
356 return cacheIt->second;
357 }
358
359 z3::expr result = boost::any_cast<z3::expr>(expression.getOperand()->accept(*this, data));
360
361 switch (expression.getOperatorType()) {
363 result = !result;
364 break;
365 default:
366 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException,
367 "Cannot evaluate expression: unknown boolean binary operator '" << static_cast<int>(expression.getOperatorType())
368 << "' in expression " << expression << ".");
369 }
370
371 expressionCache.emplace(&expression, result);
372 return result;
373}
374
375boost::any Z3ExpressionAdapter::visit(storm::expressions::UnaryNumericalFunctionExpression const& expression, boost::any const& data) {
376 auto cacheIt = expressionCache.find(&expression);
377 if (cacheIt != expressionCache.end()) {
378 return cacheIt->second;
379 }
380
381 z3::expr result = boost::any_cast<z3::expr>(expression.getOperand()->accept(*this, data));
382
383 switch (expression.getOperatorType()) {
385 result = 0 - result;
386 break;
388 storm::expressions::Variable freshAuxiliaryVariable = manager.declareFreshVariable(manager.getIntegerType(), true);
389 z3::expr floorVariable = context.int_const(freshAuxiliaryVariable.getName().c_str());
390 additionalAssertions.push_back(z3::expr(context, Z3_mk_int2real(context, floorVariable)) <= result &&
391 result < (z3::expr(context, Z3_mk_int2real(context, floorVariable)) + 1));
392 result = floorVariable;
393 break;
394 }
396 storm::expressions::Variable freshAuxiliaryVariable = manager.declareFreshVariable(manager.getIntegerType(), true);
397 z3::expr ceilVariable = context.int_const(freshAuxiliaryVariable.getName().c_str());
398 additionalAssertions.push_back(z3::expr(context, Z3_mk_int2real(context, ceilVariable)) - 1 < result &&
399 result <= z3::expr(context, Z3_mk_int2real(context, ceilVariable)));
400 result = ceilVariable;
401 break;
402 }
403 default:
404 STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException,
405 "Cannot evaluate expression: unknown numerical unary operator '" << static_cast<int>(expression.getOperatorType()) << "'.");
406 }
407
408 expressionCache.emplace(&expression, result);
409 return result;
410}
411
412boost::any Z3ExpressionAdapter::visit(storm::expressions::IfThenElseExpression const& expression, boost::any const& data) {
413 auto cacheIt = expressionCache.find(&expression);
414 if (cacheIt != expressionCache.end()) {
415 return cacheIt->second;
416 }
417
418 z3::expr conditionResult = boost::any_cast<z3::expr>(expression.getCondition()->accept(*this, data));
419 z3::expr thenResult = boost::any_cast<z3::expr>(expression.getThenExpression()->accept(*this, data));
420 z3::expr elseResult = boost::any_cast<z3::expr>(expression.getElseExpression()->accept(*this, data));
421 z3::expr result = z3::expr(context, Z3_mk_ite(context, conditionResult, thenResult, elseResult));
422
423 expressionCache.emplace(&expression, result);
424 return result;
425}
426
427boost::any Z3ExpressionAdapter::visit(storm::expressions::VariableExpression const& expression, boost::any const&) {
428 return this->translateExpression(expression.getVariable());
429}
430
431z3::expr Z3ExpressionAdapter::createVariable(storm::expressions::Variable const& variable) {
432 z3::expr z3Variable(context);
433 if (variable.getType().isBooleanType()) {
434 z3Variable = context.bool_const(variable.getName().c_str());
435 } else if (variable.getType().isIntegerType()) {
436 z3Variable = context.int_const(variable.getName().c_str());
437 } else if (variable.getType().isBitVectorType()) {
438 z3Variable = context.bv_const(variable.getName().c_str(), variable.getType().getWidth());
439 } else if (variable.getType().isRationalType()) {
440 z3Variable = context.real_const(variable.getName().c_str());
441 } else {
442 STORM_LOG_THROW(false, storm::exceptions::InvalidTypeException,
443 "Encountered variable '" << variable.getName() << "' with unknown type while trying to create solver variables.");
444 }
445 variableToExpressionMapping.insert(std::make_pair(variable, z3Variable));
446 declarationToVariableMapping.insert(std::make_pair(z3Variable.decl(), variable));
447 return z3Variable;
448}
449
450#endif
451} // namespace adapters
452} // namespace storm
virtual boost::any accept(ExpressionVisitor &visitor, boost::any const &data) const =0
Accepts the given visitor by calling its visit method.
OperatorType getOperatorType() const
Retrieves the operator associated with the expression.
std::shared_ptr< BaseExpression const > const & getSecondOperand() const
Retrieves the second operand of the expression.
std::shared_ptr< BaseExpression const > const & getFirstOperand() const
Retrieves the first operand of the expression.
OperatorType getOperatorType() const
Retrieves the operator associated with the expression.
RelationType getRelationType() const
Retrieves the relation associated with the expression.
bool getValue() const
Retrieves the value of the boolean literal.
BaseExpression const & getBaseExpression() const
Retrieves the base expression underlying this expression object.
ExpressionManager const & getManager() const
Retrieves the manager responsible for this expression.
std::shared_ptr< BaseExpression const > getElseExpression() const
Retrieves the else expression of the if-then-else expression.
std::shared_ptr< BaseExpression const > getCondition() const
Retrieves the condition expression of the if-then-else expression.
std::shared_ptr< BaseExpression const > getThenExpression() const
Retrieves the then expression of the if-then-else expression.
int_fast64_t getValue() const
Retrieves the value of the integer literal.
storm::RationalNumber getValue() const
Retrieves the value of the double literal.
bool isBooleanType() const
Checks whether this type is a boolean type.
Definition Type.cpp:194
std::size_t getWidth() const
Retrieves the bit width of the type, provided that it is a bitvector type.
Definition Type.cpp:226
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
bool isBitVectorType() const
Checks whether this type is a bitvector type.
Definition Type.cpp:202
OperatorType getOperatorType() const
Retrieves the operator associated with this expression.
virtual std::shared_ptr< BaseExpression const > getOperand(uint_fast64_t operandIndex) const override
Retrieves the given operand from the expression.
OperatorType getOperatorType() const
Retrieves the operator associated with this expression.
Variable const & getVariable() const
Retrieves the variable associated with this expression.
ExpressionManager const & getManager() const
Retrieves the manager responsible for this variable.
Definition Variable.cpp:54
Type const & getType() const
Retrieves the type of the variable.
Definition Variable.cpp:50
std::string const & getName() const
Retrieves the name of the variable.
Definition Variable.cpp:46
#define STORM_LOG_WARN(message)
Definition logging.h:35
#define STORM_LOG_THROW_UNCONDITIONALLY(exception, message)
Definition macros.h:48
#define STORM_LOG_ASSERT(cond, message)
Definition macros.h:9
#define STORM_LOG_THROW(cond, exception, message)
Definition macros.h:39
Expression ite(Expression const &condition, Expression const &thenExpression, Expression const &elseExpression)
Expression iff(Expression const &first, Expression const &second)
Expression sum(std::vector< storm::expressions::Expression > const &expressions)
Expression product(std::vector< storm::expressions::Expression > const &expressions)
Expression xclusiveor(Expression const &first, Expression const &second)
Expression implies(Expression const &first, Expression const &second)
SettingsManager const & manager()
Retrieves the settings manager.
TargetType convertNumber(SourceType const &number)
The contract of a DD backend.