Tutorials

Part 4: Quantifiers, reachability, and exact real closed fields

This part covers Z3's higher-level reasoning tools: quantified axioms with instantiation triggers, recursive functions, model-based quantifier elimination, Fixedpoint Horn/reachability queries, and exact real-closed-field numbers (RcfNum).

Full runnable file: docs/examples/tutorial_04_quantifiers_rcf.mojo.

1. Quantifiers with patterns (MultiPattern) and weights

When asserting quantified axioms (ForAll / Exists), you can guide Z3's E-matching engine with explicit trigger patterns (MultiPattern), priority weights, and quantifier IDs (qid):

from z3_mojo import (
    Context, ForAll, Function, IntSort, IntVal, IntVar, MultiPattern, Solver, unsat
)

var ctx = Context()
var f = Function("f", IntSort(ctx), IntSort(ctx))
var x = IntVar("x", ctx)

var ax = ForAll(
    [x],
    f(x) >= x,
    patterns=[MultiPattern([f(x)])],
    weight=1,
    qid="f_ge_id",
)

var s = Solver(ctx)
s.add(ax, f(IntVal(10, ctx)) < 5)
assert_equal(s.check(), unsat)

Because f(10) matches the pattern f(x), Z3 instantiates f(10) >= 10 immediately and refutes f(10) < 5. Note that Z3 forbids passing both non-empty patterns and non-empty no_patterns on the same quantifier.

2. Recursive functions and prove

Declare recursive functions with RecFunction and attach their defining equation with RecAddDefinition. To prove a closed formula (checking that its negation is unsat), use prove(...):

from z3_mojo import Eq, If, RecAddDefinition, RecFunction, prove

var tri = RecFunction("tri", IntSort(ctx), IntSort(ctx))
var n = IntVar("n", ctx)
RecAddDefinition(tri, n, If(n <= 0, 0, n + tri(n - 1)))

assert_equal(prove(Eq(tri(IntVal(4, ctx)), 10)), unsat)

prove(formula) returns a CheckResult: unsat means the negation has no counterexample, so formula is valid.

3. Model-based projection (Model.project)

Given a satisfying model m, m.project(vars, formula) eliminates vars from formula into a quantifier-free implicant satisfied by m:

from z3_mojo import And, sat

var y = IntVar("y", ctx)
var sm = Solver(ctx)
sm.add(y > x, y < x + 4, Eq(x, 10))
assert_equal(sm.check(), sat)

var proj = sm.model().project([y], And(y > x, y < x + 4))
print("Model.project eliminating y:", proj)

4. Graph reachability with Fixedpoint

Z3's Fixedpoint engine (Horn clauses / Spacer) solves inductive reachability directly. Register predicates with register_relation, add Horn rules with add_rule, and run fp.query(...) (which returns Lbool.TRUE when derivable and Lbool.FALSE when not):

from z3_mojo import BoolSort, Fixedpoint, Implies, Lbool

var fp = Fixedpoint(ctx)
var edge = Function("edge", IntSort(ctx), IntSort(ctx), BoolSort(ctx))
var reach = Function("reach", IntSort(ctx), IntSort(ctx), BoolSort(ctx))
fp.register_relation(edge)
fp.register_relation(reach)

var u = IntVar("u", ctx)
var v = IntVar("v", ctx)
var w = IntVar("w", ctx)
fp.add_rule(edge(IntVal(0, ctx), IntVal(1, ctx)), "e01")
fp.add_rule(edge(IntVal(1, ctx), IntVal(2, ctx)), "e12")
fp.add_rule(edge(IntVal(2, ctx), IntVal(3, ctx)), "e23")
fp.add_rule(ForAll([u, v], Implies(edge(u, v), reach(u, v))), "base")
fp.add_rule(
    ForAll([u, v, w], Implies(And(reach(u, v), edge(v, w)), reach(u, w))),
    "step",
)

assert_equal(fp.query(reach(IntVal(0, ctx), IntVal(3, ctx))), Lbool.TRUE)
assert_equal(fp.query(reach(IntVal(3, ctx), IntVal(0, ctx))), Lbool.FALSE)

5. Exact real closed fields (RcfNum)

When you need exact algebraic roots, transcendental constants (pi, e), or infinitesimals without floating-point error, use RcfNum. Polynomials are given as coefficient lists [c0, c1, ..., cn] for c0 + c1*x + ... + cn*x^n:

from z3_mojo import RcfNum

# Isolate all real roots of x^2 - 2 = 0: [-sqrt(2), +sqrt(2)]
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)
assert_equal(len(roots), 2)
assert_true((roots[1] * roots[1]).eq(ctx.mk_rcf_int(2)))

var pi = ctx.mk_rcf_pi()
var e = ctx.mk_rcf_e()
var eps = ctx.mk_rcf_infinitesimal()
assert_true(e < pi)
assert_true(pi < pi + eps)
print("RcfNum sqrt(2) ~=", roots[1].to_decimal(10))

Running tutorial_04_quantifiers_rcf.mojo produces:

Quantifier with MultiPattern: unsat (axiom triggered)
RecFunction prove(tri(4) == 10): proved (negation is unsat)
Model.project eliminating y: true
Fixedpoint reach(0, 3): TRUE | reach(3, 0): FALSE
RcfNum sqrt(2) ~= 1.4142135623? | e < pi < pi + eps: verified

Try it yourself

  1. Define a recursive fact(n) function with RecFunction and prove fact(5) == 120.
  2. Add a cycle edge edge(3, 1) to the Fixedpoint graph and check that reach(3, 2) becomes Lbool.TRUE while reach(3, 0) stays Lbool.FALSE.
  3. Use RcfNum.mk_roots to isolate the golden ratio root of x^2 - x - 1 = 0 and verify phi * phi == phi + 1.

Next: Part 5: Extending Z3 — user propagators, callbacks, and the low-level C API.

z3_mojo v5.3.3.0 for Mojo 1.2 and Z3 5.3.3 · Apache License 2.0 with LLVM Exceptions · Source on GitHub