python - 表示在图 G 中存在一个函数 `path(x, y)`
问题描述
我试图通过 Z3Py 中的边通过顶点的连通性来形式化图中存在的路径的属性。
我在 z3py 中有以下定义:
from z3 import *
# Set of vertices present in the graph
V = EmptySet()
V = SetAdd(V, 0)
V = SetAdd(V, 1)
V = SetAdd(V, 2)
Edge = DataType('Edge')
Edge.declare('edge', ('first', IntSort()), ('second', IntSort()))
Edge = Edge.create()
def makeEdge(i, j):
return Edge.edge(i, j)
# Set of directional edges in the graph
E = EmptySet()
E = SetAdd(E, makeEdge(0, 1))
E = SetAdd(E, makeEdge(1, 2))
有了上面的定义,我们可以说一个图有 2个G
集合:它们是存在于.V
E
G
我现在为成员定义谓词并将它们固定到求解器中
x = Int('x')
y = Int('y')
IsVertex = Function('IsVertex', IntSort(), BoolSort())
IsEdge = Function('IsEdge', IntSort(), IntSort(), BoolSort())
vertex_axiom = ForAll([x], IsMember(x, V) == IsVertex(x))
edge_axiom = ForAll([x, y], IsMember(makeEdge(x, y), E) == IsEdge(x, y))
s = Solver()
s.add(vertex_axiom)
s.add(edge_axiom)
上面的内容sat
在s.check()
被调用时返回。使用随机值作为函数的输入进行测试,IsVertex
并且仅当在集合中找到该值且符合预期IsEdge
时才返回 true 。V
E
现在我尝试定义一个谓词函数IsPath(x, z)
wrtG
当IsPath(x, z)
且仅当顶点之间存在路径时应该返回 truex
和z
.
z = Int('z')
IsPath = Function('IsPath', IntSort(), IntSort(), BoolSort())
# base case
path_axiom1 = ForAll([x, z], Implies(IsEdge(x, z), IsPath(x, z))
# recurrence case
'''
A path exists between x, z if and only if there is a vertex y such that
x, y is an edge in G and y, z is a path
'''
path_axiom2 = ForAll([x, z], Exists([y], And(And(IsVertex(y), IsEdge(x, y)), IsPath(y, z) == IsPath(x, z))))
使用第一个代码片段中定义的图形将其修复到求解器中:
s.add(path_axiom1)
s.add(path_axiom2)
print(s.check())
返回unsat
有意义,因为路径不存在ForAll
顶点对。
如何更好地改进我的表达式以仅引用符合路径公式的顶点并将其添加到我的求解器?
谢谢你。
解决方案
推荐阅读
- applescript - AppleScript - 语法错误:预期的行尾但找到“””
- python-3.x - 使用 numpy 数组比较两个相似的 PIL 图像不起作用
- python - 更改 seaborn pairplot 对角线颜色
- scala - Scala 是否可以异步运行循环?
- java - java中斐波那契堆consolidate方法的实现,IndexofBoundsException的错误
- asp.net - 如何在aspx页面中获取请求值
- c - scanf() 的 char 函数采用 \n 输入而不是 char?
- node.js - 持久化 NodeJS 套接字
- python - Python 中的 Selenium 代码会产生语法错误
- javascript - 如何使用jQuery删除空格字符后的文本?