25template<
typename ValueType,
bool RawMode>
29 config.set(
"model",
true);
30 context = std::make_unique<z3::context>(config);
31 solver = std::make_unique<z3::optimize>(*context);
34 z3::params params(*context);
35 params.set(
"ctrl_c",
false);
37 expressionAdapter = std::make_unique<storm::adapters::Z3ExpressionAdapter>(*this->manager, *context);
40template<
typename ValueType,
bool RawMode>
45template<
typename ValueType,
bool RawMode>
46Z3LpSolver<ValueType, RawMode>::Z3LpSolver(OptimizationDirection
const& optDir) : Z3LpSolver(
"", optDir) {
50template<
typename ValueType,
bool RawMode>
55template<
typename ValueType,
bool RawMode>
56Z3LpSolver<ValueType, RawMode>::~Z3LpSolver() {
60template<
typename ValueType,
bool RawMode>
61void Z3LpSolver<ValueType, RawMode>::update()
const {
63 lastCheckObjectiveValue.reset(
nullptr);
64 lastCheckModel.reset(
nullptr);
65 this->currentModelHasBeenOptimized =
false;
68template<
typename ValueType,
bool RawMode>
69typename Z3LpSolver<ValueType, RawMode>::Variable Z3LpSolver<ValueType, RawMode>::addVariable(std::string
const& name, VariableType
const& type,
70 std::optional<ValueType>
const& lowerBound,
71 std::optional<ValueType>
const& upperBound,
72 ValueType objectiveFunctionCoefficient) {
73 STORM_LOG_ASSERT(isIncremental || !this->
manager->hasVariable(name),
"Variable with name " << name <<
" already exists.");
75 if (type == VariableType::Binary) {
76 solver->add(expressionAdapter->translateExpression(newVariable.
getExpression() >= this->manager->integer(0)));
77 solver->add(expressionAdapter->translateExpression(newVariable.
getExpression() <= this->manager->integer(1)));
80 solver->add(expressionAdapter->translateExpression(newVariable.
getExpression() >= this->manager->rational(*lowerBound)));
83 solver->add(expressionAdapter->translateExpression(newVariable.
getExpression() <= this->manager->rational(*upperBound)));
86 optimizationSummands.push_back(this->
manager->rational(objectiveFunctionCoefficient) * newVariable);
89 if constexpr (RawMode) {
90 rawIndexToVariableMap.push_back(newVariable);
91 return rawIndexToVariableMap.size() - 1;
97template<
typename ValueType,
bool RawMode>
98void Z3LpSolver<ValueType, RawMode>::addConstraint(std::string
const& name, Constraint
const& constraint) {
99 if constexpr (RawMode) {
101 STORM_LOG_ASSERT(constraint.lhsVariableIndices.size() == constraint.lhsCoefficients.size(),
"Number of variables and coefficients do not match.");
102 std::vector<storm::expressions::Expression> lhsSummands;
103 lhsSummands.reserve(constraint.lhsVariableIndices.size());
104 auto varIt = constraint.lhsVariableIndices.cbegin();
105 auto varItEnd = constraint.lhsVariableIndices.cend();
106 auto coefIt = constraint.lhsCoefficients.cbegin();
107 for (; varIt != varItEnd; ++varIt, ++coefIt) {
108 lhsSummands.push_back(rawIndexToVariableMap[*varIt] * this->
manager->rational(*coefIt));
110 if (lhsSummands.empty()) {
115 solver->add(expressionAdapter->translateExpression(constraintExpr));
117 STORM_LOG_THROW(constraint.isRelationalExpression(), storm::exceptions::InvalidArgumentException,
"Illegal constraint is not a relational expression.");
119 "Illegal constraint uses inequality operator.");
120 solver->add(expressionAdapter->translateExpression(constraint));
124template<
typename ValueType,
bool RawMode>
125void Z3LpSolver<ValueType, RawMode>::addIndicatorConstraint(std::string
const& name, Variable indicatorVariable,
bool indicatorValue,
126 Constraint
const& constraint) {
127 if constexpr (RawMode) {
128 STORM_LOG_THROW(
false, storm::exceptions::NotImplementedException,
"Indicator constraints not implemented in RawMode.");
131 STORM_LOG_THROW(indicatorVariable.hasIntegerType(), storm::exceptions::InvalidArgumentException,
132 "Variable " << indicatorVariable.getName() <<
" is not binary.");
133 STORM_LOG_THROW(constraint.isRelationalExpression(), storm::exceptions::InvalidArgumentException,
"Illegal constraint is not a relational expression.");
135 "Illegal constraint uses inequality operator.");
139 auto indicatorConstraint = (indicatorVariable.getExpression() == invertedIndicatorVal) || constraint;
140 solver->add(expressionAdapter->translateExpression(indicatorConstraint));
144template<
typename ValueType,
bool RawMode>
145void Z3LpSolver<ValueType, RawMode>::optimize()
const {
154 if (!optimizationSummands.empty()) {
157 z3::optimize::handle optFuncHandle = this->getOptimizationDirection() == OptimizationDirection::Minimize
158 ? solver->minimize(expressionAdapter->translateExpression(optimizationFunction))
159 : solver->maximize(expressionAdapter->translateExpression(optimizationFunction));
161 z3::check_result chkRes = solver->check();
162 STORM_LOG_THROW(chkRes != z3::unknown, storm::exceptions::InvalidStateException,
"Unable to solve LP problem with Z3: Check result is unknown.");
167 lastCheckInfeasible = (chkRes == z3::unsat);
168 if (lastCheckInfeasible) {
169 lastCheckUnbounded =
false;
172 lastCheckObjectiveValue = std::make_unique<z3::expr>(solver->upper(optFuncHandle));
174 STORM_LOG_ASSERT(lastCheckObjectiveValue->is_app(),
"Failed to convert Z3 expression. Encountered unknown expression type.");
175 lastCheckUnbounded = (lastCheckObjectiveValue->decl().decl_kind() != Z3_OP_ANUM);
176 if (lastCheckUnbounded) {
177 lastCheckObjectiveValue.reset(
nullptr);
180 STORM_LOG_ASSERT(std::string(Z3_get_numeral_string(*context, *lastCheckObjectiveValue)) ==
181 std::string(Z3_get_numeral_string(*context, solver->lower(optFuncHandle))),
182 "Lower and Upper Approximation of z3LPSolver result do not match.");
183 lastCheckModel = std::make_unique<z3::model>(solver->get_model());
188 this->currentModelHasBeenOptimized =
true;
191template<
typename ValueType,
bool RawMode>
192bool Z3LpSolver<ValueType, RawMode>::isInfeasible()
const {
193 STORM_LOG_THROW(this->currentModelHasBeenOptimized, storm::exceptions::InvalidStateException,
194 "Illegal call to Z3LpSolver<ValueType, RawMode>::isInfeasible: model has not been optimized.");
195 return lastCheckInfeasible;
198template<
typename ValueType,
bool RawMode>
199bool Z3LpSolver<ValueType, RawMode>::isUnbounded()
const {
200 STORM_LOG_THROW(this->currentModelHasBeenOptimized, storm::exceptions::InvalidStateException,
201 "Illegal call to Z3LpSolver<ValueType, RawMode>::isUnbounded: model has not been optimized.");
202 return lastCheckUnbounded;
205template<
typename ValueType,
bool RawMode>
206bool Z3LpSolver<ValueType, RawMode>::isOptimal()
const {
207 STORM_LOG_THROW(this->currentModelHasBeenOptimized, storm::exceptions::InvalidStateException,
208 "Illegal call to Z3LpSolver<ValueType, RawMode>::isOptimal: model has not been optimized.");
209 return !lastCheckInfeasible && !lastCheckUnbounded;
212template<
typename ValueType,
bool RawMode>
214 if (!this->isOptimal()) {
215 STORM_LOG_THROW(!this->isInfeasible(), storm::exceptions::InvalidAccessException,
"Unable to get Z3 solution from infeasible model.");
216 STORM_LOG_THROW(!this->isUnbounded(), storm::exceptions::InvalidAccessException,
"Unable to get Z3 solution from unbounded model.");
217 STORM_LOG_THROW(
false, storm::exceptions::InvalidAccessException,
"Unable to get Z3 solution from unoptimized model.");
221 if constexpr (RawMode) {
222 STORM_LOG_ASSERT(variable < rawIndexToVariableMap.size(),
"Requested variable out of range.");
223 z3::expr z3Var = this->expressionAdapter->translateExpression(rawIndexToVariableMap[variable]);
224 return this->expressionAdapter->translateExpression(lastCheckModel->eval(z3Var,
true));
226 STORM_LOG_ASSERT(variable.getManager() == this->getManager(),
"Requested variable is managed by a different manager.");
227 z3::expr z3Var = this->expressionAdapter->translateExpression(variable);
228 return this->expressionAdapter->translateExpression(lastCheckModel->eval(z3Var,
true));
232template<
typename ValueType,
bool RawMode>
233ValueType Z3LpSolver<ValueType, RawMode>::getContinuousValue(Variable
const& variable)
const {
239 "Expected a rational literal while obtaining the value of a continuous variable. Got " << value <<
"instead.");
243template<
typename ValueType,
bool RawMode>
244int_fast64_t Z3LpSolver<ValueType, RawMode>::getIntegerValue(Variable
const& variable)
const {
247 "Expected an integer literal while obtaining the value of an integer variable. Got " << value <<
"instead.");
251template<
typename ValueType,
bool RawMode>
252bool Z3LpSolver<ValueType, RawMode>::getBinaryValue(Variable
const& variable)
const {
256 "Expected an integer literal while obtaining the value of a binary variable. Got " << value <<
"instead.");
258 STORM_LOG_THROW((val == 0 || val == 1), storm::exceptions::ExpressionEvaluationException,
259 "Tried to get a binary value for a variable that is neither 0 nor 1.");
263template<
typename ValueType,
bool RawMode>
264ValueType Z3LpSolver<ValueType, RawMode>::getObjectiveValue()
const {
265 if (!this->isOptimal()) {
266 STORM_LOG_THROW(!this->isInfeasible(), storm::exceptions::InvalidAccessException,
"Unable to get Z3 solution from infeasible model.");
267 STORM_LOG_THROW(!this->isUnbounded(), storm::exceptions::InvalidAccessException,
"Unable to get Z3 solution from unbounded model.");
268 STORM_LOG_THROW(
false, storm::exceptions::InvalidAccessException,
"Unable to get Z3 solution from unoptimized model.");
270 STORM_LOG_ASSERT(lastCheckObjectiveValue,
"Objective value has not been stored.");
277 "Expected a rational literal while obtaining the objective result. Got " << result <<
"instead.");
281template<
typename ValueType,
bool RawMode>
282void Z3LpSolver<ValueType, RawMode>::writeModelToFile(std::string
const& filename)
const {
283 std::ofstream stream;
285 stream << Z3_optimize_to_string(*context, *solver);
289template<
typename ValueType,
bool RawMode>
290void Z3LpSolver<ValueType, RawMode>::push() {
291 STORM_LOG_THROW(!RawMode, storm::exceptions::NotImplementedException,
"Incremental solving is not supported in Raw mode.");
292 incrementaOptimizationSummandIndicators.push_back(optimizationSummands.size());
296template<
typename ValueType,
bool RawMode>
297void Z3LpSolver<ValueType, RawMode>::pop() {
298 STORM_LOG_THROW(!RawMode, storm::exceptions::NotImplementedException,
"Incremental solving is not supported in Raw mode.");
299 STORM_LOG_ASSERT(!incrementaOptimizationSummandIndicators.empty(),
"Tried to pop() without push()ing first.");
302 optimizationSummands.resize(incrementaOptimizationSummandIndicators.back());
303 incrementaOptimizationSummandIndicators.pop_back();
304 isIncremental =
true;
307template<
typename ValueType,
bool RawMode>
308void Z3LpSolver<ValueType, RawMode>::setMaximalMILPGap(ValueType
const&,
bool) {
313template<
typename ValueType,
bool RawMode>
314ValueType Z3LpSolver<ValueType, RawMode>::getMILPGap(
bool relative)
const {
319template<
typename ValueType,
bool RawMode>
322 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
323 "requires this support.");
326template<
typename ValueType,
bool RawMode>
329 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
330 "requires this support.");
333template<
typename ValueType,
bool RawMode>
336 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
337 "requires this support.");
340template<
typename ValueType,
bool RawMode>
343 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
344 "requires this support.");
347template<
typename ValueType,
bool RawMode>
350template<
typename ValueType,
bool RawMode>
352 std::optional<ValueType>
const&, std::optional<ValueType>
const&,
355 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
356 "requires this support.");
359template<
typename ValueType,
bool RawMode>
362 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
363 "requires this support.");
366template<
typename ValueType,
bool RawMode>
369 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
370 "requires this support.");
373template<
typename ValueType,
bool RawMode>
376 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
377 "requires this support.");
380template<
typename ValueType,
bool RawMode>
383 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
384 "requires this support.");
387template<
typename ValueType,
bool RawMode>
390 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
391 "requires this support.");
394template<
typename ValueType,
bool RawMode>
397 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
398 "requires this support.");
401template<
typename ValueType,
bool RawMode>
404 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
405 "requires this support.");
408template<
typename ValueType,
bool RawMode>
411 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
412 "requires this support.");
415template<
typename ValueType,
bool RawMode>
418 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
419 "requires this support.");
422template<
typename ValueType,
bool RawMode>
425 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
426 "requires this support.");
429template<
typename ValueType,
bool RawMode>
432 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
433 "requires this support.");
436template<
typename ValueType,
bool RawMode>
439 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
440 "requires this support.");
443template<
typename ValueType,
bool RawMode>
446 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
447 "requires this support.");
450template<
typename ValueType,
bool RawMode>
453 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
454 "requires this support.");
457template<
typename ValueType,
bool RawMode>
460 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
461 "requires this support.");
464template<
typename ValueType,
bool RawMode>
467 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
468 "requires this support.");
471template<
typename ValueType,
bool RawMode>
474 "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that "
475 "requires this support.");
IntegerLiteralExpression const & asIntegerLiteralExpression() const
RationalLiteralExpression const & asRationalLiteralExpression() const
virtual bool isRationalLiteralExpression() const
virtual bool isIntegerLiteralExpression() const
BaseExpression const & getBaseExpression() const
Retrieves the base expression underlying this expression object.
int_fast64_t getValue() const
Retrieves the value of the integer literal.
storm::RationalNumber getValue() const
Retrieves the value of the double literal.
storm::expressions::Expression getExpression() const
Retrieves an expression that represents the variable.
An interface that captures the functionality of an LP solver.
A class that implements the LpSolver interface using Z3.
virtual ValueType getObjectiveValue() const override
Retrieves the value of the objective function.
typename LpSolver< ValueType, RawMode >::Variable Variable
virtual void update() const override
Updates the model to make the variables that have been declared since the last call to update usable.
virtual int_fast64_t getIntegerValue(Variable const &variable) const override
Retrieves the value of the integer variable with the given name.
virtual Variable addVariable(std::string const &name, VariableType const &type, std::optional< ValueType > const &lowerBound=std::nullopt, std::optional< ValueType > const &upperBound=std::nullopt, ValueType objectiveFunctionCoefficient=0) override
typename LpSolver< ValueType, RawMode >::Constraint Constraint
virtual void writeModelToFile(std::string const &filename) const override
Writes the current LP problem to the given file.
virtual bool isUnbounded() const override
Retrieves whether the model was found to be infeasible.
virtual ValueType getContinuousValue(Variable const &variable) const override
Retrieves the value of the continuous variable with the given name.
Z3LpSolver()
Constructs a solver without a name.
virtual void addIndicatorConstraint(std::string const &name, Variable indicatorVariable, bool indicatorValue, Constraint const &constraint) override
Adds the given indicator constraint to the LP problem: "If indicatorVariable == indicatorValue,...
virtual ValueType getMILPGap(bool relative) const override
Returns the obtained gap after a call to optimize().
virtual void setMaximalMILPGap(ValueType const &gap, bool relative) override
Specifies the maximum difference between lower- and upper objective bounds that triggers termination.
virtual void push() override
Pushes a backtracking point on the solver's stack.
virtual void addConstraint(std::string const &name, Constraint const &constraint) override
Adds a the given constraint to the LP problem.
Z3LpSolver(std::string const &name, OptimizationDirection const &optDir)
Constructs a solver with the given name and optimization direction.
virtual bool isOptimal() const override
Retrieves whether the model was found to be optimal, i.e.
typename LpSolver< ValueType, RawMode >::VariableType VariableType
virtual ~Z3LpSolver()
Destructs a solver by freeing the pointers to Z3's structures.
virtual bool isInfeasible() const override
Retrieves whether the model was found to be infeasible.
virtual void pop() override
Pops a backtracking point from the solver's stack.
virtual bool getBinaryValue(Variable const &variable) const override
Retrieves the value of the binary variable with the given name.
virtual void optimize() const override
Optimizes the LP problem previously constructed.
#define STORM_LOG_ASSERT(cond, message)
#define STORM_LOG_THROW(cond, exception, message)
SFTBDDChecker::ValueType ValueType
Expression makeBinaryRelationExpression(Expression const &first, Expression const &second, RelationType const &reltype)
Expression sum(std::vector< storm::expressions::Expression > const &expressions)
void closeFile(std::ofstream &stream)
Close the given file after writing.
void openFile(std::string const &filepath, std::ofstream &filestream, bool append=false, bool silent=false)
Open the given file for writing.
SettingsManager const & manager()
Retrieves the settings manager.
bool isZero(ValueType const &a)
TargetType convertNumber(SourceType const &number)
The contract of a DD backend.