Structure and constraint programming: trees, global constraints and CP-SAT
Constraint-graph structure determines complexity: tree CSPs are solved without backtracking and general difficulty grows exponentially only in treewidth. This lesson studies efficiently filtered global constraints, conflict-directed backjumping, min-conflicts local search, symmetry breaking and professional modeling with CP-SAT.
After this lesson you can
- Solve tree-structured CSPs without backtracking and exploit cycle cutsets, bucket elimination and tree decompositions.
- Implement alldifferent filtering using bipartite matchings.
- Explain conflict-directed backjumping and nogood learning as precursors to CDCL.
- Apply min-conflicts and recognize CSPs on which local search fails.
- Model scheduling problems in CP-SAT with native constraints and symmetry breaking.
Before you start
Motivation: structure decides
Deciding whether a finite-domain CSP has a solution is NP-complete: graph coloring is already NP-complete with three colors. Yet constraint solvers schedule real workshops, timetables and shifts daily, and in this lesson CP-SAT proves in seconds the optimum of a workshop that resisted for twenty-six years. There is no contradiction. NP-completeness concerns the worst case over all instances; real instances have structure, and the previous lesson (modeling, propagation and backtracking) exploited part of it: arc consistency prunes domains and maintaining consistency during search avoids dead branches.
This lesson goes further in four directions, all sharing the idea that blind search is the last resort.
- Graph shape. If the constraint graph is a tree, two linear passes solve the problem without backtracking. Otherwise exact inference cost grows exponentially in one number, treewidth, rather than the number of variables.
- Meaningful constraints. Saying “these 16 squares are all different” in one constraint permits reasoning over all 16 together using bipartite matchings, pruning what 120 binary inequalities miss.
- Learning from failure. When a branch dies, the cause is often far away. Jumping directly to it and remembering it is the idea that became CDCL in SAT.
- Giving up systematic search. For large problems with many solutions, repairing a complete assignment is remarkably effective: a million queens in about 50 moves.
The lesson closes with practice: how to model a scheduling problem in Google’s OR-Tools CP-SAT solver and read its output.
Tree CSPs: two passes and no backtracking
Start with the most favorable case. A binary CSP is tree-structured if its constraint graph is a tree: connected and acyclic (equivalently, connected with edges, or with a unique path between each pair of vertices; review tree characterizations). Choose a root and order variables so each follows its parent, for example breadth-first. That order is a linear extension of the “ancestor of” partial order.
This is half of arc consistency: support is required only forward, from each variable in later ones. One backward pass achieves it: for , revise each earlier neighbor of against , deleting from values unsupported in . When is revised against , ‘s domain is already final, because only domains of variables earlier than the one processed change. Thus one pass suffices.
In a tree ordered from the root, each non-root variable has exactly one earlier neighbor, its parent. Pass 1 revises each parent against each child, leaves to root; pass 2 assigns root to leaves, choosing any value compatible with the parent’s for each variable.
The proof is a three-line induction you will reconstruct in the final guided exercise. Complexity follows by counting: there are edges and each revision compares at most pairs. Compared with exhaustive search’s , the tree makes an exponential problem linear.
With root order, pass 1 prunes 6 values and pass 2 assigns all 8 variables with zero dead ends. The figure’s two experiments show that both theorem assumptions matter:
- Order. From leaves, each parent has two earlier neighbors, its children, already assigned by its turn. Arc consistency guarantees each child’s value has support in the parent, but not that two children have a common support. This instance has 7 dead ends. Freuder gives the minimal example: two-coloring a binary tree is arc-consistent, but if postorder colors two siblings differently, the parent has no possible color.
- Cycles. Edge gives two earlier neighbors, and . The directional pass still prunes but no longer suffices: 3 dead ends.
Freuder stated the result generally. An order’s width is the maximum, over variables, of their number of earlier neighbors; graph width is the minimum over all orders. His theorem 1 says that if the strong-consistency level exceeds order width, search in that order never backtracks; theorem 3 says a connected graph has width 1 if and only if it is a tree. On a tree, arc consistency (strong level-2 consistency) suffices. Width would need strong consistency at level , and achieving it may add constraints increasing width: bucket elimination, two sections below, resolves this vicious circle.
Implementation from scratch
The cell implements both passes and compares them with simple backtracking on 400 random trees with varied relations. It then measures checks on increasingly large trees.
import random, time
def revise(D, x, y, ok):
"""Quita de D[x] los valores sin apoyo en D[y]; ok(a, b) dice si x = a, y = b es compatible."""
quitados = [a for a in D[x] if not any(ok(a, b) for b in D[y])]
for a in quitados:
D[x].remove(a)
return len(quitados)
def resolver_arbol(n, dominios, padre, rel):
"""CSP binario cuyo grafo es un árbol con raíz 0. padre[j] es el padre de j (padre[0] = None) y
rel[j](a, b) la restricción entre padre[j] = a y j = b. Devuelve (asignación o None, comprobaciones)."""
D = [list(d) for d in dominios]
orden = [0] # orden topológico desde la raíz (BFS)
for x in orden:
orden += [j for j in range(n) if padre[j] == x]
comprobaciones = 0
for j in reversed(orden[1:]): # pasada 1: de las hojas a la raíz
p = padre[j]
comprobaciones += len(D[p]) * len(D[j])
revise(D, p, j, rel[j])
if not D[p]:
return None, comprobaciones
valor = {}
for x in orden: # pasada 2: de la raíz a las hojas, sin retroceso
p = padre[x]
candidatos = [b for b in D[x] if p is None or rel[x](valor[p], b)]
comprobaciones += len(D[x])
assert candidatos, "callejón sin salida: el teorema dice que es imposible"
valor[x] = candidatos[0]
return valor, comprobaciones
def satisfacible(n, dominios, restr):
"""Backtracking simple, para contrastar. restr: lista de (u, v, ok)."""
val = {}
def bt(i):
if i == n:
return True
for a in dominios[i]:
val[i] = a
if all(ok(val[u], val[v]) for u, v, ok in restr if max(u, v) == i):
if bt(i + 1):
return True
del val[i]
return False
return bt(0)
RELS = [lambda a, b: a < b, lambda a, b: a != b, lambda a, b: abs(a - b) == 1,
lambda a, b: (a + b) % 3 == 0, lambda a, b: a >= b + 2]
rnd = random.Random(0)
n, d, total, sat = 12, 4, 400, 0
for _ in range(total):
padre = [None] + [rnd.randrange(j) for j in range(1, n)] # árbol aleatorio con raíz 0
rel = [None] + [rnd.choice(RELS) for _ in range(1, n)]
dominios = [rnd.sample(range(d), rnd.randint(2, d)) for _ in range(n)]
sol, _ = resolver_arbol(n, dominios, padre, rel)
restr = [(padre[j], j, rel[j]) for j in range(1, n)]
assert (sol is not None) == satisfacible(n, dominios, restr)
if sol is not None:
sat += 1
assert all(r(sol[u], sol[v]) for u, v, r in restr) and all(sol[x] in dominios[x] for x in range(n))
print(f"{total} árboles aleatorios con n = {n}, d = {d}: {sat} satisfacibles; el algoritmo de dos pasadas")
print("coincide siempre con el backtracking y nunca encuentra un callejón sin salida")
# coste lineal en n: árboles aleatorios de ≠ con d = 10 (cada padre entre los 3 anteriores)
for n in [10, 100, 1000, 10000]:
padre = [None] + [rnd.randrange(max(0, j - 3), j) for j in range(1, n)]
rel = [None] + [lambda a, b: a != b] * (n - 1)
dominios = [list(range(10))] * n
sol, comp = resolver_arbol(n, dominios, padre, rel)
print(f"n = {n:5d}: {comp:8d} comprobaciones = {comp / n:.1f} por variable")The pass-2 assert never fires, and the 96 satisfiable instances of 400 are exactly those backtracking declares satisfiable. Checks per variable stabilize at : cost is linear in , as the theorem promises.
Cycle-cutset conditioning
Almost no real problem is a tree, but many are nearly trees. Russell and Norvig’s Australia map is the textbook example: fixing South Australia’s color, which touches every other mainland region, leaves a chain.
If , there are at most cutset assignments and each forest costs , totaling : exponential only in cutset size. Finding the minimum cutset is the NP-hard feedback vertex set problem, but any cutset works and greedy heuristics give reasonable ones.
import itertools, random
def corte_de_ciclos(n, aristas):
"""Heurística voraz: quita vértices de grado máximo del 2-núcleo hasta que no quedan ciclos."""
vivos, corte = set(range(n)), []
while True:
nucleo = set(vivos) # 2-núcleo: borrar repetidamente vértices de grado <= 1
cambio = True
while cambio:
cambio = False
for v in list(nucleo):
if sum(1 for a, b in aristas if v in (a, b) and {a, b} <= nucleo) <= 1:
nucleo.discard(v); cambio = True
if not nucleo:
return corte # lo que queda es un bosque
v = max(nucleo, key=lambda v: sum(1 for a, b in aristas if v in (a, b) and {a, b} <= nucleo))
corte.append(v); vivos.discard(v)
def resolver_bosque(vars_, D, aristas):
"""Dos pasadas en cada árbol del bosque inducido por vars_ (restricciones ≠)."""
vecinos = {v: [] for v in vars_}
for a, b in aristas:
if a in vecinos and b in vecinos:
vecinos[a].append(b); vecinos[b].append(a)
D = {v: list(D[v]) for v in vars_}
valor, comprob = {}, 0
vistos = set()
for r in vars_:
if r in vistos:
continue
orden, padre = [r], {r: None}; vistos.add(r)
for x in orden:
for y in vecinos[x]:
if y not in vistos:
vistos.add(y); padre[y] = x; orden.append(y)
for j in reversed(orden[1:]): # pasada 1
p = padre[j]; comprob += len(D[p]) * len(D[j])
D[p] = [a for a in D[p] if any(a != b for b in D[j])]
if not D[p]:
return None, comprob
for x in orden: # pasada 2
p = padre[x]
valor[x] = next(b for b in D[x] if p is None or b != valor[p])
return valor, comprob
def condicionamiento(n, D, aristas, corte):
"""Recorre TODAS las asignaciones del corte y cuenta cuántas se extienden a una solución."""
resto = [v for v in range(n) if v not in corte]
vec = {v: set() for v in range(n)}
for u, v in aristas:
vec[u].add(v); vec[v].add(u)
probadas = comprob = buenas = 0
primera = None
for asign in itertools.product(*[D[c] for c in corte]):
a = dict(zip(corte, asign))
if any(a[u] == a[v] for u, v in aristas if u in a and v in a):
continue # el corte ya es inconsistente
probadas += 1
D2 = {v: [x for x in D[v] if all(x != a[u] for u in vec[v] if u in a)] for v in resto}
if any(not D2[v] for v in resto):
continue
sol, c = resolver_bosque(resto, D2, aristas)
comprob += c
if sol is not None:
buenas += 1
primera = primera or {**a, **sol}
return primera, probadas, buenas, comprob
rnd = random.Random(7)
n, d = 40, 3
aristas = [(rnd.randrange(j), j) for j in range(1, n)] # un árbol aleatorio...
while len(aristas) < n - 1 + 12: # ...más 12 aristas que cierran ciclos
a, b = sorted(rnd.sample(range(n), 2))
if (a, b) not in aristas:
aristas.append((a, b))
D = {v: list(range(d)) for v in range(n)}
for v in rnd.sample(range(n), 15): # algunos dominios recortados
D[v] = rnd.sample(range(d), 2)
corte = corte_de_ciclos(n, aristas)
sol, probadas, buenas, comprob = condicionamiento(n, D, aristas, sorted(corte))
c = len(corte)
print(f"n = {n}, d = {d}, {len(aristas)} aristas; corte de ciclos de tamaño c = {c}: {sorted(corte)}")
print(f"asignaciones del corte: d^c = {d**c}; consistentes entre sí: {probadas}; se extienden a solución: {buenas}")
print("solución válida:", sol is not None and all(sol[u] != sol[v] for u, v in aristas) and all(sol[v] in D[v] for v in range(n)))
print(f"comprobaciones: {comprob}; cota d^c (n - c) d^2 = {d**c * (n - c) * d**2}; d^n = {d**n:.2e}")A graph of 40 vertices with 12 independent cycles reduces to a cutset of 5 variables. Of its assignments, 108 are mutually consistent and 76 extend to a solution, and total checks (9194) are well below the 76 545 bound because many domains are reduced. The contrast with is the point: the exponential part depends on how many vertices must be removed to break cycles, not problem size.
Bucket elimination and treewidth
Cycle cutsets pay even when cycles are far apart. The alternative is to infer rather than condition: eliminate variables one by one, summarizing everything an eliminated variable imposed on neighbors in a new constraint.
Bucket elimination
Fix an order and place each constraint in the bucket of its latest variable. Process buckets from to . ’s bucket contains constraints on and earlier variables; join them in a relation over their joint scope and project out : the resulting relation on contains exactly those combinations admitting some value of compatible with the whole bucket. The new relation goes to its latest variable’s bucket. This is Dechter and Pearl’s (1987) adaptive consistency, presented by Dechter (1999) as bucket elimination, the same scheme used to marginalize graphical models (variable elimination).
Afterward, assign from to looking only at each variable’s bucket constraints, with no dead ends: by construction every surviving earlier-value combination admits an extension. What changes from trees is cost. Projecting makes the new constraint connect all its earlier neighbors, equivalent to adding edges among them in the graph. The resulting graph, with those fill edges, is the order’s induced graph.
Proof
The scope of ‘s bucket consists of and its earlier neighbors in the induced graph, hence . Computing the join enumerates at most tuples of and checks each bucket constraint; each constraint, original or generated, is in exactly one bucket, and there are at most , giving the time bound. Each generated relation has scope size at most and thus at most tuples, and one is generated per bucket. Correctness follows from projection: a tuple of enters the new relation iff it extends to satisfying all bucket constraints, so after processing ‘s bucket the problem has the same solutions, restricted to , as the original.
∎Thus complexity depends on order, and the best possible order yields a graph parameter:
Two classical facts connect the pieces. First, treewidth equals minimum induced width across all orders: an elimination order yields bags forming a decomposition, and conversely eliminating decomposition leaves gives an order of the same width. Second, trees with at least one edge are exactly connected graphs of treewidth 1, where bucket elimination is the directional pass above. Dechter and Pearl’s (1989) tree clustering uses the decomposition directly: each bag becomes a metavariable whose domain is the bag’s consistent tuples (at most ), and the metavariable CSP is a tree solved by two passes.
The order remains to be chosen. Computing treewidth is NP-hard (Arnborg, Corneil and Proskurowski, 1987), although for fixed one can decide in linear time whether it is at most (Bodlaender, 1996), with constants making it impractical except for very small . Practice uses greedy orders:
- min-degree: eliminate the variable with fewest remaining neighbors first.
- min-fill: eliminate the variable whose removal creates fewest fill edges first.
On grid no order goes below 3, its treewidth: grid has treewidth , so exact inference in grid-structured models (images, the Ising model) is infeasible except on narrow grids. On the trap graph, min-degree with ties broken by smallest index gives width 4 and min-fill optimal width 3. Heuristic width is always an upper bound on treewidth, never necessarily its value; the exact number requires exponential search.
import itertools, random
def eliminacion_por_cubos(dominios, restricciones, orden):
"""Consistencia adaptativa (Dechter y Pearl): restricciones = lista de (ámbito, conjunto de tuplas
permitidas). Procesa los cubos del último al primero de `orden`. Devuelve los cubos (o None si es
insatisfacible) y estadísticas de coste."""
pos = {x: k for k, x in enumerate(orden)}
cubos = {x: [] for x in orden}
for alc, tuplas in restricciones:
cubos[max(alc, key=pos.get)].append((tuple(alc), tuplas))
anchura = enumeradas = mayor_tabla = 0
for x in reversed(orden):
if not cubos[x]:
continue
ambito = sorted({v for alc, _ in cubos[x] for v in alc}, key=pos.get) # x es el último
anchura = max(anchura, len(ambito) - 1)
resto = ambito[:-1]
nueva = set()
for t in itertools.product(*[dominios[v] for v in ambito]): # unión (join)...
enumeradas += 1
a = dict(zip(ambito, t))
if all(tuple(a[v] for v in alc) in tuplas for alc, tuplas in cubos[x]):
nueva.add(t[:-1]) # ...y proyección: se olvida x
if not nueva:
return None, anchura, enumeradas, mayor_tabla
if resto:
mayor_tabla = max(mayor_tabla, len(nueva))
cubos[max(resto, key=pos.get)].append((tuple(resto), nueva))
return cubos, anchura, enumeradas, mayor_tabla
def asignar(cubos, dominios, orden):
"""Pasada hacia delante: cada variable solo mira las restricciones de su cubo. Cuenta callejones."""
a, callejones = {}, 0
for x in orden:
buenos = [v for v in dominios[x]
if all(tuple({**a, x: v}[u] for u in alc) in tuplas for alc, tuplas in cubos[x])]
if not buenos:
callejones += 1
return None, callejones
a[x] = buenos[0]
return a, callejones
# CSP aleatorio sobre una rejilla 4x4, d = 3, cada restricción permite 6 de los 9 pares
rnd = random.Random(1)
k, d = 4, 3
V = [(i, j) for i in range(k) for j in range(k)]
dominios = {v: list(range(d)) for v in V}
aristas = [((i, j), (i, j + 1)) for i in range(k) for j in range(k - 1)] + \
[((i, j), (i + 1, j)) for i in range(k - 1) for j in range(k)]
restricciones = [((a, b), set(rnd.sample(list(itertools.product(range(d), repeat=2)), 6))) for a, b in aristas]
ordenes = {
"por filas": V,
"en zigzag": [(i, j) for j in range(k) for i in (range(k) if j % 2 == 0 else reversed(range(k)))],
"aleatorio": rnd.sample(V, len(V)),
"centro primero": sorted(V, key=lambda v: (min(v[0], k - 1 - v[0]) + min(v[1], k - 1 - v[1]), v), reverse=True),
}
for nombre, orden in ordenes.items():
cubos, w, enum, tabla = eliminacion_por_cubos(dominios, restricciones, orden)
if cubos is None:
print(f"{nombre:18s} anchura inducida {w}: insatisfacible"); continue
sol, callejones = asignar(cubos, dominios, orden)
ok = all((sol[a], sol[b]) in t for (a, b), t in restricciones)
print(f"{nombre:18s} anchura inducida {w}: {enum:6d} tuplas enumeradas, mayor tabla nueva {tabla:3d}, "
f"solución correcta: {ok}, callejones: {callejones}")All four orders find a correct solution without a dead end, as the theorem guarantees; the price differs. Row and zigzag orders have induced width 4, the treewidth of grid , and enumerate 2658 tuples; random and center-first reach width 6, enumerate 6006 and 4926 tuples and generate tables up to 369 and 324 tuples versus 72 and 81. With the difference is a factor of 2; each unit of width multiplies by , so with and widths 4 versus 6 it would be on the order of 100. Treewidth as a general parameter of exact inference returns with treewidth and the junction tree in probabilistic models.
Global constraints: alldifferent and matchings
Change perspective. So far constraints were binary. Many natural constraints concern many variables at once: “all different,” “at every instant total consumption is within capacity,” “ is the -th element of this list.” They can be decomposed into binaries, but information is lost.
The canonical example is . Its decomposition is the constraints , and arc consistency on a binary prunes only when one variable has a singleton domain: if , every value of has support in . Now consider and . No binary prunes anything, but and share between them, so . With four variables in the problem is impossible (the pigeonhole principle), which binaries do not detect without search. The general argument is Hall’s theorem: if a set of variables has a domain union of size exactly (a Hall set), those values are reserved for them.
The value graph
Régin (1994) turned this intuition into an exact algorithm. The constraint’s value graph is bipartite, with variables on one side, values on the other, and an edge for each . An assignment satisfying alldifferent is exactly a matching covering all variables. Hence:
Proof
The first equivalence is the definition: a support of is an assignment with all values distinct, i.e. a matching covering variables and containing . For the second, let be another matching covering variables and containing . Symmetric difference is a disjoint union of cycles and paths alternating edges of and (each vertex touches at most one edge of each). Since and cover the same variables, no path can end at a variable touching only one, so paths have even length and endpoints are values, one free in and one free in . Edge lies on an alternating cycle or one such path. In the directed graph, traversing an alternation goes from value to variable along a free edge and variable to value along one in , so an alternating cycle is directed (endpoints are in the same strongly connected component) and an even path from a free value is a directed path from that value. Conversely, if lies on a directed cycle or path beginning at a free value, swapping edges and free edges along it gives another matching still covering variables and containing . This is Berge’s lemma, cited by Régin as property 1.
∎The algorithm follows: a maximum matching with Hopcroft-Karp in , with edges; if it does not cover the variables, the constraint fails. Otherwise Tarjan’s strongly connected components and a search from free values, both in , classify every edge at once. Prune those not in , a cycle, or a path from a free value. Régin bounds the worst case of maintaining consistency while deleting edges one at a time by for a constraint over variables with domains of size , versus generic generalized consistency enumerating tuples.
In Régin’s example, form a Hall set over : the matching covers them with edges forming an alternating cycle, and all their values survive. Conversely and , are on no cycle or path from free value 7, so are pruned: , and remain. In the sudoku row filtering chains several Hall sets ( over , then over ) and fixes , and without search, while binary inequalities prune nothing.
Two more global constraints
- cumulative: tasks with starts , durations and consumption of a resource with capacity ; at every instant, total consumption of active tasks is at most . It generalizes NoOverlap (capacity 1, consumption 1) and is filtered using edge-finding and energetic reasoning, deducing that a task cannot start before a time because energy available in a window is insufficient. It was introduced in CHIP (Aggoun and Beldiceanu, 1993).
- element: , indexing a table with a variable. Filtering keeps in only indices with , and in only with . This expresses choice-dependent costs such as setup time between jobs.
Lab: Régin filtering with networkx
The implementation uses networkx for Hopcroft-Karp matching and strongly connected components, and is checked against brute force.
import itertools, random
import networkx as nx
from networkx.algorithms import bipartite
def regin(dominios):
"""Filtrado de alldifferent (Régin, 1994). dominios: dict variable -> conjunto de valores.
Devuelve el conjunto de pares (x, v) que no están en ningún emparejamiento que cubra las variables,
o None si no existe tal emparejamiento (la restricción falla)."""
X = [("x", x) for x in dominios]
G = nx.Graph()
G.add_nodes_from(X)
G.add_edges_from((("x", x), ("v", v)) for x, D in dominios.items() for v in D)
M = bipartite.hopcroft_karp_matching(G, top_nodes=X)
if any(x not in M for x in X):
return None
# grafo orientado: emparejadas de variable a valor, libres de valor a variable
R = nx.DiGraph()
R.add_nodes_from(G)
for x, D in dominios.items():
for v in D:
if M[("x", x)] == ("v", v):
R.add_edge(("x", x), ("v", v))
else:
R.add_edge(("v", v), ("x", x))
comp = {u: k for k, c in enumerate(nx.strongly_connected_components(R)) for u in c}
libres = [u for u in G if u[0] == "v" and u not in M]
alcanzable = set(libres)
for u in libres:
alcanzable |= nx.descendants(R, u)
return {(x, v) for x, D in dominios.items() for v in D
if M[("x", x)] != ("v", v) # no está en el emparejamiento,
and comp[("x", x)] != comp[("v", v)] # ni en un ciclo alternante par,
and ("v", v) not in alcanzable} # ni en un camino par desde un valor libre
def regin_fuerza_bruta(dominios):
xs = list(dominios)
soporte = {(x, t[i]) for t in itertools.product(*[sorted(dominios[x]) for x in xs])
if len(set(t)) == len(t) for i, x in enumerate(xs)}
if not soporte:
return None
return {(x, v) for x in xs for v in dominios[x]} - soporte
ejemplo = {1: {1, 2}, 2: {2, 3}, 3: {1, 3}, 4: {2, 4}, 5: {3, 4, 5, 6}, 6: {6, 7}} # figura 2 de Régin
print("podados en el ejemplo de Régin:", sorted(regin(ejemplo)))
rnd = random.Random(0)
for _ in range(300):
n = rnd.randint(2, 6)
dom = {x: set(rnd.sample(range(7), rnd.randint(1, 4))) for x in range(n)}
assert regin(dom) == regin_fuerza_bruta(dom), dom
print("300 casos aleatorios: coincide con la fuerza bruta")Now integrate it into a consistency-maintaining solver: the previous lesson’s MAC scheme with minimum remaining values first (MRV) and two interchangeable propagators. The binary propagator enforces arc consistency, which for removes a fixed cell’s value from all its peers. The alldifferent propagator runs regin on each affected row, column or box to a fixed point. The sudokus are generated by permuting a valid pattern and emptying 150 of 256 cells.
import random, time
def unidades_sudoku(B):
N = B * B
filas = [[(r, c) for c in range(N)] for r in range(N)]
cols = [[(r, c) for r in range(N)] for c in range(N)]
cajas = [[(br * B + i, bc * B + j) for i in range(B) for j in range(B)] for br in range(B) for bc in range(B)]
U = filas + cols + cajas
de = {}
for k, u in enumerate(U):
for x in u:
de.setdefault(x, []).append(k)
return U, de
def propagar(D, U, de, modo, pendientes):
"""modo 'ne': consistencia de arco sobre las ≠ binarias (solo actúan los dominios unitarios).
modo 'alldiff': filtrado de Régin en cada unidad afectada. pendientes: celdas que han cambiado."""
if modo == "ne":
pila = [x for x in pendientes if len(D[x]) == 1]
while pila:
x = pila.pop()
(a,) = D[x]
for k in de[x]:
for y in U[k]:
if y != x and a in D[y]:
D[y] = D[y] - {a}
if not D[y]:
return False
if len(D[y]) == 1:
pila.append(y)
return True
cola = {k for x in pendientes for k in de[x]}
while cola:
k = cola.pop()
podar = regin({x: D[x] for x in U[k]})
if podar is None:
return False
for x, a in podar:
D[x] = D[x] - {a}
cola.update(de[x])
return True
def mac(D, U, de, modo, stats, limite):
stats["nodos"] += 1
if stats["nodos"] > limite:
return None
libres = [x for x in D if len(D[x]) > 1]
if not libres:
return D
x = min(libres, key=lambda x: len(D[x])) # MRV
for a in sorted(D[x]):
D2 = dict(D); D2[x] = {a}
if propagar(D2, U, de, modo, [x]):
r = mac(D2, U, de, modo, stats, limite)
if r is not None:
return r
return None
def generar(B, huecos, semilla):
"""Sudoku resuelto por permutaciones de un patrón válido, con `huecos` celdas vaciadas al azar."""
N, rnd = B * B, random.Random(semilla)
base = lambda r, c: (B * (r % B) + r // B + c) % N
digs = rnd.sample(range(N), N)
filas = [b * B + i for b in rnd.sample(range(B), B) for i in rnd.sample(range(B), B)]
cols = [b * B + i for b in rnd.sample(range(B), B) for i in rnd.sample(range(B), B)]
sol = {(r, c): digs[base(filas[r], cols[c])] for r in range(N) for c in range(N)}
vaciar = set(rnd.sample(sorted(sol), huecos))
return {x: v for x, v in sol.items() if x not in vaciar}
def resolver(B, pistas, modo, limite=2000):
N = B * B
U, de = unidades_sudoku(B)
D = {(r, c): {pistas[(r, c)]} if (r, c) in pistas else set(range(N)) for r in range(N) for c in range(N)}
stats = {"nodos": 0}
t = time.perf_counter()
r = mac(D, U, de, modo, stats, limite) if propagar(D, U, de, modo, list(D)) else None
return r, stats["nodos"], time.perf_counter() - t
for semilla in [0, 2]:
pistas = generar(4, 150, semilla)
(ok1, n1, t1), (ok2, n2, t2) = [(r is not None, nodos, dt) for r, nodos, dt in
(resolver(4, pistas, modo) for modo in ["ne", "alldiff"])]
print(f"16x16 con {256 - 150} pistas (semilla {semilla}): ≠ binarias: "
f"{'resuelto en ' + str(n1) + ' nodos' if ok1 else 'sin resolver al llegar a 2000 nodos'}; "
f"alldifferent: {'resuelto' if ok2 else 'sin resolver'} en {n2} nodos; "
f"coste por nodo alldifferent / ≠: {(t2 / n2) / (t1 / n1):.0f}x")In the first sudoku binary inequalities exhaust the 2000-node limit without solving it while alldifferent solves it in 21; in the second, 698 nodes versus 18. Each alldifferent node is far more expensive (the cell prints a ratio of two orders of magnitude, machine-dependent), but the search tree shrinks even more, and in practice the latter decides: node count for MAC with weak propagation has a heavy tail, and an early poor choice can cost thousands of nodes strong propagation never opens.
Conflict-directed backjumping and nogoods
Chronological backtracking returns to the immediately preceding variable at a dead end. If the cause lies much earlier, it repeatedly traverses the unrelated intervening part of the tree: thrashing.
The update makes chained jumps correct too. If fails, assignments to variables in suffice to leave without values: no skipped variable can fix it, so skipping them loses no solutions. On reaching and exhausting its values too, blame is shared between causes of ‘s failures and ‘s, hence they are inherited. That partial assignment, , is a nogood: a combination belonging to no solution. CBJ uses it once and forgets it. Nogood learning stores it as a new constraint so search does not stumble over it in another branch.
import random, statistics
def buscar(n, D, ok, saltar):
"""Backtracking (saltar=False) o retroceso dirigido por conflictos de Prosser (saltar=True) para un CSP
binario con orden fijo 0..n-1. ok[(h, i)](a, b) con h < i. Devuelve (solución o None, nodos, primer nogood)."""
val, conf = [None] * n, [set() for _ in range(n)]
restantes = [list(D[0])] + [None] * (n - 1)
i, nodos, nogood = 0, 0, None
while 0 <= i < n:
consistente = False
while restantes[i] and not consistente:
val[i] = restantes[i].pop(0); nodos += 1
consistente = True
for h in range(i): # comprobar contra las anteriores, en orden
if (h, i) in ok and not ok[(h, i)](val[h], val[i]):
conf[i].add(h); consistente = False; break
if consistente:
i += 1
if i < n:
restantes[i], conf[i] = list(D[i]), set()
continue
if not saltar: # cronológico: a la anterior
h = i - 1
else:
if not conf[i]:
return None, nodos, nogood
h = max(conf[i]) # la más profunda del conjunto conflicto
if nogood is None and h < i - 1:
nogood = {x: val[x] for x in sorted(conf[i])}
if h >= 0:
conf[h] |= conf[i] - {h} # hereda las causas del fallo
for j in range(h + 1, i + 1):
restantes[j], conf[j] = None, set()
i = h
return (list(val) if i == n else None), nodos, nogood
# 1) un conflicto lejano: x0 = 0 deja sin valores a x11, y entre medias una cadena de ≠ que no tiene que ver
n = 12
D = [[0, 1, 2]] * 11 + [[0]]
ok = {(i, i + 1): (lambda a, b: a != b) for i in range(1, 10)}
ok[(0, 11)] = lambda a, b: a != b
for saltar in (False, True):
sol, nodos, nogood = buscar(n, D, ok, saltar)
print(f"{'dirigido por conflictos' if saltar else 'cronológico':24s} nodos = {nodos:5d} solución x0 = {sol[0]}"
+ (f" primer salto aprende el nogood {nogood}" if saltar else ""))
# 2) CSP aleatorios: n = 15, d = 5, densidad 0.25 (probabilidad de cada restricción), estrechez 0.4 (pares prohibidos)
def aleatorio(n, d, p1, p2, rnd):
ok = {}
for h in range(n):
for i in range(h + 1, n):
if rnd.random() < p1:
prohibidos = set(rnd.sample([(a, b) for a in range(d) for b in range(d)], round(p2 * d * d)))
ok[(h, i)] = (lambda P: lambda a, b: (a, b) not in P)(prohibidos)
return [list(range(d))] * n, ok
rnd = random.Random(4)
cocientes, sat = [], 0
for _ in range(25):
D, ok = aleatorio(15, 5, 0.25, 0.4, rnd)
s1, n1, _ = buscar(15, D, ok, False)
s2, n2, _ = buscar(15, D, ok, True)
assert (s1 is None) == (s2 is None)
sat += s1 is not None
cocientes.append(n1 / n2)
print(f"25 CSP aleatorios ({sat} satisfacibles): nodos cronológico / dirigido por conflictos: "
f"mediana {statistics.median(cocientes):.1f}, mínimo {min(cocientes):.1f}, máximo {max(cocientes):.1f}")In the constructed example chronological backtracking needs 6156 nodes: with it traverses every coloring of chain (there are ), each dying at . CBJ needs 34: the first failure has conflict set , jumps straight there and learns nogood . In the 25 random CSPs, all satisfiable, median savings are a factor of 22.8, with cases showing no gain (1.0) and others over a thousand: gain depends on distant conflicts, which random instances may or may not have.
Local search: min-conflicts
All previous methods are systematic: if a solution exists they find it, otherwise they prove none exists. The local search alternative starts with a complete assignment violating constraints and repairs it.
Minton and colleagues extracted it from Johnston and Adorf’s GDS neural network for scheduling Hubble Space Telescope observations: ten to thirty thousand observations per year, with orbital, power and stray-light constraints, and an earlier classical system that reportedly would have needed more than three weeks to schedule one. Their most famous result is different. With a greedy initial assignment placing each queen in order in its column’s square with fewest conflicts with earlier queens, mean repairs to solve queens were 57.0, 55.6, 48.8, 48.5, 52.8 and 48.3 for (their table 1, one hundred runs per size), and they solved one million queens in under four minutes on a SPARCstation 1. Backtracking with the most-constrained-variable heuristic, under the same move limit, failed to finish in 19 % of runs with .
The initial assignment explains the constant step count. Greedy leaves very few queens in conflict (Minton et al. measured a mean of 3.1 at to 12.8 at ), and -queens solutions are so numerous and spread out that one is always a few repairs away. Random initialization, by contrast, starts with on the order of queens in conflict and steps grow linearly with . Each repair costs because the column’s rows must be inspected, and incremental row and diagonal counters make each query . With greedy initialization, repair costs on the order of operations total: linear, as Minton et al. observe. The expensive part becomes greedy initialization itself, which brute-force checks rows per column: .
Sparse 3-coloring is the opposite. The graph has a planted coloring, so it is satisfiable, but solutions are scarce and separated by barriers. With mean degree 3 and no noise, the method quickly descends to a strict local minimum with a few conflicting vertices: each already has its unique conflict-minimizing color, no step changes anything and it remains forever (the figure detects this and stops). With mean degree 4 it sometimes reaches a strict minimum, other times wanders a plateau of sideways moves without improvement for 20 000 steps. Minton et al. warn that the method is “less effective” coloring sparsely connected graphs, and their analysis shows error probability grows with distance to a solution. Some noise (with probability , a random value instead of the best) permits escape. This is the idea behind WalkSAT and simulated annealing.
Lab: min-conflicts with incremental structures
import random, time
import numpy as np
class Reinas:
"""n reinas, la reina i en la columna i y la fila q[i]. Contadores incrementales: cuántas reinas hay en
cada fila y en cada diagonal (r + i) y antidiagonal (r - i + n - 1). Conflictos de la casilla (r, i):
filas[r] + d1[r + i] + d2[r - i + n - 1], todo O(1). Se guardan como listas (acceso escalar rápido)
y como arrays de NumPy (barridos de una columna entera en O(n) vectorizado)."""
def __init__(self, n, semilla, voraz=True, muestras=256):
self.n, self.rnd = n, random.Random(semilla)
self.F, self.D1, self.D2 = np.zeros(n, np.int32), np.zeros(2 * n, np.int32), np.zeros(2 * n, np.int32)
self.q = np.zeros(n, np.int64)
f, d1, d2 = [0] * n, [0] * (2 * n), [0] * (2 * n)
self.barridos = 0
for i in range(n):
o, r = n - 1 - i, -1
if voraz: # voraz de Minton et al.: fila de menos conflictos con las ya colocadas, empates al azar
for _ in range(muestras): # la primera fila libre muestreada es uniforme entre las libres
x = self.rnd.randrange(n)
if f[x] == 0 and d1[x + i] == 0 and d2[x + o] == 0:
r = x; break
if r < 0: # no hay (o no la encontramos): barrido completo
self.barridos += 1
r = self.mejor_fila(i)
else:
r = self.rnd.randrange(n)
f[r] += 1; d1[r + i] += 1; d2[r + o] += 1
self.poner(i, r)
def poner(self, i, r):
self.q[i] = r; self.F[r] += 1; self.D1[r + i] += 1; self.D2[r - i + self.n - 1] += 1
def quitar(self, i):
r = self.q[i]; self.F[r] -= 1; self.D1[r + i] -= 1; self.D2[r - i + self.n - 1] -= 1
def mejor_fila(self, i):
o = self.n - 1 - i
c = self.F + self.D1[i:i + self.n] + self.D2[o:o + self.n]
cand = np.flatnonzero(c == c.min())
return int(cand[self.rnd.randrange(len(cand))])
def en_conflicto(self):
i = np.arange(self.n)
return np.flatnonzero(self.F[self.q] + self.D1[self.q + i] + self.D2[self.q - i + self.n - 1] > 3)
def min_conflicts(R, max_pasos=100_000):
inicial = len(R.en_conflicto())
for paso in range(max_pasos):
malas = R.en_conflicto()
if len(malas) == 0:
return paso, inicial
i = int(malas[R.rnd.randrange(len(malas))]) # una reina en conflicto al azar
R.quitar(i)
R.poner(i, R.mejor_fila(i)) # a la fila de menos conflictos
return None, inicial
for n in [10, 100, 1000, 10000]:
filas = []
for semilla in range(5):
pasos, ini = min_conflicts(Reinas(n, semilla))
filas.append((pasos, ini))
al = [min_conflicts(Reinas(n, s, voraz=False)) for s in range(3)] if n <= 1000 else None
print(f"n = {n:6d}: voraz -> pasos {[p for p, _ in filas]}, en conflicto al empezar {[c for _, c in filas]}"
+ (f"\n aleatoria -> pasos {[p for p, _ in al]}, en conflicto al empezar {[c for _, c in al]}" if al else ""))Two implementation details. Exact greedy traverses rows per column, total, which at already gives operations. Here rows are sampled randomly until a conflict-free one is found; only if 256 attempts fail is the full traversal performed. This is not an approximation: the first free row found in uniform sampling is uniform among free rows, so its distribution exactly matches greedy with random tie-breaking. Worst case remains quadratic, but only the last columns, when few free rows remain, need a full scan (2.4 % in the -queens cell). The number of conflicting queens is recomputed each step with NumPy, in vectorized , which with a few hundred steps does not warrant incremental maintenance.
With greedy initialization steps stay between 0 and 121 at all sizes, with 0 to 16 initially conflicting queens. With random initialization they rise from around a hundred at to about 700 at . Now the million scale, reduced to to fit in the browser:
t = time.perf_counter()
R = Reinas(100_000, semilla=0)
t_ini = time.perf_counter() - t
pasos, ini = min_conflicts(R)
print(f"n = 100 000: {ini} reinas en conflicto tras la voraz ({R.barridos} columnas necesitaron el barrido completo)")
print(f"resuelto en {pasos} reparaciones; la inicialización se llevó el {100 * t_ini / (time.perf_counter() - t):.0f} % del tiempo")
print("comprobación independiente: ¿solución?", len(set(R.q)) == R.n
and len(set(R.q + np.arange(R.n))) == R.n and len(set(R.q - np.arange(R.n))) == R.n)Six queens in conflict after greedy initialization, 2418 columns fully scanned and 37 repairs solve one hundred thousand queens. Almost all time goes into initialization: search itself is trivial when starting so close.
Symmetries and symmetry breaking
Many CSPs have symmetries: transformations mapping solutions to solutions and nonsolutions to nonsolutions. For queens, the square’s 8 symmetries (90°, 180° and 270° rotations, four reflections and identity); in coloring, color permutations; in a timetable, swapping two identical rooms. An unaware solver explores each space region as many times as the group size and pays that entire factor when proving unsatisfiability.
Proof
Every orbit is finite and lexicographic order total, so it has a minimum . For every , is in the same orbit, hence : the minimum satisfies all constraints and any subset. If another solution in the orbit satisfies them all, since for some , we have , and by minimality .
∎Using the whole group can be expensive (some have exponentially many elements), so practice breaks a subset: no orbit is lost, only some symmetry remains. For interchangeable values such as colors, standard value precedence says color cannot be used before in variable order. Two alternatives to static constraints are dynamic symmetry breaking during search (such as SBDS, adding constraints on backtracking), or letting the solver detect symmetry, as CP-SAT presolve does.
def reinas(n, extra=None, valores=None, primera=False):
"""Backtracking columna a columna. extra(q) poda asignaciones parciales; valores: orden de las filas.
Devuelve (soluciones, nodos)."""
valores = valores or list(range(n))
sols, nodos, q = [], 0, []
usadas, d1, d2 = set(), set(), set()
def bt(i):
nonlocal nodos
if i == n:
sols.append(tuple(q)); return primera
for r in valores:
if r in usadas or r + i in d1 or r - i in d2:
continue
nodos += 1
q.append(r)
if extra is None or extra(q, n):
usadas.add(r); d1.add(r + i); d2.add(r - i)
if bt(i + 1):
return True
usadas.discard(r); d1.discard(r + i); d2.discard(r - i)
q.pop()
return False
bt(0)
return sols, nodos
def simetrias(n):
"""Las 8 simetrías del cuadrado como funciones sobre casillas (columna, fila)."""
m = n - 1
return [lambda c, r: (c, r), lambda c, r: (r, m - c), lambda c, r: (m - c, m - r), lambda c, r: (m - r, c),
lambda c, r: (m - c, r), lambda c, r: (c, m - r), lambda c, r: (r, c), lambda c, r: (m - r, m - c)]
def aplicar(g, q):
casillas = sorted(g(c, r) for c, r in enumerate(q)) # vuelve a una reina por columna
return tuple(r for _, r in casillas)
n = 8
sols, _ = reinas(n)
G = simetrias(n)
orbitas = {min(aplicar(g, s) for g in G) for s in sols}
lider = [s for s in sols if all(s <= aplicar(g, s) for g in G[1:])] # restricciones lex-leader
print(f"{n} reinas: {len(sols)} soluciones, {len(orbitas)} órbitas, {len(lider)} cumplen lex-leader;",
"una por órbita:", set(lider) == orbitas)
# dos simetrías rotas con su restricción lex-leader, que solo mira la primera componente distinta:
# espejo horizontal r -> n-1-r: q[0] < n-1-q[0] (se decide en la primera columna)
# espejo vertical c -> n-1-c: q[0] < q[n-1] (no se decide hasta la última)
horizontal = lambda q, n: q[0] < n - 1 - q[0]
vertical = lambda q, n: len(q) < n or q[0] < q[-1]
n = 10
todas, nod = reinas(n)
for nombre, f in [("q[0] < n-1-q[0]", horizontal), ("q[0] < q[n-1]", vertical)]:
rotas, nod_r = reinas(n, extra=f)
print(f"n = {n}: {len(todas)} soluciones en {nod} nodos; con {nombre}: {len(rotas)} soluciones en {nod_r} nodos")
# la trampa: la heurística de valores y la rotura tiran en sentidos opuestos (primera solución)
print("nodos hasta la primera solución (sin romper / con q[0] < q[n-1]):")
for n in [8, 10, 12]:
fila = []
for nombre, vals in [("filas ascendentes", None), ("filas descendentes", list(range(n - 1, -1, -1)))]:
_, a = reinas(n, valores=vals, primera=True)
_, b = reinas(n, extra=vertical, valores=vals, primera=True)
fila.append(f"{nombre} {a} / {b}")
print(f" n = {n}: " + "; ".join(fila))The 92 eight-queens solutions form 12 orbits, and exactly 12 satisfy all seven lex-leader constraints, one per orbit as the theorem says. Two symmetries broken separately on the ten-board show when breaking helps. Both retain 362 of 724 solutions, but horizontal reflection is decided in the first column and halves nodes (17 774 versus 35 538), whereas is checked only on a full board and saves no nodes. The last part is the trap: with rows descending, search favors solutions with large , exactly those excluded, and with it goes from 261 to 63 886 nodes to the first solution. Symmetry breaking should select as orbit representative the one the heuristic would find first.
Professional modeling with CP-SAT
CP-SAT, Google’s OR-Tools constraint solver, is a reference tool for these problems. Internally it combines constraint-programming propagation, SAT-solver clause learning (constraints are explained with clauses to learn from conflicts, called lazy clause generation), linear relaxations with cuts like an integer-programming solver, and a portfolio of parallel strategies. How SAT and theories fit together appears in the SMT lesson (DPLL(T)). Here the external view matters: the model.
Fisher and Thompson’s workshop
Job-shop scheduling is the classic benchmark: jobs, each a sequence of operations with a machine and duration; each machine processes one operation at a time without interruption, and the goal is minimum makespan, the last operation’s finish time. Fisher and Thompson’s (1963) ft06 instance has 6 jobs and 6 machines. In CP-SAT each operation is an interval variable: an object with start, duration and end known to satisfy , acted on by scheduling constraints such as NoOverlap or Cumulative with specialized propagators.
from ortools.sat.python import cp_model
# ft06 (Fisher y Thompson, 1963), formato de la OR-Library: por trabajo, pares (máquina, duración)
FT06 = """2 1 0 3 1 6 3 7 5 3 4 6
1 8 2 5 4 10 5 10 0 10 3 4
2 5 3 4 5 8 0 9 1 1 4 7
1 5 0 5 2 5 3 3 4 8 5 9
2 9 1 3 4 5 5 4 0 3 3 1
1 3 3 3 5 9 0 10 4 4 2 1"""
def leer(texto):
trabajos = []
for linea in texto.strip().splitlines():
v = list(map(int, linea.split()))
trabajos.append([(v[2 * k], v[2 * k + 1]) for k in range(len(v) // 2)])
return trabajos
def modelo_intervalos(trabajos, simetrias=()):
m = cp_model.CpModel()
H = sum(p for ops in trabajos for _, p in ops) # horizonte: todo en serie
ini, fin, por_maquina = {}, {}, {}
for j, ops in enumerate(trabajos):
for k, (maq, p) in enumerate(ops):
ini[j, k] = m.new_int_var(0, H, f"ini_{j}_{k}")
fin[j, k] = m.new_int_var(0, H, f"fin_{j}_{k}")
iv = m.new_interval_var(ini[j, k], p, fin[j, k], f"op_{j}_{k}") # impone fin = ini + p
por_maquina.setdefault(maq, []).append(iv)
if k > 0:
m.add(ini[j, k] >= fin[j, k - 1]) # orden dentro del trabajo
for ivs in por_maquina.values():
m.add_no_overlap(ivs) # una operación a la vez por máquina
makespan = m.new_int_var(0, H, "makespan")
m.add_max_equality(makespan, [fin[j, len(ops) - 1] for j, ops in enumerate(trabajos)])
for a, b in simetrias: # trabajos idénticos: a empieza antes que b
m.add(ini[a, 0] <= ini[b, 0])
m.minimize(makespan)
return m, ini
def resolver(m, hilos=1, limite=60.0, semilla=0, **params):
s = cp_model.CpSolver()
s.parameters.num_workers = hilos
s.parameters.max_time_in_seconds = limite
s.parameters.random_seed = semilla
for k, v in params.items():
setattr(s.parameters, k, v)
estado = s.solve(m)
return s, s.status_name(estado)
ft06 = leer(FT06)
m, ini = modelo_intervalos(ft06)
s, estado = resolver(m)
print(f"ft06: {estado}, makespan = {s.objective_value:.0f}, cota demostrada = {s.best_objective_bound:.0f}")
print(f"ramas = {s.num_branches}, conflictos = {s.num_conflicts}")
print("inicios por trabajo:", [[s.value(ini[j, k]) for k in range(6)] for j in range(6)])
print("\n".join(l for l in s.response_stats().splitlines() if l.split(":")[0].strip() in
("status", "objective", "best_bound", "booleans", "conflicts", "branches", "propagations", "walltime")))npm run lab and open the connection link.Read the output as follows. OPTIMAL means the solver has a solution and proof that none is better: the proven lower bound (best_bound) equals objective 55, ft06’s known optimum. If time runs out earlier, status is FEASIBLE and the distance between objective and bound is what you know about your solution, the gap. Branches and conflicts measure search: 214 branches and 3 conflicts show ft06 is trivial for this solver. booleans counts internal Boolean variables: 85, although the model declares none, because the solver creates them to reason with clauses over integers. To follow a long run, log_search_progress = True prints presolve, each new solution and bound evolution.
Dispatch rules build a schedule in one pass without search, and the best of five (most work remaining first, MWKR) gives 67, 22 % above optimum; the worst gives 96. Even the optimum misses the lower bound of 47, job J2’s duration: the gap from 47 to 55 is what search must prove.
Native constraints versus big-M
Those coming from integer linear programming may write the disjunction “either before , or before ” using Boolean and large constant : and . The cell compares this with the interval model on ft10, the instance Fisher and Thompson published in 1963 whose optimum, 930, was not proven until 1989 (Carlier and Pinson), and also runs it through HiGHS, an integer-programming solver, via SciPy.
import time
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds
FT10 = """0 29 1 78 2 9 3 36 4 49 5 11 6 62 7 56 8 44 9 21
0 43 2 90 4 75 9 11 3 69 1 28 6 46 5 46 7 72 8 30
1 91 0 85 3 39 2 74 8 90 5 10 7 12 6 89 9 45 4 33
1 81 2 95 0 71 4 99 6 9 8 52 7 85 3 98 9 22 5 43
2 14 0 6 1 22 5 61 3 26 4 69 8 21 7 49 9 72 6 53
2 84 1 2 5 52 3 95 8 48 9 72 0 47 6 65 4 6 7 25
1 46 0 37 3 61 2 13 6 32 5 21 9 32 8 89 7 30 4 55
2 31 0 86 1 46 5 74 4 32 6 88 8 19 9 48 7 36 3 79
0 76 1 69 3 76 5 51 2 85 9 11 6 40 7 89 4 26 8 74
1 85 0 13 2 61 6 7 8 64 9 76 5 47 3 52 4 90 7 45"""
ft10 = leer(FT10)
def modelo_big_m(trabajos):
"""Lo que no hay que hacer: una booleana por par de operaciones de la misma máquina y dos desigualdades
con una constante grande H que desactiva la que no toca."""
m = cp_model.CpModel()
H = sum(p for ops in trabajos for _, p in ops)
ini, ops_m = {}, {}
for j, ops in enumerate(trabajos):
for k, (maq, p) in enumerate(ops):
ini[j, k] = m.new_int_var(0, H, "")
ops_m.setdefault(maq, []).append((j, k, p))
if k > 0:
m.add(ini[j, k] >= ini[j, k - 1] + ops[k - 1][1])
for L in ops_m.values():
for a in range(len(L)):
for b in range(a + 1, len(L)):
(j1, k1, p1), (j2, k2, p2) = L[a], L[b]
y = m.new_bool_var("") # y = 1: la primera va antes
m.add(ini[j1, k1] + p1 <= ini[j2, k2] + H * (1 - y))
m.add(ini[j2, k2] + p2 <= ini[j1, k1] + H * y)
mk = m.new_int_var(0, H, "makespan")
for j, ops in enumerate(trabajos):
m.add(mk >= ini[j, len(ops) - 1] + ops[-1][1])
m.minimize(mk)
return m
print("ft10: makespan óptimo conocido 930")
for hilos in (8, 1):
for nombre, mod in [("intervalos + NoOverlap", modelo_intervalos(ft10)[0]), ("big-M", modelo_big_m(ft10))]:
s, estado = resolver(mod, hilos=hilos, limite=60)
print(f" {hilos} hilo(s), {nombre:22s}: {estado:8s} makespan {s.objective_value:.0f}, cota {s.best_objective_bound:.0f}, "
f"ramas {s.num_branches}, {s.wall_time:.1f} s")
print("restricciones de cada modelo:", len(modelo_intervalos(ft10)[0].proto.constraints), "frente a",
len(modelo_big_m(ft10).proto.constraints))
# ¿qué hace el presolve con el big-M? Lo dice el registro de CP-SAT
s = cp_model.CpSolver()
s.parameters.num_workers = 1
s.parameters.log_search_progress = True
s.parameters.log_to_stdout = False
lineas = []
s.log_callback = lineas.append
s.solve(modelo_big_m(ft06))
print("registro del presolve con ft06 en big-M:")
print("\n".join(" " + l.strip() for l in "\n".join(lineas).splitlines() if "enforcement literal" in l or "num_relations" in l))
def big_m_highs(trabajos, limite):
"""El mismo big-M en un resolutor MIP (HiGHS, a través de SciPy)."""
ops = [(j, k, maq, p) for j, o in enumerate(trabajos) for k, (maq, p) in enumerate(o)]
pares = [(a, b) for a in range(len(ops)) for b in range(a + 1, len(ops)) if ops[a][2] == ops[b][2]]
nS, nY = len(ops), len(pares)
MK = nS + nY
nv = MK + 1
H = sum(o[3] for o in ops)
idx = {(j, k): i for i, (j, k, _, _) in enumerate(ops)}
filas, lb = [], []
def fila(coefs, cota):
r = np.zeros(nv)
for i, c in coefs:
r[i] += c
filas.append(r)
lb.append(cota)
for j, o in enumerate(trabajos):
for k in range(1, len(o)):
fila([(idx[j, k], 1), (idx[j, k - 1], -1)], o[k - 1][1])
fila([(MK, 1), (idx[j, len(o) - 1], -1)], o[-1][1])
for t, (a, b) in enumerate(pares):
fila([(b, 1), (a, -1), (nS + t, -H)], ops[a][3] - H) # y = 1: a antes que b
fila([(a, 1), (b, -1), (nS + t, H)], ops[b][3]) # y = 0: b antes que a
A = np.array(filas)
c = np.zeros(nv)
c[MK] = 1
cotas = Bounds(np.zeros(nv), np.r_[np.full(nS, H), np.ones(nY), H])
integ = np.r_[np.zeros(nS), np.ones(nY), 0]
relajacion = milp(c, constraints=LinearConstraint(A, lb, np.inf), bounds=cotas)
t = time.perf_counter()
r = milp(c, constraints=LinearConstraint(A, lb, np.inf), integrality=integ, bounds=cotas, options={"time_limit": limite})
return relajacion.fun, r, time.perf_counter() - t
for nombre, tr in [("ft06", ft06), ("ft10", ft10)]:
lp, r, dt = big_m_highs(tr, 60)
print(f"HiGHS con big-M en {nombre}: relajación lineal {lp:.0f}; {'óptimo' if r.status == 0 else 'límite de tiempo'}, "
f"mejor solución {r.fun:.0f}, cota {r.mip_dual_bound:.1f}, {r.mip_node_count} nodos, {dt:.1f} s")npm run lab and open the connection link.The result is more nuanced than textbook advice; read it all.
- Size. The interval model has 201 constraints (100 intervals, 90 precedences, 10 NoOverlap and the maximum); big-M has 1000, because each machine with 10 operations needs Booleans and 90 inequalities.
- CP-SAT undoes big-M. With 8 threads both models prove optimum 930 in seconds. With one thread, in this run big-M finishes before intervals, with fewer branches (130 394 versus 162 379). The log explains: for ft06 presolve applies “extracted enforcement literal” 180 times, once per big-M inequality (). It rewrites each as implication , the classical disjunctive model; thereafter single-thread search follows different paths depending on the starting model, sometimes better and sometimes worse. Repeat the cell with different seeds before drawing timing conclusions.
- An integer-programming solver does not undo it. HiGHS solves ft06 in 128 nodes, but on ft10 reaches the 60 s limit with solution 1046 and bound 742.8, far from 930. The linear relaxation gives 47 on ft06 and 655 on ft10, exactly the longest job’s duration: with and large both inequalities hold simultaneously, so the relaxation ignores machines entirely and bounds must come from branching.
The practical lesson is not “big-M is slow in CP-SAT,” which this cell disproves, but that the native constraint expresses the intent, occupies a fraction of the size, extends effortlessly (optional intervals, Cumulative, setup times), and does not depend on a particular solver’s presolve recognizing the trick.
Workshop symmetries
ft06 has no obvious symmetries, so the experiment uses a workshop with two identical copies of each job: swapping all operations of two copies transforms schedules into schedules. Break this with the simplest lex-leader constraint, “copy starts before ,” and compare with and without CP-SAT automatic symmetry detection (symmetry_level).
# Simetría: un taller con dos copias de cada trabajo de ft06. Intercambiar todas las operaciones de dos
# copias transforma calendarios en calendarios: la rompemos con «la copia a empieza antes que la b».
doble = ft06 + ft06
pares = [(j, j + 6) for j in range(6)]
for nombre, sims, nivel in [("sin romper", (), 2), ("con ini[a,0] <= ini[b,0]", pares, 2),
("sin romper, sin detección de simetrías", (), 0),
("con ini[a,0] <= ini[b,0], sin detección", pares, 0)]:
m, _ = modelo_intervalos(doble, simetrias=sims)
s, estado = resolver(m, hilos=1, limite=120, symmetry_level=nivel)
print(f"{nombre:42s}: {estado}, makespan {s.objective_value:.0f}, ramas {s.num_branches}, conflictos {s.num_conflicts}")npm run lab and open the connection link.All four variants prove the same optimum, 95. The breaking constraint reduces branches from 1703 to 901 and conflicts from 260 to 190. Disabling symmetry detection (symmetry_level = 0) changes nothing in this model, so the gain comes entirely from the explicit constraint. It is correct because the symmetry swaps two entire jobs: in each pair of symmetric schedules, one has copy starting no later than . Here would also work, because both copies start on the same machine and never simultaneously; in general is safe because a strict inequality would discard symmetry-fixed schedules.
Against custom backtracking
Finally, the comparison any honest lab asks for: a solver written from scratch. It is branch and bound over Giffler and Thompson’s (1960) active schedules, which always contain an optimum, using the simplest bound: what remains for each machine and job from when it becomes free.
import random, time
def bb_taller(trabajos, limite=3_000_000):
"""Nuestro backtracking: ramificación y poda sobre calendarios activos (Giffler y Thompson, 1960).
En cada nodo, la operación disponible de menor fin posible c* fija una máquina; se ramifica sobre las
operaciones de esa máquina que pueden empezar antes de c*. Cota: lo que le queda a cada máquina y a cada
trabajo desde el instante en que queda libre."""
nJ, M = len(trabajos), 1 + max(m for o in trabajos for m, _ in o)
rm0 = [sum(p for o in trabajos for m, p in o if m == k) for k in range(M)]
rj0 = [sum(p for _, p in o) for o in trabajos]
mejor, nodos = [sum(rj0) + 1], [0]
def rec(sig, lj, lm, rm, rj, mk):
nodos[0] += 1
if nodos[0] > limite:
return
if max([mk] + [lm[k] + rm[k] for k in range(M)] + [lj[j] + rj[j] for j in range(nJ)]) >= mejor[0]:
return
disp = [j for j in range(nJ) if sig[j] < len(trabajos[j])]
if not disp:
mejor[0] = mk
return
ini = lambda j: max(lj[j], lm[trabajos[j][sig[j]][0]])
js = min(disp, key=lambda j: (ini(j) + trabajos[j][sig[j]][1], j))
ms, cs = trabajos[js][sig[js]][0], ini(js) + trabajos[js][sig[js]][1]
for j in sorted((j for j in disp if trabajos[j][sig[j]][0] == ms and ini(j) < cs), key=ini):
m, p = trabajos[j][sig[j]]
s = ini(j)
sig2, lj2, lm2, rm2, rj2 = sig[:], lj[:], lm[:], rm[:], rj[:]
sig2[j] += 1
lj2[j] = lm2[m] = s + p
rm2[m] -= p
rj2[j] -= p
rec(sig2, lj2, lm2, rm2, rj2, max(mk, s + p))
rec([0] * nJ, [0] * nJ, [0] * M, rm0, rj0, 0)
return mejor[0], nodos[0], nodos[0] <= limite
rnd = random.Random(0)
instancias = [("ft06", ft06)] + [(f"aleatoria {n}x{n}", [[(m, rnd.randint(1, 99)) for m in rnd.sample(range(n), n)] for _ in range(n)])
for n in (6, 7, 8)]
for nombre, tr in instancias:
t = time.perf_counter()
mk, nodos, completo = bb_taller(tr)
dt = time.perf_counter() - t
s, estado = resolver(modelo_intervalos(tr)[0], hilos=8, limite=60)
print(f"{nombre:16s} backtracking propio: {'óptimo' if completo else 'sin terminar'} {mk} en {nodos} nodos ({dt:.1f} s) | "
f"CP-SAT: {estado} {s.objective_value:.0f} en {s.wall_time:.2f} s")npm run lab and open the connection link.On ft06 both reach 55, ours with 6814 nodes. In random instances with durations 1 to 99, our tree grows from 72 795 nodes with to 1 752 535 with , and with exhausts the three-million-node limit with a schedule of 766, while CP-SAT proves optimum 651 in a fraction of a second. The difference is not implementation (Python versus C++), which would give a constant factor, but reasoning: our bound considers each machine separately, while CP-SAT combines NoOverlap propagation, conflict learning and linear relaxations to prune trees ours must traverse.
Common mistakes
Exercises
Step 1 of 3. With which already assigned variables is constrained?
More than one answer may be correct.
More than one answer may be correct.
podar_alldiff(dominios): it receives a list of sets (each variable domain) and returns the set of pairs (i, v) such that value v in variable i's domain occurs in no assignment with all values distinct, or None if no such assignment exists. Do this without enumerating assignments: maximum matching by augmenting paths and Régin edge classification (alternating cycles and paths from free values). Do not use networkx. Tests compare with brute force.def podar_alldiff(dominios):
"""dominios: lista de conjuntos. Devuelve el conjunto de pares (i, v) que se podan, o None si no hay
ninguna asignación con todos los valores distintos."""
# 1) emparejamiento máximo (caminos de aumento); si no cubre todas las variables, devuelve None
# 2) grafo orientado: variable -> su valor emparejado; valor -> variables que lo tienen sin emparejar
# 3) una arista (i, v) fuera del emparejamiento sobrevive si v es alcanzable desde un valor libre,
# o si v es alcanzable desde la variable i (ciclo alternante)
return set()Summary
- A binary tree CSP is solved in : directional arc consistency from leaves to root, then root-to-leaf assignment without backtracking (Freuder). Order and acyclicity are essential.
- Cycle-cutset conditioning costs ; bucket elimination costs with the order’s induced width. Its minimum over orders is treewidth, NP-hard to compute; min-degree and min-fill give upper bounds only.
- Global constraints reason over many variables together. Alldifferent is arc-consistent iff each value-graph edge belongs to a matching covering variables; Régin checks with one matching and strongly connected components.
- Conflict-directed backjumping jumps to the deepest cause of failure and passes along remaining causes; saving causes as nogoods is the idea CDCL refines in SAT.
- Min-conflicts solves queens in nearly constant repairs thanks to greedy initialization and abundant solutions; sparse-solution problems need noise or restarts.
- Lex-leader constraints break symmetry while retaining one solution per orbit, and should align with the search heuristic.
- CP-SAT models with interval variables and native constraints; read status, objective, bound and gap. Big-M formulations are unnecessary when a global constraint exists.