Over the years I keep track of solving technology - and I maintain a blog post about applying them to a specific puzzle - the "crossing ladders".
To get to the point, I accidentally found out about z3, and tried putting it to use in the specific problem. I used the Python bindings, and wrote this:
$ cat laddersZ3.py
#!/usr/bin/env python
from z3 import *
a = Int('a')
b = Int('b')
c = Int('c')
d = Int('d')
e = Int('e')
f = Int('f')
solve(
a>0, a<200,
b>0, b<200,
c>0, c<200,
d>0, d<200,
e>0, e<200,
f>0, f<200,
(e+f)**2 + d**2 == 119**2,
(e+f)**2 + c**2 == 70**2,
e**2 + 30**2 == a**2,
f**2 + 30**2 == b**2,
a*d == 119*30,
b*c == 70*30,
a*f - 119*e + a*e == 0,
b*e - 70*f + b*f == 0,
d*e == c*f)
Unfortunately, z3 reports...
$ python laddersZ3.py
failed to solve
The problem does have at least this integer solution: a=34, b=50, c=42, d=105, e=16, f=40.
Am I doing something wrong, or is this kind of system of equations / range constraints beyond what z3 can solve?
Thanks in advance for any help.
UPDATE, 5 years later: Z3 now solves this out of the box.
You can solve this using Z3 if you encode the integers as reals, which will force Z3 to use the nonlinear real arithmetic solver. See this for more details on the nonlinear integer vs. real arithmetic solvers: How does Z3 handle non-linear integer arithmetic?
Here's your example encoded as reals with the solution (z3py link: http://rise4fun.com/Z3Py/1lxH ):
a,b,c,d,e,f = Reals('a b c d e f')
solve(
a>0, a<200,
b>0, b<200,
c>0, c<200,
d>0, d<200,
e>0, e<200,
f>0, f<200,
(e+f)**2 + d**2 == 119**2,
(e+f)**2 + c**2 == 70**2,
e**2 + 30**2 == a**2,
f**2 + 30**2 == b**2,
a*d == 119*30,
b*c == 70*30,
a*f - 119*e + a*e == 0,
b*e - 70*f + b*f == 0,
d*e == c*f) # yields [a = 34, b = 50, c = 42, d = 105, e = 16, f = 40]
While the result is integer as you noted, and as what Z3 finds, Z3 apparently needs to use the real arithmetic solver to handle it.
Alternatively, you can leave the variables declared as integers and do the following from the suggestion at the referenced post:
t = Then('purify-arith','nlsat')
s = t.solver()
solve_using(s, P)
where P is the conjunction of the constraints (z3py link: http://rise4fun.com/Z3Py/7nqN ).
Rather than asking Z3 for a solution in reals, you could ask the solver of the Microsoft Solver Foundation:
using Microsoft.SolverFoundation.Services;
static Term sqr(Term t)
{
return t * t;
}
static void Main(string[] args)
{
SolverContext context = SolverContext.GetContext();
Domain range = Domain.IntegerRange(1, 199); // integers ]0; 200[
Decision a = new Decision(range, "a");
Decision b = new Decision(range, "b");
Decision c = new Decision(range, "c");
Decision d = new Decision(range, "d");
Decision e = new Decision(range, "e");
Decision f = new Decision(range, "f");
Model model = context.CreateModel();
model.AddDecisions(a, b, c, d, e, f);
model.AddConstraints("limits",
sqr(e+f) + d*d == 119*119,
sqr(e+f) + c*c == 70*70,
e*e + 30*30 == a*a,
f*f + 30*30 == b*b,
a*d == 119*30,
b*c == 70*30,
a*f - 119*e + a*e == 0,
b*e - 70*f + b*f == 0,
d*e == c*f);
Solution solution = context.Solve();
Report report = solution.GetReport();
Console.WriteLine("a={0} b={1} c={2} d={3} e={4} f={5}", a, b, c, d, e, f);
Console.Write("{0}", report);
}
The solver comes up with the solution you mentioned within fractions of a second. The Express Edition used to be free, but I am not sure about the current state.
a: 34
b: 50
c: 42
d: 105
e: 16
f: 40
There is no algorithm that, in general, can answer whether a multivariate polynomial equation (or a system thereof, as in your case) has integer solution (this is the negative answer to Hilbert's tenth problem). Thus, all solving methods for integers are either restricted to certain classes (e.g. linear equations, polynomials in one variable...) or use incomplete tricks, such as:
Linearizing expressions
Encoding equations into finite-bitwidth
numbers (ok for searching for "small" solutions).
This is why Z3 needs to be told to use the real number solver.
Related
I have a finite set of pairs of type (int a, int b). The exact values of the pairs are explicitly present in the knowledge base. For example it could be represented by a function (int a, int b) -> (bool exists) which is fully defined on a finite domain.
I would like to write a function f with signature (int b) -> (int count), representing the number of pairs containing the specified b value as its second member. I would like to do this in z3 python, though it would also be useful to know how to do this in the z3 language
For example, my pairs could be:
(0, 0)
(0, 1)
(1, 1)
(1, 2)
(2, 1)
then f(0) = 1, f(1) = 3, f(2) = 1
This is a bit of an odd thing to do in z3: If the exact values of the pairs are in your knowledge base, then why do you need an SMT solver? You can just search and count using your regular programming techniques, whichever language you are in.
But perhaps you have some other constraints that come into play, and want a generic answer. Here's how one would code this problem in z3py:
from z3 import *
pairs = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 1)]
def count(snd):
return sum([If(snd == p[1], 1, 0) for p in pairs])
s = Solver()
searchFor = Int('searchFor')
result = Int('result')
s.add(Or(*[searchFor == d[0] for d in pairs]))
s.add(result == count(searchFor))
while s.check() == sat:
m = s.model()
print("f(" + str(m[searchFor]) + ") = " + str(m[result]))
s.add(searchFor != m[searchFor])
When run, this prints:
f(0) = 1
f(1) = 3
f(2) = 1
as you predicted.
Again; if your pairs are exactly known (i.e., they are concrete numbers), don't use z3 for this problem: Simply write a program to count as needed. If the database values, however, are not necessarily concrete but have other constraints, then above would be the way to go.
To find out how this is coded in SMTLib (the native language z3 speaks), you can insert print(s.sexpr()) in the program before the while loop starts. That's one way. Of course, if you were writing this by hand, you might want to code it differently in SMTLib; but I'd strongly recommend sticking to higher-level languages instead of SMTLib as it tends to be hard to read/write for anyone except machines.
F(x1) > a;
F(x2) < b;
∀t, F'(x) >= 0 (derivative) ;
F(x) = ∑ ci*x^i; (i∈[0,n] ; c is a constant)
Your question is quite ambiguous, and stack-overflow works the best if you show what you tried and what problems you ran into.
Nevertheless, here's how one can code your problem for a specific function F = 2x^3 + 3x + 4, using the Python interface to z3:
from z3 import *
# Represent F as a function. Here we have 2x^3 + 3x + 4
def F(x):
return 2*x*x*x + 3*x + 4
# Similarly, derivative of F: 6x^2 + 3
def dF(x):
return 6*x*x + 3
x1, x2, a, b = Ints('x1 x2 a b')
s = Solver()
s.add(F(x1) > a)
s.add(F(x2) < b)
t = Int('t')
s.add(ForAll([t], dF(t) >= 0))
r = s.check()
if r == sat:
print s.model()
else:
print ("Solver said: %s" % r)
Note that I translated your ∀t, F'(x) >= 0 condition as ∀t. F'(t) >= 0. I assume you had a typo there in the bound variable.
When I run this, I get:
[x1 = 0, x2 = 0, b = 5, a = 3]
This method can be generalized to arbitrary polynomials with constant coefficients in the obvious way, but that's mostly about programming and not z3. (Note that doing so in SMTLib is much harder. This is where the facilities of host languages like Python and others come into play.)
Note that this problem is essentially non-linear. (Variables are being multiplied with variables.) So, SMT solvers may not be the best choice here, as they don't deal all that well with non-linear operations. But you can deal with those problems as they arise later on. Hope this gets you started!
Let's say I have a z3py program like this one:
import z3
a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")
some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))
s = z3.Solver()
s.add(output == some_formula)
s.check()
m = s.model()
print(m)
Is there an elegant way for me to retrieve the branching conditions from some_formula?
So get a list like [a < input_0, a > 1]. It should work for arbitrarily deep nesting of if expressions.
I know there is some way to use cubes, but I am not able to retrieve more than two cube expressions. I am not sure how to configure the solver.
My ultimate goal is to force the solver to give me different outputs based on the constraints I push and pop. The constraints are the set of conditions I have inferred from this formula.
You can print the cubes using:
for cube in s.cube():
print cube
But this isn't going to really help you. For your example, it prints:
[If(a + -1*input_0 >= 0, If(a <= 1, 2, 4), 1) == 1]
[Not(If(a + -1*input_0 >= 0, If(a <= 1, 2, 4), 1) == 1)]
which isn't quite what you were looking for.
The easiest way to go about your problem would be to directly walk down the AST of the formula yourself, and grab the conditions as you walk along the expressions. Of course, Z3 AST is quite a hairy object (pun intended!), so this will require quite a bit of programming. But reading through the constructors (If, Var etc.) in this file can get you started: https://z3prover.github.io/api/html/z3py_8py_source.html
Alright,thanks #alias! I came up with a custom version, which gets the job done. If someone knows a more elegant way to do this, please let me know.
import z3
a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")
some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))
nested_formula = z3.If(some_formula == 1, 20, 10)
s = z3.Solver()
s.add(output == some_formula)
s.check()
m = s.model()
print(m)
def get_branch_conditions(z3_formula):
conditions = []
if z3.is_app_of(z3_formula, z3.Z3_OP_ITE):
# the first child is usually the condition
cond = z3_formula.children()[0]
conditions.append(cond)
for child in z3_formula.children():
conditions.extend(get_branch_conditions(child))
return conditions
conds = get_branch_conditions(some_formula)
print(conds)
conds = get_branch_conditions(nested_formula)
print(conds)
I have been experimenting with z3 (version '4.8.7' obtained through pip3) and found this (apparent) discrepancy.
t, s0, s, u, a, v = Reals('t s0 s u a v')
equations = [v == u + a*t, s == s0 + u*t + a*t**2/2,
v**2 - u**2 == 2*a*s]
problem = [t == 10, s0 == 0, u == 0, a == 9.81]
solve(equations+problem)
This gives the correct output for s:
[a = 981/100, u = 0, s0 = 0, t = 10, s = 981/2, v = 981/10]
But when I use the Solver, the result is different:
solver = Solver()
solver.check(equations+problem)
solver.model()
This gives a wrong output for s, though it gets v right.
[t = 10, u = 0, s0 = 0, s = 0, a = 981/100, v = 981/10]
s should be (1/2) * (981/100) * 100 which is the result in solve.
Am I missing something obvious in z3's Solver or is this a bug? Thank you.
The issue here is that the argument to solver.check are extra assumptions the solver can make as it solves the constraints, not the actual constraints to check. See the documentation here: https://z3prover.github.io/api/html/z3py_8py_source.html#l06628
The correct call would be:
solver = Solver()
solver.add(equations+problem)
print solver.check()
print solver.model()
that is, you add the constraints, and then call check with no arguments. This would match what solve does. The argument to check are used if you want to check validity under some extra assumptions only.
I am trying to learn how Z3 uninterpreted functions work to show that n=2k+1 => log(m) + k*log(m*m) == n*log(m). To do so I use something like following
mylog = Function('mylog', IntSort(), IntSort())
mylog_rule1 = mylog(x*y) == mylog(x) + mylog(y)
mylog_rule2 = mylog(x**y) == y*mylog(x)
#mylog_rule3 = y*mylog(x) == mylog(x**y) #is this rule needed ?
rules = And(mylog_rule1, mylog_rule2, mylog_rule3)
prop = Implies(n==2*k+1, log(m) + k*log(m*m) == n*log(m))
prove(rules, prop)
There must be something wrong in my approach because this doesn't quite work. In fact I can't even do prove(Implies(mylog(x*y) == mylog(x) + mylog(y), mylog(m*n) == mylog(m) + mylog(n)) which just change the variable names.
Z3 will not be able to solve this kind of problem effectively.
Z3 has a solver for nonlinear arithmetic (nlsat). However, this solver does not support quantifiers and uninterpreted functions. Z3 will support that in the future.
So, when a problem contains uninterpreted functions such as mylog, Z3 will use a different (and incomplete) solver for nonlinear arithmetic. This solver will fail on simple nonlinear problems.
Another issue with your example is that you did not use the universal quantifier in your rules.
The simple example prove(Implies(mylog(x*y) == mylog(x) + mylog(y), mylog(m*n) == mylog(m) + mylog(n)) can be proved even when the incomplete solver for nonlinear arithmetic is used.
Here is the correct Z3Py script (also available online here)
mylog = Function('mylog', RealSort(), RealSort())
x, y = Reals('x y')
m, n = Reals('m n')
prove(Implies(ForAll([x,y], mylog(x*y) == mylog(x) + mylog(y)),
mylog(m*n) == mylog(m) + mylog(n)))