问题
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