简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM