Suppose we have 3 variables and we need to ASSERT that they can either all be equal to -1 or neither can be equal to -1. I wrote the following code:
x := 1;
y := 1;
z := 1;
ASSERT( (x = -1) = (y = -1) = (z = -1) );
I often write this kind of check, but for two variables. Surprisingly the triple comparison compiled too, but it doesn't work as expected. For (1, 1, 1) values I expect it to evaluate to true. After substitution of variable values and simplification we get:
ASSERT( False = False = False );
and I thought that it should evaluate to True, but it doesn't. So how is this triple comparison evaluated?
First of all, the = operator is a binary operator: it always works on a pair of values. So there's no such thing as a "triple equality". The compiler will evaluate one pair, and use the result to evaluate the other.
When the compiler sees multiple linked operators, it needs to group them into pairs using what's called the "precedence of operators". It's clear if you think about the basic arithmetic operators we learned in primary school. There's no doubt what: 3+2*4 evaluates to: it's equivalent to 3+(2*4). When in doubt, always add the grouping yourself. If you do that, you see your expression is equivalent to:
((False = False) = False), and it's obvious it evaluates to:
(True = False).
What you probably want is to use the AND operator and group your initial Assert like this:
ASSERT(((x = -1) = (y = -1)) and ((y = -1) = (z = -1)))
Then I'd probably either write that expression on multiple lines to make the AND operator obvious (SQL habit, I know), or rewrite it completely:
Assert (
((x = -1) = (y = -1))
and
((x = -1) = (z = -1))
);
or this variant:
Assert (
((x = -1) and (y = -1) and (z = -1))
or
((x <> -1) and (y <> -1) and (z <> -1))
);
My rule is: if it takes more then 1 second to figure out the precedence of operators, add parentheses.
Comparison is associative: False=False=False is equivalent to (False=False)=False. The first False=False evaluates to True, leading to comparison True=False which in turn is False.
Related
I want to check the value of a, b, c, and if value 'a' equals to 1, 'x' is added one. We continue the process for values 'b' and 'c'.
So if a=1, b=1, c=1, the result of x should be 3.
if a=1, b=1, c=0, so the result of x should be 2.
Any methods to be implemented in z3?
The source code looks like this:
from z3 import *
a, b, c = Ints('a b c')
x, y = Ints('x y')
s = Solver()
s.add(If(a==1, x=x + 1, y = y-1))
s.add(If(b==1, x=x + 1, y = y-1))
s.add(If(c==1, x=x + 1, y = y-1))
s.check()
print s.model()
Any suggestions about what I can do?
This sort of "iterative" processing is usually modeled by unrolling the assignments and creating what's known as SSA form. (Static single assignment.) In this format, every variable is assigned precisely once, but can be used many times. This is usually done by some underlying tool as it is rather tedious, but you can do it by hand as well. Applied to your problem, it'd look something like:
from z3 import *
s = Solver()
a, b, c = Ints('a b c')
x0, x1, x2, x3 = Ints('x0 x1 x2 x3')
s.add(x0 == 0)
s.add(x1 == If(a == 1, x0+1, x0))
s.add(x2 == If(b == 1, x1+1, x1))
s.add(x3 == If(c == 1, x2+1, x2))
# Following asserts are not part of your problem, but
# they make the output interesting
s.add(b == 1)
s.add(c == 0)
# Find the model
if s.check() == sat:
m = s.model()
print("a=%d, b=%d, c=%d, x=%d" % (m[a].as_long(), m[b].as_long(), m[c].as_long(), m[x3].as_long()))
else:
print "no solution"
SSA transformation is applied to the variable x, creating as many instances as necessary to model the assignments. When run, this program produces:
a=0, b=1, c=0, x=1
Hope that helps!
Note that z3 has many functions. One you could use here is Sum() for the sum of a list. Inside the list you can put simple variables, but also expression. Here an example for both a simple and a more complex sum:
from z3 import *
a, b, c = Ints('a b c')
x, y = Ints('x y')
s = Solver()
s.add(a==1, b==0, c==1)
s.add(x==Sum([a,b,c]))
s.add(y==Sum([If(a==1,-1,0),If(b==1,-1,0),If(c==1,-1,0)]))
if s.check() == sat:
print ("solution:", s.model())
else:
print ("no solution possible")
Result:
solution: [y = 2, x = 2, c = 1, b = 0, a = 1]
If your problem is more complex, using BitVecs instead of Ints can make it run a little faster.
edit: Instead of Sum() you could also simply use addition as in
s.add(x==a+b+c)
s.add(y==If(a==1,-1,0)+If(b==1,-1,0)+If(c==1,-1,0))
Sum() makes sense towards readability when you have a longer list of variables, or when the variables already are in a list.
I want to find a maximal interval in which an expression e is true for all x. A way to write such a formula should be: Exists d : ForAll x in (-d,d) . e and ForAll x not in (-d,d) . !e.
To get such a d, the formula f in Z3 (looking at the one above) could be the following:
from z3 import *
x = Real('x')
delta = Real('d')
s = Solver()
e = And(1/10000*x**2 > 0, 1/5000*x**3 + -1/5000*x**2 < 0)
f = ForAll(x,
And(Implies(And(delta > 0,
-delta < x, x < delta,
x != 0),
e),
Implies(And(delta > 0,
Or(x > delta, x < -delta),
x != 0),
Not(e))
)
)
s.add(Not(f))
s.check()
print s.model()
It prints: [d = 2]. This is surely not true (take x = 1). What's wrong?
Also: by specifying delta = RealVal('1'), a counterexample is x = 0, even when x = 0 should be avoided.
Your constants are getting coerced to integers. Instead of writing:
1/5000
You should write:
1.0/5000.0
You can see the generated expression by:
print s.sexpr()
which would have alerted you to the issue.
NB. Being explicit about types is always important when writing constants. See this answer for a variation on this theme that can lead to further problems: https://stackoverflow.com/a/46860633/936310
I used the Z3_ast fs = Z3_parse_smtlib2_file(ctx,arg[1],0,0,0,0,0,0) to read file.
Additionally to add into the solver utilized the expr F = to_expr(ctx,fs) and then s.add(F).
My question is how can I get the number of total constraints in each instance?
I also tried the F.num_args(), however, it is giving wrong size in some instances.
Are there any ways to compute the total constraints?
Using Goal.size() may do what you want, after you add F to some goal. Here's a link to the Python API description, I'm sure you can find the equivalent in the C/C++ API: http://research.microsoft.com/en-us/um/redmond/projects/z3/z3.html#Goal-size
An expr F represents an abstract syntax tree, so F.num_args() returns the number of (one-step) children that F has, which is probably why what you've been trying doesn't always work. For example, suppose F = a + b, then F.num_args() = 2. But also, if F = a + b*c, then F.num_args() = 2 as well, where the children would be a and b*c (assuming usual order of operations). Thus, to compute the number of constraints (in case your definition is different than what Goal.size() yields), you can use a recursive method that traverses the tree.
I've included an example below highlighting all of these (z3py link here: http://rise4fun.com/Z3Py/It5E ).
For instance, my definition of constraint (or rather the complexity of an expression in some sense) might be the number of leaves or the depth of the expression. You can get as detailed as you want with this, e.g., counting different types of operands to fit whatever your definition of constraint might be, since it's not totally clear from your question. For instance, you might define a constraint as the number of equalities and/or inequalities appearing in an expression. This would probably need to be modified to work for formulas with quantifiers, arrays, or uninterpreted functions. Also note that Z3 may simplify things automatically (e.g., 1 - 1 gets simplified to 0 in the example below).
a, b, c = Reals('a b c')
F = a + b
print F.num_args() # 2
F = a + b * c
print F.num_args() # 2
print F.children() # [a,b*c]
g = Goal()
g.add(F == 0)
print g.size() # number of constraints = 1
g.add(Or(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 2
print g
g.add(And(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 6
print g
def count_constraints(c,d,f):
print 'depth: ' + str(d) + ' expr: ' + str(f)
if f.num_args() == 0:
return c + 1
else:
d += 1
for a in f.children():
c += count_constraints(0, d, a)
return c
exp = a + b * c + a + c * c
print count_constraints(0,0,exp)
exp = And(a == b, b == c, a == 0, c == 0, b == 1 - 1)
print count_constraints(0,0,exp)
q, r, s = Bools('q r s')
exp = And(q, r, s)
print count_constraints(0,0,exp)
I have two variables 'a' and 'b' of different size, see below. I have few questions:
(1) How can I copy value of 'a' to 'b'? (i.e extend operation)
(2) How can I copy value of 'b' to 'a'? (i.e trunc operation)
Thanks.
a = BitVec('a', 1)
b = BitVec('b', 32)
For extending, we use ZeroExt or SignExt. The ZeroExt will add "zeros", and SignExt will "copy" the sign bit (i.e., the most significant bit). For truncation we use Extract, it can extract any subsequence of bits. Here is a small example (also available online at rise4fun).
a = BitVec('a', 1)
b = BitVec('b', 32)
solve(ZeroExt(31, a) == b)
solve(b > 10, Extract(0,0,b) == a)
EDIT: we can use p == (x == 1) to 'assign' a Boolean variable p with the value of a Bit-vector x of size 1, and vice-versa. The formula p == (x == 1) is just stating that p is true if and only if x is 1. Here is an example (also available online here)
x = BitVec('x', 1)
p = Bool('p')
solve(p == (x == 1), x == 0)
solve(p == (x == 1), x == 1)
solve(p == (x == 1), Not(p))
solve(p == (x == 1), p)
Solver.model() sometimes returns an assignment with a seemingly-needless Var(), whereas I was (perhaps naively) expecting Solver.model() to always return a concrete value for each variable. For example:
#!/usr/bin/python
import z3
x, y = z3.Ints('x y')
a = z3.Array('a', z3.IntSort(), z3.IntSort())
e = z3.Not(z3.Exists([x], z3.And(x != y, a[x] == a[y])))
solver = z3.Solver()
solver.add(e)
print solver.check()
print solver.model()
produces
sat
[k!1 = 0,
a = [else -> k!5!7(k!6(Var(0)))],
y = 1,
k!5 = [else -> k!5!7(k!6(Var(0)))],
k!5!7 = [1 -> 3, else -> 2],
k!6 = [1 -> 1, else -> 0]]
What's going on here? Is Var(0) in a's "else" referring to the 0th argument to the a array, meaning a[i] = k!5!7[k!6[i]]? Is it possible to get a concrete satisfying assignment for a out of Z3, such as a = [1 -> 1, else -> 0]?
This is the intended output. The interpretation for functions and arrays should be viewed as function definitions. Keep in mind that the assertion
z3.Not(z3.Exists([x], z3.And(x != y, a[x] == a[y])))
is essentially a universal quantifier. For quantifier free problems, Z3 does generate the "concrete assignments" suggested in your post. However, this kind of representation is not expressive enough. In the end of the message, I attached an example that cannot be encoded using "concrete assignments".
The following post has additional information about how models are encoded in Z3.
understanding the z3 model
You can find more details regarding the encoding used by Z3 at http://rise4fun.com/Z3/tutorial/guide
Here is an example that produces a model that can't be encoded using "concrete" assignments (available online at http://rise4fun.com/Z3Py/eggh):
a = Array('a', IntSort(), IntSort())
i, j = Ints('i j')
solver = Solver()
x, y = Ints('x y')
solver.add(ForAll([x, y], Implies(x <= y, a[x] <= a[y])))
solver.add(a[i] != a[j])
print solver.check()
print solver.model()