User guide¶
Expressions, operators, and helpers¶
Every expression is an Ast bound to its Context. You can build terms either
with the ported Python Z3 helpers and operators or with the 1-to-1 Context.mk_*
methods; both produce the same Ast values:
from apn_mojo import Rational
from z3_mojo import Context, Eq, Real, Solver, sat
var ctx = Context()
var s = Solver.from_tactic(ctx, "qfnra-nlsat")
var x = Real("x", ctx)
var y = Real("y", ctx)
s.add(Eq(x * x + y * y, 1), x > Rational(1, 2), y > 0)
if s.check() == sat:
var m = s.model()
var xv = m.get_rational(x) # Optional[Rational]; None if irrational algebraic
Ast supports +, -, *, /, //, %, **, &, |, ^, ~, <<,
>>, <, <=, >, >=, and arr[i], coercing Int, apn_mojo.Integer,
apn_mojo.Rational, Bool, and String literals to the AST's sort. Because
== on Ast is Mojo Equatable structural equality (Bool), use Eq(a, b)
or a.eq(b) (and Ne(a, b) / a.ne(b)) for Z3 equality formulas, and place
the Ast on the left side of <, <=, >, >= (write x > 0 rather than
0 < x).
Nonlinear real arithmetic (QF_NRA and qfnra-nlsat)¶
For quantifier-free polynomial constraints over the reals, Z3's qfnra-nlsat
tactic is usually much faster than the default solver:
from apn_mojo import Integer, Rational
from z3_mojo import Context, Eq, Real, Solver, sat
var ctx = Context()
var s = Solver.from_tactic(ctx, "qfnra-nlsat")
s.set_timeout_ms(1000)
s.set_seed(0)
var x = Real("x", ctx)
var y = Real("y", ctx)
s.add(Eq(x * x + y * y, 1), x > Rational(Integer(1), Integer(2)))
if s.check() == sat:
var m = s.model()
var xv = m.get_rational(x) # Optional[Rational]; None if irrational algebraic
Timeouts and resource limits
Z3 enforces set_timeout_ms(ms) to millisecond precision. For
machine-independent bounds, use set_rlimit(limit).
Quantified formulas, patterns, and prove / solve¶
For quantified formulas (ForAll / Exists, optionally with patterns /
MultiPattern, no_patterns, weight, and qid), use the default
Solver(ctx):
from z3_mojo import Context, ForAll, Implies, Real, Solver, unsat
var ctx = Context()
var s = Solver(ctx)
s.set_timeout_ms(2000)
var x = Real("x", ctx)
var y = Real("y", ctx)
var body = Implies(x > 0, 1 + x + x * x <= y * x)
s.add(ForAll(x, body))
assert_equal(s.check(), unsat)
For quick validity or satisfiability checks, prove(formula) checks whether
Not(formula) is unsatisfiable and solve(*constraints) returns
Optional[Model].
Unsat cores, incremental solving, and solution enumeration¶
When you need an unsat core, create the solver with Solver.for_logic rather
than Solver.from_tactic (tactic-wrapped solvers return an empty core for
tracked assertions):
var s = Solver.for_logic(ctx, "QF_NRA")
s.set_unsat_core(True)
var x = Real("x", ctx)
var p1 = BoolVar("p1", ctx)
var p2 = BoolVar("p2", ctx)
s.assert_and_track(x > 2, p1)
s.assert_and_track(x * x < 4, p2)
if s.check() == unsat:
var core = s.unsat_core() # List[Ast] of the tracked Bool constants
For incremental solving, use s.push(), s.pop(n=1), and s.reset(). To
enumerate distinct satisfying values for a term or tuple of terms, use
s.solutions(x) or s.solutions([x, y]).
Tactics, probes, and goals¶
Chain tactics with Then, OrElse, TryFor, With, When, Cond,
Repeat, ParOr, and ParThen, or compose Probe predicates with <, <=,
>, >=, &, |, and ~:
var p = Params(ctx)
p.set_uint("max_conflicts", 5)
p.set_bool("factor", True)
var tac = Then(Tactic("simplify", ctx), With(Tactic("qfnra-nlsat", ctx), p))
var solver = tac.solver()
Or apply a tactic directly to a Goal:
var g = Goal(ctx)
g.add(Eq(IntVal(2, ctx) + 3, 5))
var ar = Tactic("simplify", ctx).apply(g)
var subgoal0 = ar.subgoal(0)
Optimization (Optimize)¶
var opt = Optimize(ctx)
var x = IntVar("x", ctx)
var y = IntVar("y", ctx)
opt.add(x >= 0, y >= 0, x + y <= 10)
var obj = opt.maximize(3 * x + y)
if opt.check() == sat:
print("max =", opt.upper(obj))
Use opt.add_soft(formula, weight, id) for weighted MaxSMT and
opt.set_on_model(handler) to observe each improving model (see
Callbacks).
Real closed fields (RcfNum)¶
Z3 includes a real-closed-field arithmetic engine (z3_rcf.h) for exact
rationals, real algebraic roots, pi, e, and infinitesimals:
var pi = ctx.mk_rcf_pi()
var e = ctx.mk_rcf_e()
assert_true(e < pi)
var coeffs: List[RcfNum] = [ctx.mk_rcf_int(-2), ctx.mk_rcf_int(0), ctx.mk_rcf_int(1)]
var roots = RcfNum.mk_roots(ctx, coeffs) # [-sqrt(2), +sqrt(2)]
assert_true((roots[1] * roots[1]).eq(ctx.mk_rcf_int(2)))
Theories supported out of the box¶
Both Pythonic free functions and 1-to-1 Context.mk_* methods are available for
all Z3 5.3.3 theories:
- IEEE-754 floating point:
Float16Sort..Float128Sort(FloatHalf,FloatSingle,FloatDouble,FloatQuadruple),FPSort,RNE..RTZ,FP,FPVal,fpAdd..fpFMA,fpEQ..fpGEQ,fpIsNaN..fpIsNegative, and conversions (fpToReal,fpToFP,fpToSBV,fpToUBV,fpToIEEEBV). - Bitvectors:
BitVec,BitVecVal,ULT..UGE,UDiv,URem,SRem,LShR,Concat,Extract,ZeroExt,SignExt,RotateLeft,RotateRight,BV2Int,Int2BV, and overflow/underflow checks. - Strings, sequences, characters, and regex:
StringVar,StringVal,Length,Contains,PrefixOf,SuffixOf,IndexOf,LastIndexOf,SubString,Replace,StrToInt,IntToStr,StrToCode,StrFromCode,SeqMap,SeqFoldLeft,CharSort,CharVal,Re,InRe,Union,Intersect,Star,Plus,Option,Complement,Range,Loop,Diff. - Arrays and sets:
Array,Select,Store,Update,K,Default,Lambda,AsArray,Map,Ext,EmptySet,FullSet,SetAdd,SetDel,SetUnion,SetIntersect,SetDifference,SetComplement,IsMember,IsSubset. - Algebraic & polymorphic datatypes and recursive functions:
Datatype,DatatypeField(.of,.self_ref,.mutual_ref),CreateDatatypes,DeclareTypeVar,DatatypeSort,CreatePolymorphicDatatype,EnumSort,TupleSort,RecFunction,RecAddDefinition. - Z3 5.x theories: Finite Fields (
FiniteFieldSort,FiniteFieldElem,FiniteFieldVal,FiniteFieldBitsum), Finite Sets with cardinality (FiniteSetSort,FiniteSetSingleton/Singleton,FiniteSetSize,FiniteSetRange,FiniteSetMap,FiniteSetFilter), Finite Domains (FiniteDomainSort,FiniteDomainVal), Complex numbers (ComplexSort,Complex,ComplexVal,RealPart,ImagPart), and Order / Graph relations (LinearOrder,PartialOrder,TreeOrder,PiecewiseLinearOrder,TransitiveClosure). - Polynomials, algebraic numbers, and Fixedpoint / Horn / Spacer:
ctx.polynomial_subresultants,ctx.algebraic_*,Fixedpoint(ctx),fp.register_relation,fp.add_rule,fp.query.
Next steps¶
- Need custom theory propagation, clause logging, or optimizer progress hooks? Read User propagators and callbacks.
- Need direct 1-to-1
Z3_*C functions orZ3_mk_context_rcmanual refcounting? Read Low-level C API (z3_mojo.c). - Coming from Python
z3-solver? See Python to Mojo migration.