How to check in Z3py whether the expression contains a specific variable or expression? - z3

I'm using z3py, how do I check whether an expression contains a given variable or expression? For example,
x = Int('x')
expr = x + 1
So, expr should contains variable x.
I've checked the z3.py source code, but I didn't find a solution. Any idea? Thanks.

You can write a simple recursive descent walk over the expression:
from z3 import *
def contains(x, e):
return x.__repr__() == e.__repr__() or any([contains(x, c) for c in e.children()])
x, y, z = Ints('x y z')
expr = x + 2 * y
print(contains(x, expr))
print(contains(y, expr))
print(contains(z, expr))
print(contains(x+2, expr))
print(contains(2*y, expr))
print(contains(y*2, expr))
print(contains(1, IntVal(2)))
print(contains(1, IntVal(1)))
print(contains(x, x))
print(contains(x, y))
This prints:
True
True
False
False
True
False
False
True
True
False
However, I should caution that in typical z3 programming you already know what your variables are. (After all, you have to declare them explicitly!) So, unless you're writing some high-level library code, you should simply keep track of what variables you have and just check in this list. Recursive-descents like this can be expensive for large expressions.

Related

How to use substitute method in Z3 to replace a variable to True its not working and it replaces with ζ1 and also simplify method doesn't work?

This is the following code . I also tried to convert it into Bool and BoolRef but here also it didn't work:-
print(A)
substitute(A, (Var[0], Bool(True) )) # where Var[0] = x_0_2
Output:-
And(And(And(And(x_0_3, Not(x_0_2)), Not(x_0_1)), Not(x_0_0)),
And(And(And(x_1_3 == x_0_0, x_1_2 == x_0_3),
x_1_1 == x_0_2),
x_1_0 == x_0_1))
x_0_3 ∧ ¬ζ1 ∧ ¬x_0_1 ∧ ¬x_0_0 ∧ x_1_3 = x_0_0 ∧ x_1_2 = x_0_3 ∧ x_1_1 = ζ1 ∧ x_1_0 = x_0_1
Stack-overflow works the best if you post code that people can run on their own; without seeing other parts of what you are doing it's impossible for other people to figure out what else might cause issues in your code.
Having said that, here's how you'd substitute True for a variable:
from z3 import *
x, y = Bools('x y')
expr = And(x, Or(y, And(x, y)))
print expr
expr2 = substitute(expr, (x, BoolVal(True)))
print expr2
print simplify(expr2)
When I run this, I get:
And(x, Or(y, And(x, y)))
And(True, Or(y, And(True, y)))
y
which shows the effect of the substitution and the further simplification of the expression. Note the use of the term BoolVal(True) to get access to the constant value True as a boolean expression.

How to get every clauses of a CNF formula in Z3

like in the code below, Is there any function in Z3 to get all the clauses of a formula(as a CNF)?
x = Boolean('x')
y = Boolean('y')
f = And(x, Or(x,y),And(x,Not(x,y))
# can I get all the clauses of formula f stored in a list
You can do something like the following:
from z3 import *
x = Bool('x') # Note: Bool() rather than Boolean()
y = Bool('y')
z = Bool('z')
f = And(x, Or(x,y), And(x, z == Not(y)))
# from https://stackoverflow.com/a/18003288/1911064
g = Goal()
g.add(f)
# use describe_tactics() to get to know the tactics available
t = Tactic('tseitin-cnf')
clauses = t(g)
for clause in clauses[0]:
print(clause)
Output is a list of disjunctive clauses:
x
Or(x, y)
Or(y, z)
Or(Not(y), Not(z))
Your original expression is not satisfiable.
What is Not(x, y) supposed to do?
As simpler way to convert (nested) Boolean expressions to CNF is provided by bc2cnf.

Understanding quantifier traversing in Z3

I'm trying to understand traversing quantified formula in z3 (i'm using z3py). Have no idea how to pickup the quantified variables. For example in code shown below i'm trying to print the same formula and getting error.
from z3 import *
def traverse(e):
if is_quantifier(e):
var_list = []
if e.is_forall():
for i in range(e.num_vars()):
var_list.append(e.var_name(i))
return ForAll (var_list, traverse(e.body()))
x, y = Bools('x y')
fml = ForAll(x, ForAll (y, And(x,y)))
same_formula = traverse( fml )
print same_formula
With little search i got to know that z3 uses De Bruijn index and i have to get something like Var(1, BoolSort()). I can think of using var_sort() but how to get the formula to return the variable correctly. Stuck here for some time.
var_list is a list of strings, but ForAll expects a list of constants. Also, traverse should return e when it's not a quantifier. Here's a modified example:
from z3 import *
def traverse(e):
if is_quantifier(e):
var_list = []
if e.is_forall():
for i in range(e.num_vars()):
c = Const(e.var_name(i) + "-traversed", e.var_sort(i))
var_list.append(c)
return ForAll (var_list, traverse(e.body()))
else:
return e
x, y = Bools('x y')
fml = ForAll(x, ForAll (y, And(x,y)))
same_formula = traverse( fml )
print(same_formula)

Z3 array: why Select() does not return value saved by Store()?

I have simple Z3 python code like below. I expect the "print" line will return me "y" which was stored in the line above it. Instead, I got back "A[x]" as result.
I = IntSort()
A = Array('A', I, I)
x = Int('x')
y = Int('y')
Store(A, x, y)
print Select(A,x)
Why does not Select() return the value stored by Store()?
Thanks.
There are two things to note:
First:
When you write
Store(A, x, y)
You create a term with three arguments , A, x, and y.
There is no side-effect to A.
You can create a name for this term by writing
B = Store(A,x,y)
Second:
Z3 does not simplify terms unless you want it to.
The python API exposes a simplification function called simplify.
You can obtain the reduced term by calling the simplifier.
The example is:
I = IntSort()
A = Array('A', I, I)
x = Int('x')
y = Int('y')
B = Store(A, x, y)
print Select(B,x)
print simplify (Select(B,x))

F# Power issues which accepts both arguments to be bigints

I am currently experimenting with F#. The articles found on the internet are helpful, but as a C# programmer, I sometimes run into situations where I thought my solution would help, but it did not or just partially helped.
So my lack of knowledge of F# (and most likely, how the compiler works) is probably the reason why I am totally flabbergasted sometimes.
For example, I wrote a C# program to determine perfect numbers. It uses the known form of Euclids proof, that a perfect number can be formed from a Mersenne Prime 2p−1(2p−1) (where 2p-1 is a prime, and p is denoted as the power of).
Since the help of F# states that '**' can be used to calculate a power, but uses floating points, I tried to create a simple function with a bitshift operator (<<<) (note that I've edit this code for pointing out the need):
let PowBitShift (y:int32) = 1 <<< y;;
However, when running a test, and looking for performance improvements, I also tried a form which I remember from using Miranda (a functional programming language also), which uses recursion and a pattern matcher to calculate the power. The main benefit is that I can use the variable y as a 64-bit Integer, which is not possible with the standard bitshift operator.
let rec Pow (x : int64) (y : int64) =
match y with
| 0L -> 1L
| y -> x * Pow x (y - 1L);;
It turns out that this function is actually faster, but I cannot (yet) understand the reason why. Perhaps it is a less intellectual question, but I am still curious.
The seconds question then would be, that when calculating perfect numbers, you run into the fact that the int64 cannot display the big numbers crossing after finding the 9th perfectnumber (which is formed from the power of 31). I am trying to find out if you can use the BigInteger object (or bigint type) then, but here my knowledge of F# is blocking me a bit. Is it possible to create a powerfunction which accepts both arguments to be bigints?
I currently have this:
let rec PowBigInt (x : bigint) (y : bigint) =
match y with
| bigint.Zero -> 1I
| y -> x * Pow x (y - 1I);;
But it throws an error that bigint.Zero is not defined. So I am doing something wrong there as well. 0I is not accepted as a replacement, since it gives this error:
Non-primitive numeric literal constants cannot be used in pattern matches because they
can be mapped to multiple different types through the use of a NumericLiteral module.
Consider using replacing with a variable, and use 'when <variable> = <constant>' at the
end of the match clause.
But a pattern matcher cannot use a 'when' statement. Is there another solution to do this?
Thanks in advance, and please forgive my long post. I am only trying to express my 'challenges' as clear as I can.
I failed to understand why you need y to be an int64 or a bigint. According to this link, the biggest known Mersenne number is the one with p = 43112609, where p is indeed inside the range of int.
Having y as an integer, you can use the standard operator pown : ^T -> int -> ^T instead because:
let Pow (x : int64) y = pown x y
let PowBigInt (x: bigint) y = pown x y
Regarding your question of pattern matching bigint, the error message indicates quite clearly that you can use pattern matching via when guards:
let rec PowBigInt x y =
match y with
| _ when y = 0I -> 1I
| _ -> x * PowBigInt x (y - 1I)
I think the easiest way to define PowBigInt is to use if instead of pattern matching:
let rec PowBigInt (x : bigint) (y : bigint) =
if y = 0I then 1I
else x * PowBigInt x (y - 1I)
The problem is that bigint.Zero is a static property that returns the value, but patterns can only contain (constant) literals or F# active patterns. They can't directly contain property (or other) calls. However, you can write additional constraints in where clause if you still prefer match:
let rec PowBigInt (x : bigint) (y : bigint) =
match y with
| y when y = bigint.Zero -> 1I
| y -> x * PowBigInt x (y - 1I)
As a side-note, you can probably make the function more efficent using tail-recursion (the idea is that if a function makes recursive call as the last thing, then it can be compiled more efficiently):
let PowBigInt (x : bigint) (y : bigint) =
// Recursive helper function that stores the result calculated so far
// in 'acc' and recursively loops until 'y = 0I'
let rec PowBigIntHelper (y : bigint) (acc : bigint) =
if y = 0I then acc
else PowBigIntHelper (y - 1I) (x * acc)
// Start with the given value of 'y' and '1I' as the result so far
PowBigIntHelper y 1I
Regarding the PowBitShift function - I'm not sure why it is slower, but it definitely doesn't do what you need. Using bit shifting to implement power only works when the base is 2.
You don't need to create the Pow function.
The (**) operator has an overload for bigint -> int -> bigint.
Only the second parameter should be an integer, but I don't think that's a problem for your case.
Just try
bigint 10 ** 32 ;;
val it : System.Numerics.BigInteger =
100000000000000000000000000000000 {IsEven = true;
IsOne = false;
IsPowerOfTwo = false;
IsZero = false;
Sign = 1;}
Another option is to inline your function so it works with all numeric types (that support the required operators: (*), (-), get_One, and get_Zero).
let rec inline PowBigInt (x:^a) (y:^a) : ^a =
let zero = LanguagePrimitives.GenericZero
let one = LanguagePrimitives.GenericOne
if y = zero then one
else x * PowBigInt x (y - one)
let x = PowBigInt 10 32 //int
let y = PowBigInt 10I 32I //bigint
let z = PowBigInt 10.0 32.0 //float
I'd probably recommend making it tail-recursive, as Tomas suggested.

Resources