A model is a satisfying assignment for a set of formulas. When Z3 determines a formula is satisfiable, it can produce a model that shows concrete values making the formula true.
from z3 import *x = Int('x')y = Int('y')s = Solver()s.add(x >= 1)s.add(y < x + 3)if s.check() == sat: m = s.model() # Iterate over all declarations in model for decl in m.decls(): print(f"{decl.name()} = {m[decl]}")
from z3 import *x = Int('x')y = Int('y')s = Solver()s.add(x >= 1)s.add(y < x + 3)if s.check() == sat: m = s.model() # Model has size (number of interpretations) print(f"Model size: {len(m)}") for i in range(len(m)): decl = m[i] # Get i-th declaration # For constants (0-arity functions) if decl.arity() == 0: print(f"{decl.name()} = {m[decl]}") else: # For functions, see function interpretations below print(f"{decl.name()} is a function")
Models may not assign values to all variables in your problem—only those relevant to satisfying the constraints.
from z3 import *x = Int('x')y = Int('y')z = Int('z') # Unconstraineds = Solver()s.add(x > y)if s.check() == sat: m = s.model() print(f"x = {m[x]}") # Has value print(f"y = {m[y]}") # Has value print(f"z = {m[z]}") # May be None or default value # Use eval with model_completion for unconstrained vars print(m.eval(z, model_completion=True)) # Returns arbitrary value
When using tactics, you may need to convert models between goals:From examples/c++/example.cpp:680:
from z3 import *x, y, z = Ints('x y z')# Create and transform goalg = Goal()g.add(x > 10)g.add(y == x + 3)g.add(z > y)t = Then('simplify', 'solve-eqs')result = t(g)# Solve transformed subgoals = Solver()subgoal = result[0]for f in subgoal: s.add(f)if s.check() == sat: # Model for transformed problem m_sub = s.model() print("Subgoal model:", m_sub) # Convert back to original variables m_orig = subgoal.convert_model(m_sub) print("Original model:", m_orig)
Verify a model satisfies the original constraints:
from z3 import *def validate_model(solver, model): """Check if model satisfies all assertions""" for assertion in solver.assertions(): if not is_true(model.eval(assertion)): print(f"Failed: {assertion}") return False return Truex, y = Ints('x y')s = Solver()s.add(x > 0)s.add(y > x)s.add(x + y < 10)if s.check() == sat: m = s.model() if validate_model(s, m): print("Model is valid!")