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

本小妞迷上赌 提交于 2020-04-18 00:48:59

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/61198472/how-to-get-existing-constraints-out-of-a-z3-solver-object-in-z3py

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!