Jack Feng
Jack Feng

Reputation: 971

How to get existing constraints out of a Z3 Solver object in z3py?

For example, I want to get the existing constraints from s and into the Optimize object.

from z3 import *

a = Int('a')
x = Int('x')
b = Array('I', IntSort(), IntSort())
s = Solver()

s.add(a >= 0)
s.add(x == 0)
s.add(Select(b, 0) == 10)
s.add(Select(b, x) >= a)

opt = Optimize()
opt.add(s.constraints)

obj1 = opt.maximize(a)
obj2 = opt.minimize(a)

opt.set('priority', 'box')   # Setting Boxed Multi-Objective Optimization

is_sat = opt.check()
assert is_sat

print("Max(a): " + str(obj1.value()))
print("Min(a): " + str(obj2.value()))

Then the result would be like this.

~$ python test.py 
Max(a): 10
Min(a): 0

Upvotes: 0

Views: 1955

Answers (1)

Patrick Trentin
Patrick Trentin

Reputation: 7342

If one wants to get a vector of all constraints added to a Solver (or Optimize) instance, one can use the method assertions():

 |  assertions(self)
 |      Return an AST vector containing all added constraints.
 |      
 |      >>> s = Solver()
 |      >>> s.assertions()
 |      []
 |      >>> a = Int('a')
 |      >>> s.add(a > 0)
 |      >>> s.add(a < 10)
 |      >>> s.assertions()
 |      [a > 0, a < 10]

[source: z3 docs]

Example:

from z3 import *

a = Int('a')
x = Int('x')
b = Array('I', IntSort(), IntSort())

s = Solver()

s.add(a >= 0)
s.add(x == 0)
s.add(Select(b, 0) == 10)
s.add(Select(b, x) >= a)

opt = Optimize()

opt.add(s.assertions())

obj1 = opt.maximize(a)
obj2 = opt.minimize(a)

opt.set('priority', 'box')

is_sat = opt.check()
assert is_sat

print("Max(a): " + str(obj1.value()))
print("Min(a): " + str(obj2.value()))

Output:

~$ python test.py 
Max(a): 10
Min(a): 0

Upvotes: 3

Related Questions