4

在公式中替换函数符号(用另一个函数)的最佳方法是什么?Z3pysubstitute似乎只适用于表达式,而我现在所做的是尝试猜测可以应用该函数的所有可能的 consts/vars 组合,然后用另一个函数的应用程序替换这些组合。有没有更好的方法来做到这一点?

4

1 回答 1

4

我们可以实现一个简单的自底向上重写器,给定一个 term ,s一个函数f和 termt将替换每个f-application f(r_1, ..., r_n)。我使用符号来表示通过将自由变量替换为术语, ...,获得的术语。st[r_1, ..., r_n]t[r_1, ..., r_n]tr_1r_n

重写器可以通过 Z3 API 实现。我使用 anAstMap来缓存结果,并使用todolist 来存储仍需处理的表达式。

这是一个简单的例子,它用in替换了f表单的 -applications 。f(t)g(t+1)s

x = Var(0, IntSort())
print rewrite(s, f, g(x + 1))

这是代码和更多示例。请注意,我只在一小部分示例中测试了代码。

from z3 import *

def update_term(t, args):
    # Update the children of term t with args. 
    # len(args) must be equal to the number of children in t.
    # If t is an application, then len(args) == t.num_args()
    # If t is a quantifier, then len(args) == 1
    n = len(args)
    _args = (Ast * n)()
    for i in range(n):
        _args[i] = args[i].as_ast()
    return z3._to_expr_ref(Z3_update_term(t.ctx_ref(), t.as_ast(), n, _args), t.ctx)

def rewrite(s, f, t):
    """
    Replace f-applications f(r_1, ..., r_n) with t[r_1, ..., r_n] in s.
    """
    todo = [] # to do list
    todo.append(s)
    cache = AstMap(ctx=s.ctx)
    while todo:
        n = todo[len(todo) - 1]
        if is_var(n):
            todo.pop()
            cache[n] = n
        elif is_app(n):
            visited  = True
            new_args = []
            for i in range(n.num_args()):
                arg = n.arg(i)
                if not arg in cache:
                    todo.append(arg)
                    visited = False
                else:
                    new_args.append(cache[arg])
            if visited:
                todo.pop()
                g = n.decl()
                if eq(g, f):
                    new_n = substitute_vars(t, *new_args)
                else:
                    new_n = update_term(n, new_args)
                cache[n] = new_n
        else:
            assert(is_quantifier(n))
            b = n.body()
            if b in cache:
                todo.pop()
                new_n = update_term(n, [ cache[b] ])
                cache[n] = new_n
            else:
                todo.append(b)
    return cache[s]

f = Function('f', IntSort(), IntSort())
a, b = Ints('a b')
s = Or(f(a) == 0, f(a) == 1, f(a+a) == 2)
# Example 1: replace all f-applications with b
print rewrite(s, f, b)

# Example 2: replace all f-applications f(t) with g(t+1)
g = Function('g', IntSort(), IntSort())
x = Var(0, IntSort())
print rewrite(s, f, g(x + 1))

# Now, f and g are binary functions.
f = Function('f', IntSort(), IntSort(), IntSort())
g = Function('g', IntSort(), IntSort(), IntSort())

# Example 3: replace all f-applications f(t1, t2) with g(t2, t1)
s = Or(f(a, f(a, b)) == 0, f(b, a) == 1, f(f(1,0), 0) == 2)
# The first argument is variable 0, and the second is variable 1.
y = Var(1, IntSort())
print rewrite(s, f, g(y, x))

# Example 4: quantifiers
s = ForAll([a], f(a, b) >= 0)
print rewrite(s, f, g(y, x + 1))
于 2013-03-06T01:20:50.360 回答