SMT: satisfiability modulo theories and the design of Z3
Study SMT, the DPLL(T) interface and theory explanations, congruence closure, difference logic, arithmetic, bit-blasting, theory combination and Z3.
After this lesson you can
- Explain DPLL(T) and distinguish eager and lazy approaches.
- Implement theory solvers for equality with uninterpreted functions and difference logic with explanations.
- Describe SMT general simplex and bit-blasting and reason about their costs.
- Combine theories using Nelson–Oppen and recognize the role of convexity.
- Model problems in Z3, choosing the appropriate SMT-LIB logic.
Before you start
- 10Conflict analysis and 1-UIP learningNon-chronological backjumpingTwo watched literalsAssignment trail and decision levelsGlobal constraints
- 01Tseitin transformationFirst-order syntaxTarskian semantics
- 08Disjoint-set union (union-find)Path compressionUnion by rank or sizeBellman-Ford algorithm
- 06Linear programming
Motivation: when Booleans are not enough
Last lesson you built a CDCL solver, able to decide formulas with millions of clauses. Questions of practical interest rarely arrive as clauses. They look like this:
- Can this allocation overflow? In C,
malloc(n * 4)allocates less than requested ifn * 4wraps at 32 bits. The question is whether annexists with and . This is machine-integer arithmetic. - Does this schedule fit? Tasks with durations, precedence constraints and one machine must finish by a deadline. This is linear arithmetic over start times with disjunctions (“A before B, or B before A”).
- Are these programs equivalent? A compiler eliminated a common subexpression. Translation validation need not know what multiplication does: it suffices that it is a function, so equal arguments yield equal results.
- Can this neural network produce the wrong output in an input region? This is real linear arithmetic with ReLU constraints, solved by Reluplex (Katz et al., 2017), studied alongside certified robustness.
All of this can be translated to SAT: 32-bit integers are 32 Booleans, and start times can use the lesson 11 order encoding. But translation has a measurable cost: a schedule’s order encoding grows with time horizon, and a 32-bit multiplication exceeds eight thousand clauses. Structure is lost too: to a shortest-path algorithm, is a negative-weight cycle found in polynomial time, while SAT on the CNF must rediscover the impossibility clause by clause.
Satisfiability modulo theories (SMT) divides the work. CDCL handles Boolean structure; each theory (equality, arithmetic, bit-vectors, arrays) supplies a specialized decision procedure for conjunctions of atoms: union-find, Bellman–Ford, simplex. Their interface is the central topic: how theory explains conflicts so CDCL can learn. By the end you will understand Z3’s design, have programmed DPLL(T) for difference logic and congruence closure with explanations, and know how to choose the right theory.
Theories, logics and SMT-LIB
An SMT formula is a quantifier-free first-order formula whose symbols have predetermined meaning. In , and are not freely interpreted as in general first-order semantics: they mean integer addition and order. , however, is free.
Common theories and the cost of deciding a conjunction of literals (the theory solver’s job; CDCL supplies disjunction):
| Theory | Typical atoms | Literal conjunctions | Procedure |
|---|---|---|---|
| Equality with uninterpreted functions (EUF) | , | congruence closure | |
| Difference logic (IDL, RDL) | polynomial, | Bellman–Ford | |
| Linear real arithmetic (LRA) | polynomial | simplex (exponential worst case, fast in practice) | |
| Linear integer arithmetic (LIA) | same over | NP-complete | simplex with branching and cuts |
| Bit-vectors (BV) | bvadd x y = z, bvult | NP-complete (counting each bit in size) | bit-blasting to SAT |
| Arrays (AX) | select(store(a, i, v), j) | NP-complete | read-over-write axioms |
The third-column bounds are classical: Downey, Sethi and Tarjan’s (1980) congruence closure is ; linear programming has been polynomial since Khachiyan’s ellipsoid method (1979), though solvers use simplex; integer linear arithmetic contains 0–1 integer programming, which is NP-hard.
Uninterpreted functions seem useless but are extremely useful. They satisfy only equality axioms (reflexive, symmetric, transitive) and congruence: . They abstract: to prove two programs equivalent when the proof does not depend on multiplication’s details, replace multiplication with arbitrary . Equivalence proved for every holds for multiplication, turning nonlinear integer arithmetic (undecidable) into nearly linear-time EUF.
SMT-LIB: a common format
SMT-LIB specifies a common solver language and logic catalog. Logic names are assembled from QF_ (quantifier-free), UF (uninterpreted functions), A or AX (arrays), BV (bit-vectors), IDL and RDL (integer and real differences), LIA, LRA, NIA (linear integer, linear real, nonlinear integer arithmetic). Thus QF_AUFLIA means quantifier-free arrays, uninterpreted functions and linear integer arithmetic, typical for array-program verification. Declaring logic tells the solver which procedures to load and which simplifications are sound. An SMT-LIB 2 problem looks like this (in lab 3, s.sexpr() prints this example’s declarations and assertions):
(set-logic QF_LIA)
(declare-fun p () Int)
(declare-fun q () Int)
(assert (>= (+ p (* 2 q)) 3))
(assert (<= (- p q) 1))
(assert (or (< p 0) (> q 5)))
(check-sat)
(get-model)
Arrays have a theory with two symbols, select (read) and store (write), and two read-over-write axioms: and , plus extensionality (arrays agreeing at every index are equal). The second axiom forces case distinctions on whether indices agree, explaining NP-completeness of conjunctions.
Eager or lazy
There are two ways to use SAT to decide an SMT formula.
The eager approach translates the entire formula into equisatisfiable CNF once and calls SAT once. For bit-vectors this is natural: bit-blasting below. For EUF, Ackermann reduction (1954) replaces each application with a fresh constant and, for each pair of applications of the same symbol, adds functional consistency constraint . The resulting equality logic is encoded in SAT. Difference logic has encodings adding transitivity constraints between differences (Strichman, Seshia and Bryant, 2002). The appeal is using SAT unchanged with all its preprocessing. Size is the problem: Ackermann is quadratic in each symbol’s application count, transitivity can be cubic, and order encoding grows with constants.
The lazy approach does not translate everything. It replaces each theory atom with a fresh Boolean variable, yielding the formula’s Boolean abstraction (or propositional skeleton). For example,
Each abstraction model says which atoms are true and false: a conjunction of theory literals, exactly what the theory solver can decide. If -consistent, the original formula has a model. Otherwise theory returns an inconsistent subset , its explanation, and SAT learns clause , which is -valid: no model makes all literals of true together.
The simplest offline lazy loop alternates until SAT runs out of models or theory accepts one. Explanation size determines efficiency. The figure uses a scheduling problem: three tasks on one machine, durations 2, 3 and 1, all within with A before C. Each task pair gives two atoms, “X before Y” () and its opposite; the abstraction requires at least one.
With the problem is unsatisfiable because durations total 6. Minimal explanations prove it in 8 rounds; returning the full assignment takes 27. With four tasks and the difference is 38 versus 729, not by chance: . Each of 6 pairs permits three combinations (one order, the other, or both), giving abstraction models, all inconsistent; a clause negating the full assignment excludes exactly one. By contrast a clause of literals over free atoms excludes the total assignments falsifying it. This is enumeration versus reasoning.
The counts do not depend on the widget: the next cell implements the same Python loop, same decision order (SAT returns the first lexicographic model, true before false), and same Bellman–Ford.
import itertools
def planificacion(tareas, H, prec=()):
"""Átomos x - y <= c (z es el origen de tiempos). Devuelve los átomos y los pares de órdenes alternativas."""
atomos, pares = [], []
dur = dict(tareas)
for t, d in tareas:
atomos.append(("z", t, 0, f"{t} ≥ 0", True)) # s_t >= 0
atomos.append((t, "z", H - d, f"{t} ≤ {H - d}", True)) # s_t + d <= H
for a, b in prec:
atomos.append((a, b, -dur[a], f"{a} → {b}", True)) # a termina antes de que empiece b
for (a, da), (b, db) in itertools.combinations(tareas, 2):
atomos.append((a, b, -da, f"{a} < {b}", False))
atomos.append((b, a, -db, f"{b} < {a}", False))
pares.append((len(atomos) - 2, len(atomos) - 1))
return atomos, pares
def arista(atomos, l):
x, y, c = atomos[abs(l) - 1][:3]
return (y, x, c) if l > 0 else (x, y, -c - 1) # ¬(x - y <= c) <=> y - x <= -c - 1 en enteros
def teoria(atomos, lits):
"""Bellman-Ford desde una fuente virtual: (True, modelo) o (False, literales de un ciclo negativo)."""
E = [(arista(atomos, l), l) for l in lits]
nodos = sorted({v for (u, w, _), _ in E for v in (u, w)})
dist = {v: 0 for v in nodos}; pred = {}
for _ in range(len(nodos)):
ultimo = None
for (u, v, w), l in E:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w; pred[v] = (u, l); ultimo = v
if ultimo is None:
return True, {v: dist[v] - dist["z"] for v in nodos}
v = ultimo
for _ in range(len(nodos)):
v = pred[v][0]
ciclo, u = [], v
while True:
u, l = pred[u]; ciclo.append(l)
if u == v:
return False, ciclo
def bucle_perezoso(atomos, pares, modo):
"""El SAT devuelve el primer modelo (cierto antes que falso, en el orden de los átomos) de la abstracción
booleana más lo aprendido; la teoría lo comprueba y explica con el ciclo ('min') o con todo ('full')."""
unidades = [k + 1 for k, a in enumerate(atomos) if a[4]]
libres = [k for k, a in enumerate(atomos) if not a[4]]
n = len(libres); bit = {a: 1 << (n - 1 - i) for i, a in enumerate(libres)}
aprendidas, vueltas, mask = [], 0, 0 # bit a 1: ese átomo libre es falso
while True:
while mask < (1 << n):
if all(not (mask & bit[p] and mask & bit[q]) for p, q in pares) and \
all((~mask & t) or (mask & f) for t, f in aprendidas):
break
mask += 1
else:
return "unsat", vueltas, None
vueltas += 1
lits = [-(a + 1) if mask & bit[a] else a + 1 for a in libres]
ok, res = teoria(atomos, unidades + lits)
if ok:
return "sat", vueltas, res
expl = res if modo == "min" else unidades + lits
if any(l < 0 and atomos[-l - 1][4] for l in expl):
continue # la cláusula contiene una unidad: siempre cierta
t = sum(bit[-l - 1] for l in expl if l < 0) # cláusula: alguno de estos libres cierto...
f = sum(bit[l - 1] for l in expl if l > 0 and not atomos[l - 1][4]) # ...o alguno de estos falso
aprendidas.append((t, f))
tres = [("A", 2), ("B", 3), ("C", 1)]
cuatro = tres + [("D", 2)]
for nombre, tareas, prec, Hs in (("3 tareas, A antes que C", tres, [("A", "C")], (5, 6)),
("4 tareas", cuatro, [], (7, 8))):
for H in Hs:
atomos, pares = planificacion(tareas, H, prec)
r1, v1, modelo = bucle_perezoso(atomos, pares, "min")
r2, v2, _ = bucle_perezoso(atomos, pares, "full")
print(f"{nombre}, H = {H}: {r1}; vueltas con el ciclo: {v1:3d}, con la asignación completa: {v2:3d}")
if modelo:
print(" modelo:", {t: modelo[t] for t, _ in tareas})Notice minimal explanations: several of the 8 rounds end in conflicts such as “ and ”, stating the obvious (two tasks cannot each precede the other). SAT discovers them one by one because it knows no arithmetic. If, upon SAT setting “” true, theory immediately reported that “” must be false, those conflicts would not arise. This is theory propagation. Together with checking theory during search rather than only on complete assignments, it distinguishes offline looping from DPLL(T).
DPLL(T): SAT and theory inside the same loop
Nieuwenhuis, Oliveras and Tinelli formalize DPLL(T) as transitions over states (trail and formula ), reproducing abstract CDCL rules (propagate, decide, fail, backjump, learn, forget, restart) and adding theory rules. Three defining DPLL(T):
- T-Propagate: if for unassigned literal of , add to the trail.
- T-Learn: if is -valid (and its atoms lie in or ), add it to .
- T-Forget: remove a learned -valid clause.
The central correctness result: if decides -consistency of literal conjunctions, executions meeting fairness conditions (not restarting or forgetting indefinitely without progress) terminate, reaching failure only if is -unsatisfiable, or otherwise a -consistent trail satisfying .
Proof
For the offline loop a three-line proof contains the idea. Unsat soundness: each learned clause negates a -inconsistent conjunction, so is -valid and adding it does not change the formula’s -models. If the abstraction plus learned clauses has no Boolean model, the original has no -model, because a -model would evaluate atoms to a Boolean abstraction model satisfying every -valid clause. Sat soundness: if theory accepts an assignment, its model makes exactly those literals true and thus satisfies abstraction and formula. Termination: each learned clause is false under the proposed assignment, preventing its return; there are assignments. Full DPLL(T) terminates by the CDCL argument: each backjump yields a lexicographically greater trail in a well-founded order, and theory rules add only literals or -valid clauses.
∎Requirements for a theory solver
Dutertre and de Moura (2006) describe the interface CDCL expects, implemented in the lab:
- Assert() adds a literal. It must be sound but may be incomplete: it may accept a literal even when the set is already inconsistent if detection is expensive.
- Check() decides current-state consistency and must be sound and complete. Multiple literals can therefore be asserted before one check.
- Backtrack() returns to the last checkpoint, forgetting later asserted literals.
- Optional Propagate() returns implied literals (possibly not all).
- To communicate with CDCL, the solver must explain each conflict and propagated literal.
Explanations fit 1-UIP conflict analysis. A theory conflict with explanation is treated as if clause existed and became false: resolve backward to the first UIP and use nonchronological backjumping. Theory propagation of with explanation enters the implication graph with reason clause , like unit propagation. Serious solvers generate such reasons lazily, only when conflict analysis asks, since most propagations never participate in conflict.
Two practical consequences:
- Explanations should be small. This accounts for 38 versus 729 rounds. Finding a minimal explanation can be expensive; solvers accept small explanations obtained cheaply from the algorithm (a cycle, simplex row, proof-forest path).
- Theory must backtrack cheaply. CDCL backtracks thousands of times per second. A theory solver rebuilding state each time is unusable. Difference logic and simplex backtrack without recomputation; for congruence closure, solvers log merges and undo them in reverse (often giving up path compression, expensive to undo; this lesson’s non-backtracking solvers use it).
Equality and uninterpreted functions: congruence closure
A set of equalities and inequalities between EUF terms is satisfiable iff no inequality joins terms forced equal by the equalities. Compute the smallest equivalence relation over subterms containing the equalities and closed under congruence.
Proof
In a model, “have equal value” contains , is an equivalence and is congruence-closed (functions are functions), so contains the smallest such relation ; if their values agree and the inequality is false. Conversely, if no inequality joins equivalent terms, construct a model with one element per class: universe , each term interpreted as its class, and if some has (any class otherwise). This is well-defined exactly because is congruence-closed: two applications with equivalent arguments share a class. By induction each evaluates to its class , so the model satisfies and, since , the inequalities.
∎The algorithm is union-find with union by rank and path compression, plus two indices:
- Each class has a use list: applications with some argument in that class.
- A signature table: application has signature . Applications with the same signature are congruent.
To process , merge distinct classes; applications on the absorbed class’s use list change signature, and any matching an existing signature enqueue a new equality. Always merging the smaller class into the larger gives Downey, Sethi and Tarjan’s bound, since each term changes class at most times.
The first problem is Nelson and Oppen’s classical congruence-closure example (1980). With , congruence gives and but there remain three classes, , and : a three-element model cyclically permuted by satisfies and . Adding merges the class of with ‘s, and congruence pulls in : everything collapses into one class and inequality conflicts, explained by both equalities.
Explanations: the proof forest
A theory solver’s congruence closure must explain why terms share a class. Union-find cannot: path compression and union by rank erase history. Nieuwenhuis and Oliveras (2007) separately maintain a proof forest: an undirected term graph with one edge per merge labeled by its reason (an input equality or congruence between specific applications). Merging classes of and reverses the path from to its root so becomes its tree root, then adds edge . Edges are never compressed, so terms in a class have a unique path. To explain :
- Find the common ancestor of and in the forest and traverse both paths.
- Each input edge contributes its equality.
- Each congruence edge between and generates subproblems , explained recursively.
The result is correct (input equalities implying ) and usually small, but history-dependent. In the figure’s second problem, reaching conflict via e4 () and e5 () yields explanation , even after adding e3 (), for which would suffice: e3 arrives when and already share a class, creates no merge and leaves no forest edge. Input equalities ignored by the explanation (e1 here) occur on no traversed path. The lab implements exactly this.
Lab 1: explaining congruence closure
The implementation follows that scheme: terms as strings (constants) or tuples (f, arg1, ..., argk), ranked and compressed union-find, use lists, signature table and proof forest. The first test is the figure example.
class Congruencia:
"""Cierre por congruencia con union-find (rango + compresión de caminos), listas de uso y bosque de pruebas.
Términos: cadenas (constantes) o tuplas (f, arg1, ..., argk)."""
def __init__(self):
self.id, self.term = {}, []
self.padre, self.rango = [], []
self.miembros, self.usos = [], [] # por representante: miembros de la clase y aplicaciones que la usan
self.firma = {} # (f, rep(arg1), ..., rep(argk)) -> nodo
self.prueba, self.razon = [], [] # bosque de pruebas: arista hacia el padre y su razón
self.pendiente = []
def nodo(self, t):
if t in self.id:
return self.id[t]
args = [self.nodo(a) for a in t[1:]] if isinstance(t, tuple) else []
i = len(self.term)
self.id[t] = i; self.term.append(t)
self.padre.append(i); self.rango.append(0); self.miembros.append([i]); self.usos.append([])
self.prueba.append(None); self.razon.append(None)
if args:
for a in set(self.find(a) for a in args):
self.usos[a].append(i)
clave = (t[0],) + tuple(self.find(a) for a in args)
if clave in self.firma: # congruente con un nodo ya existente
self.pendiente.append((i, self.firma[clave], ("cong", i, self.firma[clave])))
self._procesa()
else:
self.firma[clave] = i
return i
def find(self, i):
r = i
while self.padre[r] != r:
r = self.padre[r]
while self.padre[i] != r:
self.padre[i], i = r, self.padre[i]
return r
def _args(self, i):
t = self.term[i]
return [self.id[a] for a in t[1:]] if isinstance(t, tuple) else []
def igual(self, s, t, etiqueta):
a, b = self.nodo(s), self.nodo(t)
self.pendiente.append((a, b, ("entrada", etiqueta)))
self._procesa()
def _procesa(self):
while self.pendiente:
a, b, razon = self.pendiente.pop()
ra, rb = self.find(a), self.find(b)
if ra == rb:
continue
self._enraiza(a); self.prueba[a], self.razon[a] = b, razon
if self.rango[ra] > self.rango[rb]:
ra, rb = rb, ra # ra (la de menor rango) se cuelga de rb
self.padre[ra] = rb
self.rango[rb] += self.rango[ra] == self.rango[rb]
self.miembros[rb] += self.miembros[ra]
for u in self.usos[ra]: # las aplicaciones que usaban ra cambian de firma
clave = (self.term[u][0],) + tuple(self.find(x) for x in self._args(u))
if clave in self.firma and self.find(self.firma[clave]) != self.find(u):
v = self.firma[clave]
self.pendiente.append((u, v, ("cong", u, v)))
else:
self.firma[clave] = u
self.usos[rb].append(u)
def _enraiza(self, x):
"""Invierte el camino de x a su raíz en el bosque de pruebas: x pasa a ser raíz."""
previo, razon_previa = None, None
while x is not None:
sig, r = self.prueba[x], self.razon[x]
self.prueba[x], self.razon[x] = previo, razon_previa
previo, razon_previa, x = x, r, sig
def explica(self, s, t):
"""Conjunto de etiquetas de igualdades de entrada que implican s = t (None si no se deduce)."""
a, b = self.nodo(s), self.nodo(t)
if self.find(a) != self.find(b):
return None
usadas, hecho, tareas = set(), set(), [(a, b)]
while tareas:
x, y = tareas.pop()
anc = []
z = x
while z is not None:
anc.append(z); z = self.prueba[z]
z = y
while z not in anc:
z = self.prueba[z]
comun = z
for z in (x, y):
while z != comun:
if z not in hecho:
hecho.add(z)
r = self.razon[z]
if r[0] == "entrada":
usadas.add(r[1])
else:
tareas += list(zip(self._args(r[1]), self._args(r[2])))
z = self.prueba[z]
return usadas
# Comprobación: el ejemplo clásico f³(a) = a, f⁵(a) = a ⊢ f(a) = a
def f(t, n=1):
for _ in range(n): t = ("f", t)
return t
cc = Congruencia()
for k in range(6): cc.nodo(f("a", k))
cc.igual(f("a", 3), "a", "e1")
print("tras e1: ¿f(a) = a?", cc.explica(f("a"), "a"), " ¿f⁴(a) = f(a)?", sorted(cc.explica(f("a", 4), f("a"))))
cc.igual(f("a", 5), "a", "e2")
print("tras e2: ¿f(a) = a?", sorted(cc.explica(f("a"), "a")))After e1, is not deduced (returns None), and is explained by e1 alone; after e2, needs both.
A real application: translation validation (Pnueli, Siegel and Singerman, 1998; Necula, 2000). Rather than prove an optimizer correct for every program, check each translation: convert source and optimized programs in SSA form into equalities, leave operators uninterpreted, and ask whether outputs are equal. Rewrites below are common-subexpression elimination (CSE) applied once and twice, a buggy rewrite, and one using addition commutativity.
# Validación de traducciones: dos cadenas de reescrituras de un compilador de juguete.
# Un programa es una lista de asignaciones en SSA (cada variable se asigna una vez); los operadores son
# funciones NO interpretadas: no sabemos nada de mul ni de add salvo que son funciones.
def ecuaciones(prog, sufijo):
"""Cada asignación v = op(a, b) da la igualdad v_sufijo = op(a', b'); las entradas son comunes."""
nombre = lambda x: x if x in ENTRADAS else f"{x}{sufijo}"
eqs = []
for v, (op, *args) in prog:
rhs = nombre(args[0]) if op == "copia" else (op, *[nombre(a) for a in args])
eqs.append((nombre(v), rhs, f"{v}{sufijo}"))
return eqs
ENTRADAS = {"a", "b", "c"}
fuente = [("t1", ("mul", "a", "b")), ("t2", ("mul", "a", "b")), ("t3", ("add", "t1", "c")),
("t4", ("add", "t2", "c")), ("r", ("sub", "t3", "t4"))]
# reescritura 1: eliminación de subexpresiones comunes (t2 := t1) y propagación de copias
cse = [("t1", ("mul", "a", "b")), ("t3", ("add", "t1", "c")), ("t4", ("add", "t1", "c")), ("r", ("sub", "t3", "t4"))]
# reescritura 2: otra vez CSE (t4 := t3)
cse2 = [("t1", ("mul", "a", "b")), ("t3", ("add", "t1", "c")), ("r", ("sub", "t3", "t3"))]
# una reescritura con un error: confunde b con c en la segunda multiplicación
mala = [("t1", ("mul", "a", "b")), ("t3", ("add", "t1", "c")), ("t4", ("add", ("mul", "a", "c"), "c")),
("r", ("sub", "t3", "t4"))]
# una correcta que EUF no puede justificar: usa que add es conmutativa
conm = [("t1", ("mul", "a", "b")), ("t3", ("add", "c", "t1")), ("r", ("sub", "t3", "t3"))]
def plano(prog):
"""Las subexpresiones anidadas se nombran con temporales nuevos (el programa queda en forma plana)."""
out, n = [], 0
def sube(e):
nonlocal n
if isinstance(e, tuple):
n += 1; v = f"_k{n}"; out.append((v, (e[0], *[sube(a) for a in e[1:]]))); return v
return e
for v, (op, *args) in prog:
out.append((v, (op, *[sube(a) for a in args])))
return out
def equivalentes(p, q):
cc = Congruencia()
for x, y, et in ecuaciones(plano(p), "_p") + ecuaciones(plano(q), "_q"):
cc.igual(x, y, et)
return cc.explica("r_p", "r_q"), cc
OPS = {"mul": lambda x, y: x * y, "add": lambda x, y: x + y, "sub": lambda x, y: x - y}
def evalua(prog, entrada):
env = dict(entrada)
for v, (op, *args) in plano(prog):
env[v] = OPS[op](*[env[a] for a in args])
return env["r"]
punto = {"a": 3, "b": 5, "c": 7}
for nombre, q in (("CSE", cse), ("CSE dos veces", cse2), ("con error", mala), ("conmutatividad", conm)):
expl, cc = equivalentes(fuente, q)
if expl is None:
print(f"{nombre:15s}: r_fuente = r_optimizado NO se deduce en EUF ({len(set(map(cc.find, range(len(cc.term))))):d} clases); "
f"con la aritmética de verdad en {punto}: fuente {evalua(fuente, punto)}, optimizado {evalua(q, punto)}")
else:
print(f"{nombre:15s}: equivalentes; la prueba usa {len(expl)} de las {len(fuente) + len(plano(q))} definiciones: {sorted(expl)}")The four cases show what abstraction gives and loses. Both CSE rewrites validate using all definitions. The buggy rewrite fails validation, and evaluation on actual numbers confirms it is wrong (source gives 0, optimized version −6). The rewrite commuting add also fails validation, but both versions give 0: a false alarm. EUF does not know addition is commutative; “not implied” means “not implied by operators being functions”, not “different”. To validate this rewrite give the solver more theory, e.g. integer arithmetic; lab 3 shows Z3 succeeds once operators are interpreted.
Difference logic: conflicts are negative cycles
Many scheduling, circuit-timing and timed-system verification problems use only constraints of the form “ cannot exceed by more than ”.
Edge direction is not arbitrary: using distances, the constraint says , the triangle inequality for edge . Summing constraints around a cycle cancels variables pairwise and leaves cycle weight. Therefore:
The guided exercise proves this. Two consequences matter for DPLL(T):
- Free minimal explanations. Edges of a simple negative cycle form a minimal inconsistent set: remove any and the rest is an acyclic path, with no negative cycle. Bellman–Ford finds one by following predecessors from the last relaxed vertex.
- Models translate. If is a model, so is , since only differences occur. Thus origin can be fixed at the end.
Initially the five simple cycles weigh 1, 1, 1, 5 and 6; virtual-source distances are , translated so to yield : check each constraint. Edge r2 (, weight ) lies in four of five cycles, three of weight 1, so lowering it to makes three cycles weigh ; Bellman–Ford returns one.
An incremental solver
DPLL(T) cannot run Bellman–Ford from scratch at every query. The lab solver maintains a potential , a model of active constraints, and upon adding edge of weight :
- If , the edge already holds and nothing is needed.
- Otherwise lower to and propagate the decrease to successors, as Bellman–Ford but only in the affected region.
- If propagation lowers , the repair path from to closed by the new edge is a negative cycle: undo changes and return the cycle as explanation.
Backtracking is trivial: remove edges and leave unchanged, because a model of constraints also models any subset. This makes simplex backtracking cheap too. For theory propagation, adding triggers Dijkstra distances to and from (using reduced costs , nonnegative because is a model): a free atom follows if , explained by that path. This simplifies Cotton and Maler’s propagation (2006).
Lab 2: DPLL(T) for difference logic
First the engine: compact CDCL (watches, 1-UIP, backjumping, activity and saved phase as before) with a theory hook, plus the incremental difference solver with explanations and propagation. Finally the dialogue figure’s tasks.
import time, heapq
class CDCL:
"""CDCL compacto: vigilados, 1-UIP, backjumping, actividad tipo VSIDS y fase guardada.
Opcionalmente dialoga con un solver de teoría (DPLL(T)): ver el método _teoria."""
def __init__(self, nvars, clauses, theory=None):
self.n = nvars
self.val = [0] * (nvars + 1) # 1, -1 o 0
self.level = [0] * (nvars + 1)
self.reason = [None] * (nvars + 1) # índice de cláusula o None (decisión)
self.act = [0.0] * (nvars + 1)
self.phase = [-1] * (nvars + 1)
self.inc = 1.0
self.trail, self.lim = [], []
self.clauses, self.watch = [], {}
self.qhead = 0
self.th, self.thead = theory, 0 # el solver de teoría ve el trail a partir de thead
self.stats = dict(conflicts=0, decisions=0, props=0, t_conflicts=0, t_props=0)
self.ok = True
for c in clauses:
if not self.add_clause(list(c)):
self.ok = False
def value(self, l):
v = self.val[abs(l)]
return v if l > 0 else -v
def add_clause(self, c, learnt=False):
c = list(dict.fromkeys(c))
if not learnt and any(-l in c for l in c):
return True # tautología
if len(c) == 0:
return False
if len(c) == 1:
if self.value(c[0]) == -1:
return False
if self.value(c[0]) == 0:
self.enqueue(c[0], None)
return True
i = len(self.clauses)
self.clauses.append(c)
self.watch.setdefault(c[0], []).append(i)
self.watch.setdefault(c[1], []).append(i)
return True
def enqueue(self, l, reason):
v = abs(l)
self.val[v] = 1 if l > 0 else -1
self.level[v] = len(self.lim)
self.reason[v] = reason
self.trail.append(l)
def propagate(self):
while self.qhead < len(self.trail):
l = self.trail[self.qhead]; self.qhead += 1
fl = -l # literal que acaba de hacerse falso
ws = self.watch.get(fl, [])
keep = []
i = 0
while i < len(ws):
ci = ws[i]; i += 1
c = self.clauses[ci]
if c[0] == fl:
c[0], c[1] = c[1], c[0]
if self.value(c[0]) == 1:
keep.append(ci); continue
for k in range(2, len(c)):
if self.value(c[k]) != -1:
c[1], c[k] = c[k], c[1]
self.watch.setdefault(c[1], []).append(ci)
break
else:
keep.append(ci)
if self.value(c[0]) == -1: # conflicto
keep.extend(ws[i:])
self.watch[fl] = keep
return ci
self.enqueue(c[0], ci); self.stats['props'] += 1
self.watch[fl] = keep
return None
def analyze(self, confl):
seen = set(); learnt = [None]; cnt = 0
lits = self.clauses[confl]
idx = len(self.trail) - 1
cur = len(self.lim)
p = None
while True:
for q in (lits if p is None else lits[1:]):
v = abs(q)
if v not in seen and self.level[v] > 0:
seen.add(v)
self.act[v] += self.inc
if self.level[v] == cur:
cnt += 1
else:
learnt.append(q)
while abs(self.trail[idx]) not in seen:
idx -= 1
p = self.trail[idx]; idx -= 1
seen.discard(abs(p)); cnt -= 1
if cnt == 0:
break
lits = self.clauses[self.reason[abs(p)]]
# la razón tiene el literal propagado en la posición 0
if lits[0] != p:
j = lits.index(p); lits[0], lits[j] = lits[j], lits[0]
learnt[0] = -p
self.inc *= 1.05
bt = 0
if len(learnt) > 1:
j = max(range(1, len(learnt)), key=lambda k: self.level[abs(learnt[k])])
learnt[1], learnt[j] = learnt[j], learnt[1]
bt = self.level[abs(learnt[1])]
return learnt, bt
def backjump(self, lvl):
if len(self.lim) <= lvl:
return
start = self.lim[lvl]
for l in self.trail[start:]:
v = abs(l); self.phase[v] = self.val[v]; self.val[v] = 0; self.reason[v] = None
del self.trail[start:]; del self.lim[lvl:]
self.qhead = min(self.qhead, start)
if self.th is not None and self.thead > start:
self.th.backtrack(start) # la teoría olvida lo que vio más allá de start
self.thead = start
def _teoria(self):
"""Pasa a la teoría los literales nuevos del trail. Devuelve el índice de una cláusula
de conflicto (explicación), o None. Las propagaciones de teoría entran como cláusulas razón."""
while self.thead < len(self.trail):
l = self.trail[self.thead]; self.thead += 1
expl = self.th.assert_lit(l, self.thead)
if expl is not None: # conflicto: los literales de expl son todos ciertos
self.stats['t_conflicts'] += 1
c = [-e for e in expl]
c.sort(key=lambda q: -self.level[abs(q)])
return self._add_reason(c)
for l, expl in self.th.implied(self.value):
if self.value(l) == 0:
self.stats['t_props'] += 1
ci = self._add_reason([l] + [-e for e in expl])
self.enqueue(l, ci)
return None
def _add_reason(self, c):
i = len(self.clauses); self.clauses.append(c)
if len(c) >= 2:
self.watch.setdefault(c[0], []).append(i); self.watch.setdefault(c[1], []).append(i)
return i
def solve(self, budget=200000):
if not self.ok:
return False
while True:
confl = self.propagate()
if confl is None and self.th is not None:
confl = self._teoria()
if confl is None and self.qhead < len(self.trail):
continue # la teoría ha propagado: vuelve a BCP
if confl is not None:
self.stats['conflicts'] += 1
if not self.lim:
return False
learnt, bt = self.analyze(confl)
self.backjump(bt)
if len(learnt) == 1:
self.enqueue(learnt[0], None)
else:
ci = self._add_reason(learnt)
self.enqueue(learnt[0], ci)
if self.stats['conflicts'] > budget:
return None
continue
free = [v for v in range(1, self.n + 1) if self.val[v] == 0]
if not free:
return True
v = max(free, key=lambda u: self.act[u])
self.stats['decisions'] += 1
self.lim.append(len(self.trail))
self.enqueue(v if self.phase[v] > 0 else -v, None)
class DiffLogic:
"""Solver de teoría incremental para lógica de diferencias entera.
Átomo k: x - y <= c, arista y -> x de peso c. Su negación: y - x <= -c - 1.
Mantiene un potencial pi factible (un modelo) y lo repara al añadir cada arista."""
def __init__(self, atoms, propagate=True):
self.atoms = atoms # atoms[k] = (x, y, c); variable booleana k + 1
self.nodes = list(dict.fromkeys([a[0] for a in atoms] + [a[1] for a in atoms]))
self.pi = {v: 0 for v in self.nodes}
self.out = {v: [] for v in self.nodes} # aristas activas: (destino, peso, literal)
self.inn = {v: [] for v in self.nodes}
self.stack = [] # (posición en el trail, origen, destino)
self.do_prop = propagate
self.pending = []
def edge(self, l):
x, y, c = self.atoms[abs(l) - 1]
return (y, x, c) if l > 0 else (x, y, -c - 1)
def assert_lit(self, l, pos):
u, v, w = self.edge(l)
self.out[u].append((v, w, l)); self.inn[v].append((u, w, l)); self.stack.append((pos, u, v))
if self.pi[u] + w < self.pi[v]:
old = {v: self.pi[v]}; pred = {v: (u, l)}
self.pi[v] = self.pi[u] + w
queue = [v]
while queue:
a = queue.pop()
for b, wb, lb in self.out[a]:
if self.pi[a] + wb < self.pi[b]:
if b == u: # la reparación vuelve al origen: ciclo negativo
cyc = [l, lb]; z = a
while z != v:
z, lz = pred[z]; cyc.append(lz)
for k, val in old.items():
self.pi[k] = val # deshace la reparación a medias
return cyc
old.setdefault(b, self.pi[b])
self.pi[b] = self.pi[a] + wb; pred[b] = (a, lb)
queue.append(b)
if self.do_prop:
self._propagar(u, v, w, l)
return None
def _dijkstra(self, s, forward):
# caminos mínimos con costes reducidos pi(a) + w - pi(b) >= 0 (no negativos)
pi = self.pi; dist = {s: 0}; pred = {}; heap = [(0, 0, s)]; done = set(); n = 0
adj = self.out if forward else self.inn
while heap:
d, _, a = heapq.heappop(heap)
if a in done:
continue
done.add(a)
for b, w, l in adj[a]:
rc = (pi[a] + w - pi[b]) if forward else (pi[b] + w - pi[a])
if b not in dist or d + rc < dist[b]:
dist[b] = d + rc; pred[b] = (a, l); n += 1; heapq.heappush(heap, (dist[b], n, b))
# deshace la reducción: distancia real entre s y b
real = {b: (d - pi[s] + pi[b]) if forward else (d - pi[b] + pi[s]) for b, d in dist.items()}
return real, pred
def _camino(self, pred, s, t):
path = []
while t != s:
t, l = pred[t]; path.append(l)
return path
def _propagar(self, u, v, w, l):
"""Átomos implicados por un camino que usa la arista nueva u -> v."""
hacia_u, pu = self._dijkstra(u, False) # dist(a, u) para cada a
desde_v, pv = self._dijkstra(v, True) # dist(v, b) para cada b
for k, (x, y, c) in enumerate(self.atoms):
# x - y <= c es consecuencia si dist(y, x) <= c; su negación, si dist(x, y) <= -c - 1
for lit, a, b, bound in ((k + 1, y, x, c), (-(k + 1), x, y, -c - 1)):
if a in hacia_u and b in desde_v and hacia_u[a] + w + desde_v[b] <= bound:
expl = self._camino(pu, u, a) + [l] + self._camino(pv, v, b)
self.pending.append((lit, expl)); break
def implied(self, value):
res = [(lit, e) for lit, e in self.pending if value(lit) == 0]
self.pending = []
return res
def backtrack(self, pos):
self.pending = []
while self.stack and self.stack[-1][0] > pos:
_, u, v = self.stack.pop(); self.out[u].pop(); self.inn[v].pop()
# pi sigue siendo un modelo de las aristas que quedan: no hay nada más que deshacer
def model(self):
return dict(self.pi)
# Prueba: las tareas de la figura del diálogo, ahora con CDCL + teoría incremental
for H in (5, 6):
atomos, pares = planificacion(tres, H, [("A", "C")])
clausulas = [[k + 1] for k, a in enumerate(atomos) if a[4]] + [[p + 1, q + 1] for p, q in pares]
for prop in (False, True):
th = DiffLogic([a[:3] for a in atomos], propagate=prop)
s = CDCL(len(atomos), clausulas, theory=th)
r = s.solve()
modelo = {t: th.pi[t] - th.pi["z"] for t, _ in tres} if r else None
print(f"H = {H}, propagación de teoría {'sí' if prop else 'no'}: {'sat' if r else 'unsat'}; "
f"conflictos {s.stats['conflicts']} (de teoría {s.stats['t_conflicts']}), "
f"propagaciones de teoría {s.stats['t_props']}, decisiones {s.stats['decisions']}; modelo {modelo}")With theory propagation, case solves without a single decision: unit clauses (deadlines and A-before-C) let theory deduce 4 orders and reach level-0 conflict. Without propagation it takes 4 decisions and 5 theory conflicts. With , the potential’s schedule ( at 0, at 3, at 5) meets precedence and deadline.
Now a real problem: a random job shop of 5 jobs and 5 machines, durations 1 to 9. Each job visits machines in order and operations on a machine cannot overlap. Can everything finish before ? Within-job precedences are units; each pair of operations on one machine gives a disjunction of two difference atoms: 150 atoms total. Independently, the same CDCL solves the order encoding of the same problem from lesson 11, using variables for each time .
import itertools, random, time
def jobshop(n_jobs, n_mach, seed, dmax=9):
rnd = random.Random(seed)
jobs = []
for j in range(n_jobs):
orden = list(range(n_mach)); rnd.shuffle(orden)
jobs.append([(m, rnd.randint(1, dmax)) for m in orden])
return jobs
def escalar(jobs, k):
return [[(m, d * k) for m, d in job] for job in jobs]
def codifica_dl(jobs, M):
"""Átomos x - y <= c sobre los inicios s_jk y el origen z. Devuelve (átomos, cláusulas)."""
atoms, clauses = [], []
def atom(x, y, c):
atoms.append((x, y, c)); return len(atoms)
ops = {}
for j, job in enumerate(jobs):
for k, (m, d) in enumerate(job):
ops[(j, k)] = (m, d)
clauses.append([atom('z', (j, k), 0)]) # s >= 0
if k + 1 < len(job):
clauses.append([atom((j, k), (j, k + 1), -d)]) # precedencia en el trabajo
k = len(job) - 1
clauses.append([atom((j, k), 'z', M - job[k][1])]) # termina antes de M
por_maquina = {}
for o, (m, d) in ops.items():
por_maquina.setdefault(m, []).append(o)
for m, lst in por_maquina.items():
for a, b in itertools.combinations(lst, 2):
da, db = ops[a][1], ops[b][1]
clauses.append([atom(a, b, -da), atom(b, a, -db)]) # a antes que b, o b antes que a
return atoms, clauses
def resuelve_dl(jobs, M, propagar=True):
atoms, clauses = codifica_dl(jobs, M)
th = DiffLogic(atoms, propagate=propagar)
s = CDCL(len(atoms), clauses, theory=th)
t0 = time.perf_counter(); r = s.solve(); t = time.perf_counter() - t0
modelo = None
if r:
pi = th.model(); modelo = {o: pi[o] - pi['z'] for o in th.nodes if o != 'z'}
return r, s, t, modelo, len(atoms), len(s.clauses)
def codifica_orden(jobs, M):
"""Codificación de orden: q[o][t] <=> s_o <= t, t = 0..H-1 con H = M - d_o (s_o <= H siempre)."""
nv = 0; clauses = []
def var():
nonlocal nv; nv += 1; return nv
ops = {}; q = {}
for j, job in enumerate(jobs):
for k, (m, d) in enumerate(job):
ops[(j, k)] = (m, d)
for o, (m, d) in ops.items():
H = M - d
if H < 0:
return nv, [[]]
q[o] = [var() for _ in range(H)] # q[o][t] para t < H; s_o <= H se cumple siempre
for t in range(H - 1):
clauses.append([-q[o][t], q[o][t + 1]]) # s <= t -> s <= t + 1
def le(o, t): # literal de s_o <= t (True/False si es constante)
H = M - ops[o][1]
if t < 0: return False
if t >= H: return True
return q[o][t]
def precede(a, b, sel=None):
# s_b >= s_a + d_a <=> para todo t: s_b <= t -> s_a <= t - d_a
da = ops[a][1]; Hb = M - ops[b][1]
for t in range(-1, Hb + 1):
lb, la = le(b, t), le(a, t - da)
if lb is False or la is True:
continue
c = [] if sel is None else [-sel]
if lb is not True: c.append(-lb)
if la is not False: c.append(la)
clauses.append(c)
for j, job in enumerate(jobs):
for k in range(len(job) - 1):
precede((j, k), (j, k + 1))
por_maquina = {}
for o, (m, d) in ops.items():
por_maquina.setdefault(m, []).append(o)
for m, lst in por_maquina.items():
for a, b in itertools.combinations(lst, 2):
sel = var()
precede(a, b, sel); precede(b, a, -sel)
return nv, clauses
def resuelve_orden(jobs, M):
nv, clauses = codifica_orden(jobs, M)
s = CDCL(nv, clauses)
t0 = time.perf_counter(); r = s.solve(); t = time.perf_counter() - t0
return r, s, t, nv, len(clauses)
def valida(jobs, M, inicio):
ok = all(v >= 0 for v in inicio.values())
for j, job in enumerate(jobs):
for k, (m, d) in enumerate(job):
if k + 1 < len(job): ok &= inicio[(j, k + 1)] >= inicio[(j, k)] + d
ok &= inicio[(j, len(job) - 1)] + job[-1][1] <= M
ops = [(j, k) for j, job in enumerate(jobs) for k in range(len(job))]
for a, b in itertools.combinations(ops, 2):
(ma, da), (mb, db) = jobs[a[0]][a[1]], jobs[b[0]][b[1]]
if ma == mb: ok &= inicio[b] >= inicio[a] + da or inicio[a] >= inicio[b] + db
return ok
jobs = jobshop(5, 5, seed=2)
print("trabajos (máquina, duración):")
for j, job in enumerate(jobs): print(f" J{j}: {job}")
cota = max(max(sum(d for _, d in job) for job in jobs),
max(sum(d for job in jobs for m, d in job if m == mm) for mm in range(5)))
# búsqueda del makespan óptimo: subir desde la cota inferior hasta el primer M satisfacible
M = cota
while not resuelve_dl(jobs, M)[0]:
M += 1
print(f"cota inferior trivial {cota}; makespan óptimo {M}")
for MM in (M - 1, M):
for prop in (False, True):
r, s, t, ini, na, nc = resuelve_dl(jobs, MM, prop)
print(f"M = {MM} DPLL(T) {'con' if prop else 'sin'} propagación de teoría: {'sat' if r else 'unsat'}"
f"{' (calendario válido: ' + str(valida(jobs, MM, ini)) + ')' if r else ''}; "
f"{na} átomos, conflictos {s.stats['conflicts']}, propagaciones de teoría {s.stats['t_props']}")
r, s, t, nv, nc = resuelve_orden(jobs, MM)
print(f"M = {MM} codificación de orden, mismo CDCL: {'sat' if r else 'unsat'}; {nv} variables, {nc} cláusulas, "
f"conflictos {s.stats['conflicts']}")The encodings agree: 53 is unsatisfiable and 54 satisfiable, and the DPLL(T) schedule passes independent validation. Theory propagation reduces conflicts more than tenfold (55 to 5 at and 47 to 4 at ). Order encoding needs about 1200 variables and 7000 clauses versus 150 atoms because it has a variable per operation and time. With single-digit durations this is no penalty: it propagates as well as theory (5 conflicts at ) and in the next cell with is even faster than our Python DPLL(T). What if durations use units ten times finer?
import matplotlib.pyplot as plt
filas = []
for k in (1, 2, 4, 8):
J = escalar(jobs, k)
t0 = time.perf_counter(); r1, s1, _, _, na, _ = resuelve_dl(J, (M - 1) * k); t1 = time.perf_counter() - t0
t0 = time.perf_counter(); r2, s2, _, nv, nc = resuelve_orden(J, (M - 1) * k); t2 = time.perf_counter() - t0
filas.append((k, na, len(s1.clauses), t1, nv, nc, t2))
print(f"duraciones x{k}: M = {(M - 1) * k} ({'sat' if r1 else 'unsat'}/{'sat' if r2 else 'unsat'}) "
f"DPLL(T): {na} átomos, {s1.stats['conflicts']} conflictos, {t1:.3f} s | "
f"orden: {nv} variables, {nc} cláusulas, {s2.stats['conflicts']} conflictos, {t2:.3f} s")
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ks = [f[0] for f in filas]
ax[0].plot(ks, [f[1] for f in filas], "o-", label="DPLL(T): átomos")
ax[0].plot(ks, [f[5] for f in filas], "s-", label="orden: cláusulas")
ax[0].set_xscale("log", base=2); ax[0].set_yscale("log"); ax[0].set_xlabel("factor de escala de las duraciones")
ax[0].set_title("Tamaño de la codificación"); ax[0].legend()
ax[1].plot(ks, [f[3] for f in filas], "o-", label="DPLL(T)")
ax[1].plot(ks, [f[6] for f in filas], "s-", label="orden (codificar y resolver)")
ax[1].set_xscale("log", base=2); ax[1].set_yscale("log"); ax[1].set_xlabel("factor de escala de las duraciones")
ax[1].set_title("Tiempo hasta probar M − 1 insatisfacible (s)"); ax[1].legend()
plt.tight_layout(); plt.show()Multiplying every duration by (and deadline by ) leaves the problem unchanged: DPLL(T) atoms and conflicts do not change and runtime barely moves. Order encoding grows linearly with in variables and clauses (at already about 55,000) and runtime grows at least as fast even with unchanged conflicts: size is the cost. This illustrates the lazy approach: theory treats constants as numbers, while Boolean encoding must represent them.
Linear arithmetic: general simplex
For general linear constraints , the decision procedure is linear-programming simplex adapted to DPLL(T): no objective (feasibility only), atoms arrive and leave thousands of times per second, and every conflict needs an explanation. Yices, Z3 and other modern solvers use Dutertre and de Moura’s (2006) version.
Since is fixed, rows are never added or removed: asserting an atom changes a bound; backtracking restores previous bounds (saved on a stack) and the last assignment passing Check, which satisfies all earlier checkpoint bounds. No pivots. The paper contrasts this with classical incremental simplex, which added and removed rows and might need to pivot on backtracking.
Check repeats until no basic variable violates its bounds:
- Take the smallest basic (in a fixed total order) with or .
- If below, find the smallest nonbasic in its row that can raise it: and , or and . If above, reverse directions.
- If none, conflict. Otherwise pivot with and set to the violated bound.
Always choosing the smallest variable is Bland’s rule, guaranteeing no cycling and termination of Check.
The row supplies the explanation. If is below and no nonbasic can raise it, each with is at its upper bound and each with at its lower bound. Thus for any with satisfying those bounds,
so is inconsistent: a Farkas certificate read directly from the tableau.
In the figure, pivoting from the initial state removes and introduces : tableau becomes , , and assignment jumps to . Bound b3 () moves nonbasic to 2 without pivoting, giving . With instead of 6, row can no longer decrease: is at lower bound 1 and at its own, 2, so ; explanation . Bound b4 does not participate despite being asserted.
What a real solver adds
- Strict inequalities. Dutertre and de Moura leave the algorithm unchanged: replace by with symbolic infinitesimal . Bounds and values become lexicographically ordered pairs representing , and their Lemma 1 guarantees strict constraints are satisfiable iff the nonstrict ones are satisfiable for some sufficiently small rational , computed at the end.
- Theory propagation by bound refinement. A row and its nonbasic bounds imply bounds for its basic variable, propagating atoms such as . The authors credit cheap backtracking, preprocessing and propagation for improvements in their evaluation, where their solver was even faster on difference logic than specialized solvers of the time.
- Integers. If variables are integer, the simplex solution may not be. The paper uses branch and cut: branch on fractional variable with atoms or , treated by CDCL like any others, and add Gomory cuts, which the authors report drastically accelerating convergence in several cases.
Cost. One pivot costs about tableau size (rows times columns for dense; far less for typical sparse rows). Check may take exponentially many pivots in the worst case, even with Bland’s rule (Avis and Chvátal, 1978), but in SMT each Check usually repairs few bounds from a nearly valid assignment using very few pivots. Call count dominates, making pivot-free backtracking and propagation important.
from fractions import Fraction as F
import random
class SimplexSMT:
"""Símplex general de Dutertre y de Moura (2006): tableau fijo, cotas que van y vienen, Check con la regla de Bland.
Variables 0..n-1 originales; cada forma lineal sum a_j x_j recibe una holgura básica s_i = sum a_j x_j."""
def __init__(self, n, formas):
self.N = n + len(formas)
self.fila = {n + i: {j: F(a) for j, a in enumerate(f) if a} for i, f in enumerate(formas)} # básica -> fila
self.val = [F(0)] * self.N
self.lo, self.hi = [None] * self.N, [None] * self.N # (valor, etiqueta del átomo)
self.pivotes = 0
def _actualiza(self, j, v):
d = v - self.val[j]
for b, r in self.fila.items():
if j in r:
self.val[b] += r[j] * d
self.val[j] = v
def aserta(self, x, tipo, k, etiqueta):
"""tipo '<=' o '>='. Devuelve una explicación si choca con la otra cota de x; si no, None."""
k = F(k)
if tipo == "<=":
if self.lo[x] and k < self.lo[x][0]: return {self.lo[x][1], etiqueta}
if self.hi[x] is None or k < self.hi[x][0]:
self.hi[x] = (k, etiqueta)
if x not in self.fila and self.val[x] > k: self._actualiza(x, k)
else:
if self.hi[x] and k > self.hi[x][0]: return {self.hi[x][1], etiqueta}
if self.lo[x] is None or k > self.lo[x][0]:
self.lo[x] = (k, etiqueta)
if x not in self.fila and self.val[x] < k: self._actualiza(x, k)
return None
def _pivota(self, xi, xj):
r = self.fila.pop(xi); a = r.pop(xj)
nueva = {k: -c / a for k, c in r.items()}; nueva[xi] = 1 / a # xj en función de xi y del resto
for b, rb in self.fila.items():
if xj in rb:
c = rb.pop(xj)
for k, ck in nueva.items():
v = rb.get(k, 0) + c * ck
if v: rb[k] = v
else: rb.pop(k, None)
self.fila[xj] = nueva
self.pivotes += 1
def check(self):
"""Devuelve None si las cotas son compatibles; si no, la explicación (etiquetas de las cotas de una fila)."""
while True:
malas = [b for b in sorted(self.fila) if (self.lo[b] and self.val[b] < self.lo[b][0]) or
(self.hi[b] and self.val[b] > self.hi[b][0])]
if not malas:
return None
xi = malas[0]; r = self.fila[xi]
baja = bool(self.lo[xi]) and self.val[xi] < self.lo[xi][0]
def puede(j): # ¿puede xj mover xi en la dirección necesaria?
sube_j = (r[j] > 0) == baja
return (self.hi[j] is None or self.val[j] < self.hi[j][0]) if sube_j else \
(self.lo[j] is None or self.val[j] > self.lo[j][0])
cand = [j for j in sorted(r) if puede(j)]
if not cand:
expl = {self.lo[xi][1] if baja else self.hi[xi][1]}
for j, c in r.items():
b = self.hi[j] if (c > 0) == baja else self.lo[j]
expl.add(b[1])
return expl
xj = cand[0]
objetivo = self.lo[xi][0] if baja else self.hi[xi][0]
theta = (objetivo - self.val[xi]) / r[xj]
self.val[xi] = objetivo; self.val[xj] += theta
for b, rb in self.fila.items():
if b != xi and xj in rb: self.val[b] += rb[xj] * theta
self._pivota(xi, xj)
def resuelve(n, formas, atomos):
"""atomos: lista de (índice de forma o -1-j para la variable j, tipo, k). Devuelve (sat, explicación, pivotes)."""
s = SimplexSMT(n, formas)
for e, (f, tipo, k) in enumerate(atomos):
x = n + f if f >= 0 else -1 - f
ex = s.aserta(x, tipo, k, e)
if ex: return False, ex, s.pivotes, s
ex = s.check()
if ex: return False, ex, s.pivotes, s
return True, None, s.pivotes, s
# El ejemplo de la figura: s1 = x + y <= 4, s2 = x - y >= 1, y >= 2, x <= 4
sat, ex, piv, s = resuelve(2, [[1, 1], [1, -1]], [(0, "<=", 4), (1, ">=", 1), (-2, ">=", 2), (-1, "<=", 4)])
print("figura con b1: x + y <= 4 ->", "sat" if sat else f"unsat, explicación {sorted(f'b{e + 1}' for e in ex)}", f"tras {piv} pivote(s)")
sat, ex, piv, s = resuelve(2, [[1, 1], [1, -1]], [(0, "<=", 6), (1, ">=", 1), (-2, ">=", 2), (-1, "<=", 4)])
print("figura con b1: x + y <= 6 ->", "sat" if sat else "unsat", f"tras {piv} pivote(s); modelo x = {s.val[0]}, y = {s.val[1]}")
# Validación aleatoria contra HiGHS y tamaño de las explicaciones
from scipy.optimize import linprog
import numpy as np
rnd = random.Random(3)
acuerdos = minimas = conflictos = 0; tam = []
for prueba in range(150):
n, m = 3, 4
formas = [[rnd.randint(-3, 3) for _ in range(n)] for _ in range(m)]
atomos = [(rnd.randrange(-n, m), rnd.choice(["<=", ">="]), rnd.randint(-4, 4)) for _ in range(6)]
sat, ex, piv, _ = resuelve(n, formas, atomos)
# el mismo problema para HiGHS: A_ub x <= b_ub con cada forma (o variable) y su cota
filas, b = [], []
for f, tipo, k in atomos:
a = formas[f] if f >= 0 else [1 if j == -1 - f else 0 for j in range(n)]
sg = 1 if tipo == "<=" else -1
filas.append([sg * v for v in a]); b.append(sg * k)
ref = linprog(np.zeros(n), A_ub=filas, b_ub=b, bounds=[(None, None)] * n, method="highs").status == 0
acuerdos += sat == ref
if not sat:
conflictos += 1; tam.append(len(ex))
sub = [atomos[e] for e in sorted(ex)]
assert not resuelve(n, formas, sub)[0], "la explicación debe ser insatisfacible por sí sola"
minimas += all(resuelve(n, formas, sub[:i] + sub[i + 1:])[0] for i in range(len(sub)))
print(f"coincide con HiGHS en {acuerdos} de 150 problemas; {conflictos} insatisfacibles")
print(f"explicaciones: tamaño medio {sum(tam) / len(tam):.2f} de 6 átomos; {minimas} de {conflictos} son mínimas "
f"(quitar cualquier átomo las hace satisfacibles)")The implementation agrees with HiGHS on all 150 random problems, 67 unsatisfiable. Explanations average 2.37 of 6 atoms and all 67 are minimal in this sample: removing any explanation atom makes it satisfiable. Not a general theorem (a row can carry unnecessary bounds), but typical for small problems.
Reluplex. General simplex can be extended with nonlinear constraints. Reluplex (Katz et al., 2017) adds ReLU constraint : let simplex temporarily violate the relationship between and , repair it using specialized pivots and, only if a ReLU resists, branch on its two phases (active or inactive) as DPLL(T) would. They verified properties of prototype ACAS Xu drone-collision-avoidance networks, reportedly an order of magnitude larger than earlier methods reached.
Bit-vectors: bit-blasting
Bit-vector theory models machine integers: -bit vectors with arithmetic modulo (bvadd, bvmul, bvudiv), bitwise operations, shifts, and unsigned (bvult) and two’s-complement signed (bvslt) comparisons. It is the theory of low-level software verification and symbolic execution in lesson 15, exactly reproducing overflow.
Bit-blasting reduces it to SAT: each -bit vector becomes Boolean variables, each operator its hardware circuit, and each gate a few clauses via the Tseitin transformation: fresh variable per gate and clauses for (three), (three) or (four). An -bit adder chains full adders each with and : linear size. A full shift-add multiplier has AND gates for partial products and adders (the cell’s low--bit-only version saves half the AND gates): quadratic size. Unsigned division is encoded using multiplication and addition, for (ensuring does not overflow), inheriting that size.
import random
class Circuito:
"""Bit-blasting con la transformación de Tseitin: cada puerta es una variable nueva y unas pocas cláusulas."""
def __init__(self):
self.n, self.cls = 0, []
def var(self):
self.n += 1
return self.n
def AND(self, a, b):
x = self.var(); self.cls += [[-x, a], [-x, b], [x, -a, -b]]; return x
def OR(self, a, b):
x = self.var(); self.cls += [[x, -a], [x, -b], [-x, a, b]]; return x
def XOR(self, a, b):
x = self.var(); self.cls += [[-x, a, b], [-x, -a, -b], [x, -a, b], [x, a, -b]]; return x
def entrada(self, w):
return [self.var() for _ in range(w)]
def suma(self, A, B, c=None):
"""Sumador de acarreo en cascada, módulo 2^w. Con c = None el bit 0 es un semisumador."""
S = []
for i, (a, b) in enumerate(zip(A, B)):
t = self.XOR(a, b)
if c is None:
S.append(t); c = self.AND(a, b)
else:
S.append(self.XOR(t, c))
if i + 1 < len(A): # el acarreo del último bit se descarta (módulo 2^w)
c = self.OR(self.AND(a, b), self.AND(t, c))
return S
def producto(self, A, B):
"""Multiplicador de sumas desplazadas, módulo 2^w: w² puertas AND y w − 1 sumadores."""
w = len(A)
acc = [self.AND(A[i], B[0]) for i in range(w)]
for j in range(1, w):
fila = [self.AND(A[i - j], B[j]) for i in range(j, w)]
acc = acc[:j] + self.suma(acc[j:], fila)
return acc
def distintos(self, X, Y):
"""Cláusula «algún bit difiere» (el inglete, miter, de dos circuitos)."""
d = [self.XOR(x, y) for x, y in zip(X, Y)]
self.cls.append(d)
def cuenta(op, w):
c = Circuito(); A, B = c.entrada(w), c.entrada(w)
(c.suma if op == "suma" else c.producto)(A, B)
return c.n - 2 * w, len(c.cls)
print("variables auxiliares y cláusulas de Tseitin, módulo 2^w:")
for w in (8, 16, 32, 64):
va, ca = cuenta("suma", w); vm, cm = cuenta("producto", w)
print(f" w = {w:2d} suma: {va:5d} aux, {ca:6d} cláusulas producto: {vm:6d} aux, {cm:7d} cláusulas")
def comprueba(op, w, pruebas, rnd):
"""Fija las entradas con cláusulas unitarias y lee la salida del modelo (con el CDCL del laboratorio 2)."""
for _ in range(pruebas):
c = Circuito(); A, B = c.entrada(w), c.entrada(w)
S = (c.suma if op == "suma" else c.producto)(A, B)
x, y = rnd.randrange(2 ** w), rnd.randrange(2 ** w)
unit = [[v if (x >> i) & 1 else -v] for i, v in enumerate(A)] + [[v if (y >> i) & 1 else -v] for i, v in enumerate(B)]
s = CDCL(c.n, c.cls + unit); assert s.solve()
z = sum(1 << i for i, v in enumerate(S) if s.val[v] == 1)
esperado = (x + y if op == "suma" else x * y) % 2 ** w
assert z == esperado, (op, x, y, z, esperado)
assert s.stats["decisions"] == 0, "con las entradas fijadas, la propagación unitaria basta"
return True
rnd = random.Random(0)
print("suma de 16 bits correcta en 20 pruebas:", comprueba("suma", 16, 20, rnd))
print("producto de 8 bits correcto en 20 pruebas:", comprueba("producto", 8, 20, rnd))At 32 bits addition uses 525 clauses and multiplication 9436, eighteen times more; at 64 bits the ratio is 37 (1069 versus 39,324). Both checks fix inputs with unit clauses, determining outputs by unit propagation alone (zero decisions): Tseitin circuit encoding propagates well forward.
But size is not multiplication’s real problem. Forward with fixed inputs is all propagation. Backward (which inputs give this output?) or between two multipliers, SAT must search, and multipliers are among its hardest inputs. The next cell proves addition and multiplication commutative for every pair of -bit inputs: construct the miter of and , CNF saying “some output differs”, unsatisfiable iff they match, and count CaDiCaL conflicts.
from pysat.solvers import Solver
def inglete(op, w):
"""CNF de «existen x, y de w bits con op(x, y) != op(y, x)»: insatisfacible si op es conmutativa."""
c = Circuito(); A, B = c.entrada(w), c.entrada(w)
f = c.suma if op == "suma" else c.producto
c.distintos(f(A, B), f(B, A))
return c
print("conmutatividad por bit-blasting: conflictos de CaDiCaL hasta probar que el inglete es insatisfacible")
previo = None
for w in (4, 5, 6, 7): # añade 8 y 9 en local: el producto sigue multiplicándose
fila = []
for op in ("suma", "producto"):
c = inglete(op, w)
with Solver(name="cadical153", bootstrap_with=c.cls) as s:
r = s.solve(); conf = s.accum_stats()["conflicts"]
assert r is False
fila.append((conf, len(c.cls)))
(cs, ns), (cp, np_) = fila
crece = f" (x{cp / previo:.1f} respecto a w - 1)" if previo else ""
print(f" w = {w}: suma {cs:5d} conflictos ({ns:4d} cláusulas) producto {cp:6d} conflictos ({np_:5d} cláusulas){crece}")
previo = cpAddition conflicts grow slowly, roughly proportional to . For multiplication they multiply by 3 to 5 per added bit, as the last column shows (the cell stops at to keep browser runtime to seconds; add 8 and 9 locally to see it continue): exponential growth for a property a human proves in one line. SAT multiplier verification is a known hard problem motivating specialized techniques, such as combining SAT with computational algebra on circuit polynomials (Kaufmann, Biere and Kauers, 2019). Thus bit-vector solvers do not blindly bit-blast: first simplify at word level (rewrites such as , constant propagation, bit extraction), and some lazily bit-blast only what is needed (Hadarean et al., 2014, compare both in CVC4).
Combining theories: Nelson–Oppen
Real formulas mix theories: uses EUF and arithmetic together. Nelson and Oppen (1979) gave the standard method for combining decision procedures.
Purification. Introduce fresh variables to separate each theory’s terms until each literal is pure, from one theory. becomes (EUF) and (arithmetic). Variables appearing in literals of both theories are shared, here .
Equality exchange. Each solver decides its part. If one theory implies equality between shared variables, it communicates it to the other. Repeat until a part is inconsistent (unsatisfiable) or nothing new propagates (satisfiable).
Stable infiniteness enters the soundness proof: both parts’ models must be glued into one, requiring universes of equal cardinality (modern proof by Tinelli and Harandi, 1996). Convexity determines cost. Linear real arithmetic and EUF are convex; integer arithmetic is not:
With added (and purified using , ), the formula is unsatisfiable in LIA plus EUF, yet neither part alone deduces a shared-variable equality. Split cases: if , EUF gives and conflict; if , likewise. Over reals the same formula is satisfiable with , checked by Z3 in lab 3. Oppen (1980) studied cost: convex theories with polynomial procedures retain polynomial combination, while without convexity case splits can make it NP-hard.
Real solvers integrate combination into DPLL(T): shared-variable equalities are additional atoms CDCL can decide. Z3 uses model-based combination (de Moura and Bjørner, 2008): rather than derive every implied equality, expensive in arithmetic, each theory constructs a candidate model and reconciles only the equalities it assumes. If and have equal values in the arithmetic model, is proposed as a decision to other theories and, if incompatible, CDCL backtracks normally. Its authors describe this as Z3’s central design idea, recurring in arrays and quantifiers (Bjørner and de Moura, 2019).
The same pattern in constraint programming
DPLL(T)‘s architecture is not exclusive to SMT. In lesson 10 you used CP-SAT and its global constraints. A constraint-programming propagator does what a theory solver does: receives domain changes and infers others. Lazy clause generation (Ohrimenko, Stuckey and Codish, 2009) completes the analogy:
- Domains use Boolean literals of order and direct encodings, and , created on demand.
- Each time a propagator prunes a value, it explains this with a clause over those literals. For example, ‘s propagator inferring from records reason .
- SAT treats reasons normally: analyzes conflicts, learns nogoods and backjumps.
This is exactly T-Propagate with explanations, one propagator per constraint rather than one solver per theory. OR-Tools CP-SAT follows this pattern: its authors describe a constraint solver built on SAT with lazy clause generation plus simplex (Perron, Didier and Gay, 2023). A global constraint such as NoOverlap or Cumulative is judged by its explanation quality like a theory solver.
Z3’s design
Z3 (de Moura and Bjørner, 2008) combines everything above:
- A DPLL(T) core with modern CDCL.
- An E-graph: congruence closure shared across theories, maintaining term classes as a common blackboard. Theory solvers attach to its nodes.
- Theory solvers: arithmetic (general simplex with branching and cuts for integers), bit-vectors (bit-blasting after word-level simplification), arrays, data types and others.
- Model-based combination.
- For quantifiers, E-matching (instantiate using E-graph terms) and MBQI (instantiate guided by a candidate model), studied in lesson 14.
- Tactics: composable formula transformations (
simplify,solve-eqs,bit-blast,tseitin-cnf…) selecting a problem-specific strategy. Declaring logic withSolverFor("QF_BV")selects a prepared strategy.
Lab 3: first steps with Z3
The first cell solves familiar problems with Z3: machine integers, reals versus integers, lab 2’s job shop in QF_IDL, and bit-blasting three 32-bit operations, counting clauses with Z3 tactics.
import itertools, random, time
from z3 import *
print("z3", get_version_string())
# 1. Enteros matemáticos frente a enteros de máquina
x = Int("x")
print("Int: ", end=" "); prove(x + 1 > x)
b = BitVec("b", 32)
print("BitVec 32: ", end=" "); prove(b + 1 > b) # > es la comparación con signo
n = BitVec("n", 32)
s = Solver()
s.add(UGT(n, 0), ULT(n * 4, n)) # n * 4 da la vuelta: tamaño de reserva que se queda corto
print("¿n * 4 < n sin signo?", s.check(), "con n =", s.model()[n], "y n * 4 =", s.model().eval(n * 4))
# 2. Reales frente a enteros: la misma fórmula, dos teorías
for Srt, nombre in ((Real, "Real"), (Int, "Int")):
y = Srt("y")
s = Solver(); s.add(2 * y == 1)
print(f"2y = 1 sobre {nombre}: {s.check()}", s.model() if s.check() == sat else "")
r = Real("r"); s = Solver(); s.add(r > 0, r < 1); s.check(); print("0 < r < 1:", s.model())
# 3. El job shop del laboratorio 2 en QF_IDL
def jobshop(n_jobs, n_mach, seed, dmax=9):
rnd = random.Random(seed); jobs = []
for j in range(n_jobs):
orden = list(range(n_mach)); rnd.shuffle(orden)
jobs.append([(m, rnd.randint(1, dmax)) for m in orden])
return jobs
jobs = jobshop(5, 5, seed=2)
def modelo_js(s, M):
S = {(j, k): Int(f"s_{j}_{k}") for j, job in enumerate(jobs) for k in range(len(job))}
for (j, k), v in S.items():
s.add(v >= 0)
if k + 1 < len(jobs[j]): s.add(S[(j, k + 1)] - v >= jobs[j][k][1])
else: s.add(v + jobs[j][k][1] <= M)
for a, c in itertools.combinations(S, 2):
(ma, da), (mc, dc) = jobs[a[0]][a[1]], jobs[c[0]][c[1]]
if ma == mc: s.add(Or(S[c] - S[a] >= da, S[a] - S[c] >= dc))
return S
for M in (53, 54):
s = SolverFor("QF_IDL"); modelo_js(s, M)
t0 = time.perf_counter(); r = s.check(); t = time.perf_counter() - t0
st = s.statistics()
print(f"job shop 5x5, M = {M}: {r}; conflictos {st.get_key_value('conflicts') if 'conflicts' in st.keys() else '-'}, "
f"decisiones {st.get_key_value('decisions') if 'decisions' in st.keys() else '-'}")
o = Optimize(); Mk = Int("M"); S = modelo_js(o, Mk); o.minimize(Mk); o.check()
print("Optimize: makespan mínimo", o.model()[Mk])
# 4. Bit-blasting dentro de Z3: cuántas cláusulas cuesta cada operación de 32 bits
p, q, c = BitVecs("p q c", 32)
for nombre, f in (("p + q == c", p + q == c), ("p * q == c", p * q == c), ("p / q == c (udiv)", UDiv(p, q) == c)):
g = Goal(); g.add(f)
cnf = Then("simplify", "bit-blast", "tseitin-cnf")(g)[0]
print(f"{nombre:20s} -> {len(cnf):6d} cláusulas")npm run lab and open the connection link.What to inspect:
x + 1 > xis valid overIntand false on 32-bit vectors: counterexample is the largest signed integer, whose successor wraps negative. Themalloc(n * 4)overflow question is answered: with ,n * 4equals 1431655760 in 32 bits, less thann. This defensive use finds a value breaking a size check before someone else does.- is satisfiable over reals () and unsatisfiable over integers: theory changes the answer.
- The job shop matches your DPLL(T): 53 unsatisfiable, 54 satisfiable, and
Optimizeconfirms 54 as minimum. Its conflicts (28 for ) lie between your solver with theory propagation (5) and without (55); exact figures depend on Z3 version and heuristics. - Z3 tactics count 445 clauses for 32-bit addition, 8213 for multiplication and 19,174 for unsigned division: the same scale as your bit-blasting (525 and 9436), with some simplification.
The second cell moves to EUF, theory combination, nonlinear arithmetic and SMT-LIB.
from z3 import *
# 5. Funciones no interpretadas: la validación de traducciones del laboratorio 1
V = DeclareSort("V")
mul, add, sub = (Function(f, V, V, V) for f in ("mul", "add", "sub"))
a, b, c = Consts("a b c", V)
t1, t2, t3, t4 = mul(a, b), mul(a, b), add(mul(a, b), c), add(mul(a, b), c)
r_fuente = sub(t3, t4)
print("CSE en EUF: ", end=" "); prove(r_fuente == sub(add(mul(a, b), c), add(mul(a, b), c)))
print("add conmutada (EUF): ", end=" "); prove(add(mul(a, b), c) == add(c, mul(a, b)))
ai, bi, ci = Ints("a b c")
print("add conmutada (Int): ", end=" "); prove(ai * bi + ci == ci + ai * bi)
# 6. Convexidad: la misma fórmula sobre enteros y sobre reales
for nombre, Srt, dom in (("Int", Int, IntSort()), ("Real", Real, RealSort())):
f = Function("f", dom, IntSort())
x = Srt("x")
s = Solver(); s.add(1 <= x, x <= 2, f(x) != f(1), f(x) != f(2))
r = s.check()
print(f"1 <= x <= 2, f(x) != f(1), f(x) != f(2) sobre {nombre}: {r}", s.model()[x] if r == sat else "")
# 6 bis. Nelson-Oppen en acción: aritmética lineal real y funciones no interpretadas
x1, x2, x3 = Reals("x1 x2 x3")
g = Function("g", RealSort(), RealSort())
s = Solver()
s.add(x2 >= x1, x1 - x3 >= x2, x3 >= 0, g(g(x1) - g(x2)) != g(x3))
print("x2 >= x1, x1 - x3 >= x2, x3 >= 0, g(g(x1) - g(x2)) != g(x3):", s.check())
# 7. Aritmética no lineal entera: indecidible en general; Z3 puede rendirse
x, y, z = Ints("x y z")
s = Solver(); s.set("timeout", 2000)
s.add(x**3 + y**3 + z**3 == 33)
r = s.check()
print("x³ + y³ + z³ = 33 con 2 s:", r, "| motivo:", s.reason_unknown() if r == unknown else "")
# 8. Lógicas SMT-LIB y el texto que ve el solver
s = SolverFor("QF_LIA")
p, q = Ints("p q")
s.add(p + 2 * q >= 3, p - q <= 1, Or(p < 0, q > 5))
print(s.sexpr())
print(s.check(), s.model())
st = s.statistics()
print({k: st.get_key_value(k) for k in st.keys() if k in ("conflicts", "decisions", "arith-pivots", "arith-make-feasible", "propagations")})npm run lab and open the connection link.- With
DeclareSortandFunction, Z3 matches your congruence closure: validates CSE but not commutingadd, with a counterexample whereaddis an arbitrary table. OverInt, commutativity is proved. - The nonconvex formula (, , ) is unsatisfiable over
Intand satisfiable overRealwith . The back-and-forth equality example is unsatisfiable as derived by hand. - over integers returns
unknownwith a 2-second limit: nonlinear integer arithmetic is undecidable (Hilbert’s tenth problem) and Z3 can only apply heuristics. This particular equation has a solution using 16-digit numbers, found by Booker in 2019 with a dedicated search. s.sexpr()prints the problem in SMT-LIB, the same text seen at the start, and statistics show simplex calls (arith-make-feasible).
Common mistakes
Exercises
Step 1 of 4. For the forward direction, assume model and cycle with weights . What do you do?
congruence_closure(igualdades, desigualdades, terminos), returning True if the conjunction of equalities and inequalities is EUF-satisfiable and False otherwise. Terms are strings (constants) or tuples (f, arg1, ..., argk); igualdades and desigualdades list term pairs, and terminos lists extra terms (which do not change the answer but must be accepted). Remember to register every subterm: congruence acts on them. Tests compare with brute force over all subterm partitions.def congruence_closure(igualdades, desigualdades, terminos):
"""True si la conjunción es satisfacible en EUF."""
# 1. reúne todos los subtérminos de terminos, igualdades y desigualdades
# 2. union-find: une los dos lados de cada igualdad
# 3. repite hasta el punto fijo: dos aplicaciones con el mismo símbolo y argumentos en la misma clase se unen
# 4. comprueba las desigualdades
return Truelen * sizeof(T) with uint32_t cannot overflow; (2) a schedule with integer times and constraints such as ; (3) verify a loop over an integer array with arithmetic indices that calls an auxiliary function to abstract; (4) decide feasibility of rational-coefficient linear inequalities over real variables. Which logic assignment is appropriate?Summary
- A theory fixes meaning of some symbols; SMT-LIB organizes useful fragments into logics (
QF_UF,QF_IDL,QF_LIA,QF_LRA,QF_BV,QF_AUFLIA…). Choosing the right logic chooses the decision procedure. - Eager translation sends everything to SAT (bit-blasting, Ackermann); lazy abstraction makes atoms Boolean and consults theory. DPLL(T) integrates theory with CDCL: incremental assertions, explained conflicts and propagations entering 1-UIP analysis, and cheap backtracking.
- EUF is decided by congruence closure in with proof-forest explanations. Difference logic is a shortest-path problem: inconsistent iff a negative cycle exists, a minimal explanation; virtual-source distances form a model.
- Linear arithmetic uses Dutertre–de Moura general simplex: fixed tableau, changing bounds, Bland’s rule, row explanations, for strict inequalities and branch-and-cut for integers. Backtracking does not pivot.
- Bit-vectors are bit-blasted: addition has linear size, multiplication quadratic and especially difficult for SAT.
- Nelson–Oppen combines disjoint-signature stably infinite theories by equality propagation; nonconvexity needs case splits. Z3 uses model guidance.
- Lazy clause generation is the same pattern in constraint programming, at CP-SAT’s core.