如何从 z3py 中的 Z3 Solver 对象中获取现有约束? [英] How to get existing constraints out of a Z3 Solver object in z3py?

查看:34
本文介绍了如何从 z3py 中的 Z3 Solver 对象中获取现有约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想将现有的约束从 s 获取到 Optimize 对象中.

from z3 import *a = Int('a')x = Int('x')b = Array('I', IntSort(), IntSort())s = 求解器()s.add(a >= 0)s.add(x == 0)s.add(选择(b, 0) == 10)s.add(Select(b, x) >= a)选择 = 优化()opt.add(s.constraints)obj1 = opt.maximize(a)obj2 = opt.minimize(a)opt.set('priority', 'box') # 设置盒装多目标优化is_sat = opt.check()断言 is_satprint("Max(a):" + str(obj1.value()))print("Min(a):" + str(obj2.value()))

那么结果会是这样.

~$ python test.py最大(一):10最小(一):0

解决方案

如果想要将所有约束的向量添加到 Solver(或 Optimize)实例,可以使用assertions()方法:

<块引用>

<代码> |断言(自我)|返回一个包含所有添加约束的 AST 向量.||>>>s = 求解器()|>>>s.断言()|[]|>>>a = Int('a')|>>>s.add(a > 0)|>>>s.add(a <10)|>>>s.断言()|[一个>0,a<10]

[来源:z3 文档]

示例:

from z3 import *a = Int('a')x = Int('x')b = Array('I', IntSort(), IntSort())s = 求解器()s.add(a >= 0)s.add(x == 0)s.add(选择(b, 0) == 10)s.add(Select(b, x) >= a)选择 = 优化()opt.add(s.assertions())obj1 = opt.maximize(a)obj2 = opt.minimize(a)opt.set('优先级', 'box')is_sat = opt.check()断言 is_satprint("Max(a):" + str(obj1.value()))print("Min(a):" + str(obj2.value()))

输出:

~$ python test.py最大(一):10最小(一):0

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

这篇关于如何从 z3py 中的 Z3 Solver 对象中获取现有约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆