Z3 C-API for solver timeout - z3

I am using Z3 4.1 C-API on linux.
I want to specify a timeout for a solver.
I am using following commands, however I get a segmentation fault in the command Z3_solver_set_params().
Z3_context ctx = mk_context();
Z3_solver s = Z3_mk_solver(ctx);
Z3_params params = Z3_mk_params(ctx);
Z3_symbol r = Z3_mk_string_symbol(ctx, ":timeout");
Z3_params_set_uint(ctx, params, r, static_cast<unsigned>(10));
Z3_solver_set_params(ctx, s, params);
It seems that I am not using APIs correctly.
I couldn't find any example for C-APIs to set a solver timeout in test_capi.c file containing examples.
Can anyone help?

You need to increment reference counts on the solver and parameters before doing anything else.
Here is a snippet that will go through.
Z3_config cfg = Z3_mk_config();
Z3_context ctx = Z3_mk_context(cfg);
Z3_solver s = Z3_mk_solver(ctx);
Z3_solver_inc_ref(ctx, s);
{
Z3_params params = Z3_mk_params(ctx);
Z3_params_inc_ref(ctx, params);
{
Z3_symbol r = Z3_mk_string_symbol(ctx, ":timeout");
Z3_params_set_uint(ctx, params, r, 10);
Z3_solver_set_params(ctx, s, params);
Z3_params_dec_ref(ctx, params);
}
}
Z3_solver_dec_ref(ctx, s);
Z3_del_config(cfg);
Z3_del_context(ctx);

Related

Z3: Finding all satisfying model in java

Below solution i am not able to implement in java. Please help me. Below is snippet code which i am trying to implement.
I found the same question:
Z3: finding all satisfying models
(Z3Py) checking all solutions for equation
BitVecExpr a = ctx.mkBVConst("a",8);
BitVecExpr b = ctx.mkBVConst("b",8);
BitVecExpr c = ctx.mkBVConst("c",8);
Solver s = ctx.mkSolver();
//s.add(ctx.mkEq(c,ctx.mkBVXOR(a,b))); // I am able to get distinct value for a and b for XOR.
//s.add(ctx.mkEq(c,ctx.mkBVOR(b,a))); // If i swap the position of the a and b then i was able to generate distinct pattern. For example for this add method of OR my code was working.
s.add(ctx.mkEq(c,ctx.mkBVOR(a,b))); // Not working getting same model.
s.add(ctx.mkEq(c,ctx.mkBV(11,8)));
if (s.check() == Status.SATISFIABLE)
{
System.out.println("status :"+ s.check());
Model m = s.getModel();
System.out.println("Model :"+ m);
}
BitVecExpr test1[] = {a,b};
s.add(ctx.mkDistinct(test1)); // If i use this line then only i get distinct pattern
if (s.check() == Status.SATISFIABLE)
{
System.out.println("status :"+ s.check());
Model m = s.getModel();
System.out.println("Model :"+ m);
}
Also i don't have model()[] method in java.In java i have getModel() method without any arguments.
One more question. How can we implement '!=' inside add. For example.
s.add(Or(a != s.model()[a], b != s.model()[b]))
For == we have mkEq() method, But i was unable to find any method related to '!='.
I tried using:
s.add(ctx.mkOr(ctx.mkEq(a,ctx.mkNot(s.getModel())),ctx.mkEq(a,ctx.mkNot(s.getModel()))));
For which i am getting compilation error. Which i should get because its not possible to implement in that way.
BitVecExpr a = ctx.mkBVConst("a",2);
BitVecExpr b = ctx.mkBVConst("b",2);
BitVecExpr c = ctx.mkBVConst("c",2);
Model m = null;
Solver s = ctx.mkSolver();
s.add(ctx.mkEq(c,ctx.mkBVXOR(a,b)));
s.add(ctx.mkEq(c,ctx.mkBV(3,2)));
while(s.check() == Status.SATISFIABLE){
System.out.println("status :"+ s.check());
m = s.getModel();
System.out.println("m.eval(a) " + m.eval(a,false));
System.out.println("m.eval(b) " + m.eval(b,false));
System.out.println("m.eval(c) " + m.eval(c,false));
Integer b_int = Integer.parseInt(m.eval(b,false).toString());
Integer a_int = Integer.parseInt(m.eval(a,false).toString());
BoolExpr b_bol = ctx.mkEq(b,(BitVecExpr) ctx.mkBV(b_int,2));
BoolExpr a_bol = ctx.mkEq(a,(BitVecExpr) ctx.mkBV(a_int,2));
s.add(ctx.mkOr(ctx.mkEq(b_bol,ctx.mkFalse()),ctx.mkEq(a_bol,ctx.mkFalse())));
}
Above code worked for me. Do you guys have any suggestion.

Output function for fminunc in Octave

I am trying to implement the Regularized Logistic Regression Algorithm, using the fminunc() function in Octave for minimising the cost function. As generally advised, I would like to plot the cost function as a function of iterations of the fminunc() function. The function call looks as follows -
[theta, J, exit_flag] = ...
fminunc(#(t)(costFunctionReg(t, X, y, lambda)), initial_theta, options);
with
options = optimset('GradObj', 'on', 'MaxIter', 400, 'OutputFcn',#showJ_history);
[showJ-history is the intended output function; I hope I have set the options parameter correctly].
But, I can't find good sources on the internet highlighting how to write this output function, specifically, what parameters are passed to it by the fminunc(), what it returns (if anything in particular required by the fminunc()).
Could someone please mention some helpful links or assist me in writing the output function.
I think you can refer to the source code. Consider also this example:
1;
function f = __rosenb (x)
# http://en.wikipedia.org/wiki/Rosenbrock_function
n = length (x);
f = sumsq (1 - x(1:n-1)) + 100 * sumsq (x(2:n) - x(1:n-1).^2);
endfunction
function bstop = showJ_history(x, optv, state)
plot(optv.iter, optv.fval, 'x')
# setting bstop to true stops optimization
bstop = false;
endfunction
opt = optimset('OutputFcn', #showJ_history);
figure()
xlabel("iteration")
ylabel("cost function")
hold on
[x, fval, info, out] = fminunc (#__rosenb, [5, -5], opt);

Z3 JAVA-API for solver timeout

How to set solver's timeout for Z3 JAVA API?
Back to this question again:
Here is my code:
Context ctx = getZ3Context();
solver = ctx.MkSolver();
Params p = ctx.MkParams();
p.Add("timeout", 1);
solver.setParameters(p);
Not work, the solver just running the query forever. Any idea about this?
I haven't used the Java API, but from Looking at the official Java example and at this snippet, I'd assume that something along the following lines should work:
Solver s = ctx.MkSolver();
Params p = ctx.MkParams();
p.Add("timeout", valueInMilliseconds); /* "SOFT_TIMEOUT" or ":timeout"? */
s.setParameters(p);
Okay, finally found a solution myself:
Context ctx = getZ3Context();
solver = ctx.MkSolver();
Params p = ctx.MkParams();
/* Also tried
* p.Add("timeout", 1),
* p.Add(":timeout", 1),
* neither worked.
*/
p.Add("soft_timeout", 1);
solver.setParameters(p);

Z3 and DIMACS output

Z3 currently supports the DIMACS format for input. Is there any way to output the DIMACS format for the problem before solution? I mean converting the problem to a system CNFs and output it in a DIMACS format.
If not, any ideas towards this direction would be more than helpful.
The DIMACS format is very primitive, it supports only Boolean variables. Z3 does not reduce every problem into SAT. Some problems are solved using a propositional SAT solver, but this is not the rule. This usually only happens if the input contains only Boolean and/or Bit-vector variables. Moreover, even if the input problem contains only Boolean and Bit-vector variables, there is no guarantee that Z3 will use a pure SAT solver to solve it.
That being said, you can use the tactic framework to control Z3. For example, for Bit-vector problems, the following tactic will convert it into a propositional formula in CNF format. It should be straightforward to convert it into DIMACS. Here is the example. You can try it online at: http://rise4fun.com/Z3Py/E1s
x, y, z = BitVecs('x y z', 16)
g = Goal()
g.add(x == y, z > If(x < 0, x, -x))
print g
# t is a tactic that reduces a Bit-vector problem into propositional CNF
t = Then('simplify', 'bit-blast', 'tseitin-cnf')
subgoal = t(g)
assert len(subgoal) == 1
# Traverse each clause of the first subgoal
for c in subgoal[0]:
print c
Thanks to Leonardo's answer I came up with this code that will do what you want:
private static void Output(Context ctx,Solver slv)
{
var goal = ctx.MkGoal();
goal.Add(slv.Assertions);
var applyResult = ctx.Then(ctx.MkTactic("simplify"),
ctx.MkTactic("bit-blast"),
ctx.MkTactic("tseitin-cnf")).Apply(goal);
Debug.Assert(applyResult.Subgoals.Length==1);
var map = new Dictionary<BoolExpr,int>();
foreach (var f in applyResult.Subgoals[0].Formulas)
{
Debug.Assert(f.IsOr);
foreach (var e in f.Args)
if (e.IsNot)
{
Debug.Assert(e.Args.Length==1);
Debug.Assert(e.Args[0].IsConst);
map[(BoolExpr)e.Args[0]] = 0;
}
else
{
Debug.Assert(e.IsConst);
map[(BoolExpr)e] = 0;
}
}
var id = 1;
foreach (var key in map.Keys.ToArray())
map[key] = id++;
using (var fos = File.CreateText("problem.cnf"))
{
fos.WriteLine("c DIMACS file format");
fos.WriteLine($"p cnf {map.Count} {applyResult.Subgoals[0].Formulas.Length}");
foreach(var f in applyResult.Subgoals[0].Formulas)
{
foreach (var e in f.Args)
if (e.IsNot)
fos.Write($"{map[(BoolExpr)e.Args[0]]} ");
else
fos.Write($"-{map[(BoolExpr)e]} ");
fos.WriteLine("0");
}
}
}
For it to work you should add all your constraints to the solver directly, by calling slv.Assert(...).

An error appears when running exist quantifier and fixedpoint Z3 in C#

I tried to use ctx.mkExist in the fixedpoint, howwever, it occurs error said "contains recursive predicate", I don't know why? and How to use ctx.MkExists in fixedpoint?For example:
exist (lamda real) that lamb>=0 AND inv(c,i) AND phi(c+lamb,i) => phi(c,i)
using (Context ctx = new Context())
{
var s = ctx.MkFixedpoint();
IntSort B = ctx.IntSort;
BoolSort T = ctx.BoolSort;
RealSort R = ctx.RealSort;
FuncDecl phi = ctx.MkFuncDecl("phi", new Sort[] { R,B }, T);
s.RegisterRelation(phi);
FuncDecl Inv = ctx.MkFuncDecl("inv", new Sort[] { R, B }, T);
s.RegisterRelation(Inv);
RealExpr c= (RealExpr)ctx.MkBound(0, R);
IntExpr i = (IntExpr) ctx.MkBound(1, B);
Expr[] InvArg=new Expr[2];
InvArg[0] = ctx.MkConst("inv0" , Inv.Domain[0]);
InvArg[1] = ctx.MkConst("inv1", Inv.Domain[1]);
Expr invExpr = ctx.MkImplies(ctx.MkOr(
ctx.MkAnd(ctx.MkEq(InvArg[1], ctx.MkInt(0)), ctx.MkGe((RealExpr)InvArg[0], ctx.MkReal(0))),
ctx.MkAnd(ctx.MkEq(InvArg[1], ctx.MkInt(1)), ctx.MkGe((RealExpr)InvArg[0], ctx.MkReal(2)))
),
(BoolExpr)Inv[InvArg]);
Quantifier invQ = ctx.MkForall(InvArg, invExpr, 1);
s.AddRule(invQ);
RealExpr[] lamb = new RealExpr[1];
lamb[0] = ctx.MkRealConst("lamb");
Expr existExpr = ctx.MkAnd(
(BoolExpr)Inv[c,i],
(BoolExpr)phi[ctx.MkAdd(c,lamb[0]),i],
ctx.MkGe(lamb[0], ctx.MkReal(0)));
BoolExpr t= ctx.MkExists(lamb, existExpr, 1);
s.AddRule(ctx.MkImplies(t,(BoolExpr)phi[c,i]));
}
sometimes, there is an error said "AccessViolationException was unhandlered,Attempted to read or write protected memory. This is often an indication that other memory is corrupt." when running to ctx.MkExists()
The fixedpoint solver only supports universal quantifiers at the top-level.
You should rewrite the rule as follows:
s.AddRule(ctx.MkForall(lamb,
ctx.MkImplies((BoolExpr)existExpr,(BoolExpr)phi[c,i])));
Z3 should ideally not result in any access violation. This is typically indicating a bug.
I would really appreciate repros for such bugs when/if you encounter them.

Resources