Z3 does not support optimization (maximization / minimization) of objective functions or variables. We plan to add such features, but this will not happen this year. In the current version, we can βoptimizeβ the objective function by solving several problems, where at each iteration we add additional restrictions. We know that we have found the optimum when the problem becomes unsatisfactory. Here is a small Python script that illustrates the idea. script maximizes the value of the X variable. To minimize it, we just need to replace s.add(X > last_model[X]) with s.add(X < last_model[X]) . This script is very naive, it performs a "linear search". It can be improved in many ways, but it demonstrates the basic idea.
You can also try the script online: http://rise4fun.com/Z3Py/KI1
See the following related question: Define upper / lower bounds for variables in an arbitrary propositional formula
from z3 import * # Given formula F, find the model the maximizes the value of X # using at-most M iterations. def max(F, X, M): s = Solver() s.add(F) last_model = None i = 0 while True: r = s.check() if r == unsat: if last_model != None: return last_model else: return unsat if r == unknown: raise Z3Exception("failed") last_model = s.model() s.add(X > last_model[X]) i = i + 1 if (i > M): raise Z3Exception("maximum not found, maximum number of iterations was reached") x, y = Ints('x y') F = [x > 0, x < 10, x == 2*y] print max(F, x, 10000)
source share