Beyond state-space search: planning as SAT, GraphPlan, partial-order and HTN planning
Planning includes approaches beyond heuristic search. Study GraphPlan and mutual exclusions, planning as satisfiability with horizons and incremental SAT, partial-order planning with causal links, and hierarchical task networks, the dominant industry approach, ending with a map beyond classical planning.
After this lesson you can
- Build a planning graph with mutual exclusions and extract plans with GraphPlan.
- Encode planning as SAT with explanatory frame axioms and solve using incremental horizons.
- Build partial-order plans by resolving threats through promotion and demotion.
- Design HTN domains with alternative methods and assess their risks.
- Place temporal, numeric and nondeterministic extensions relative to the classical model.
Before you start
Motivation: a plan as an object, not a path
In the previous lesson a plan was a path through state space: start at the initial state, apply a STRIPS action, reach another state, and heuristic search guided by delete relaxation decides what to expand. This dominates classical planning competitions, but is not the only approach, and each alternative answers a question state search handles poorly.
- What can happen simultaneously? Two trucks delivering in different cities do not interfere. A state-space path serializes them and pays depth equal to all actions. GraphPlan and SAT encodings reason in steps containing multiple independent actions.
- What is impossible without search? Polynomial propagation can prove two facts cannot both hold at time 3 without enumerating one state. GraphPlan mutexes do this.
- Why commit early? If backup and patch download are independent, arbitrarily ordering them hides useful information from the executor. Partial-order plans order only what must be ordered.
- What if I already know how? A security operations center does not search from scratch for incident response: procedures say “contain, eradicate, recover” and how to do each. Hierarchical task networks (HTN) plan by refining that knowledge, dominating many real applications.
The lesson treats all four rigorously: definitions, the theorem justifying each, an executable from-scratch implementation and an interactive demonstration. It ends with a map beyond the classical model: time, numeric resources, nondeterminism and uncertainty.
GraphPlan: the planning graph
Blum and Furst introduced GraphPlan at IJCAI 1995 (journal version: Fast planning through planning graph analysis, 1997), with immediate impact: it solved in seconds problems contemporary planners did not finish. The idea builds forward, in polynomial time, a layered structure overapproximating what is reachable in steps and recording incompatible pairs. It then searches backward within that structure for a plan.
We use literals: an atom or its negation , allowing negative preconditions and goals as in Russell and Norvig. The initial state is closed-world (absent means false). Each literal has a persistence action (no-op) with precondition and effect , expressing that it remains unchanged.
Mutexes propagate: literal mutexes in create competing needs in , which in turn leave literals without consistent support. None requires search: each level checks pairs in polynomial time in literals and actions.
Russell and Norvig’s classic example is “having your cake and eating it”. The initial state is (and, closed-world, ), goal , with two actions: Eat, precondition and effects ; Bake, precondition and effect . Weld’s second “surprise dinner” example has garbage, clean hands and quiet at home; goals are dinner, wrapped present and no garbage. Cooking needs clean hands; wrapping needs quiet; taking out garbage dirties hands and the cart makes noise.
Notice two things. With cake at , and are mutex: is achieved only by Eat and only by persistence of , inconsistent with Eat. At Bake appears because is already in , and at pair has consistent support: preserve and Bake. In dinner at , no goal pair is mutex: and can be achieved by cook and cart; and by wrap and take out. But not all three: take out interferes with cook and cart with wrap. Mutexes are pairwise, and pairwise nonmutex goals may be impossible together.
Graph properties
Persistence puts every literal of in and every action of in . Mutexes move the opposite way: Blum and Furst prove that if two literals (or actions) are nonmutex at one level, they remain so next level. With finitely many literals and pairs, eventually nothing changes: the graph levels off. Each level is linear in grounded literals and actions, mutex computation quadratic, so constructing levels takes polynomial time in and problem size.
You will prove this by induction on in the guided exercise. Two consequences. First, the level where goals appear without mutexes lower-bounds any plan’s parallel steps. Haslum and Geffner (Admissible heuristics for optimal planning, AIPS 2000) related it to admissible heuristic family : for parallel steps, the graph and mutexes compute essentially , which is to atom pairs what the previous lesson’s is to individual atoms. Second, the converse is false, as dinner showed. GraphPlan therefore needs a second phase.
Backward extraction and nogoods
When every goal is in without pairwise mutexes, GraphPlan attempts to extract a plan: choose for each goal an action achieving it (preferring persistence), with chosen actions pairwise nonmutex; their preconditions become goals of level , and repeat to . This is backtracking like logic programming’s backward chaining, bounded by levels. On failure record the goal set as a nogood at that level and do not retry; then add a level and repeat.
When can we conclude no plan exists? Blum and Furst proved that if the graph has leveled off at and the level nogood set does not change between consecutive extraction attempts, no plan of any length exists. Without that test GraphPlan would add levels forever on an unsolvable problem.
The cell implements everything from scratch: the graph with three action-mutex and two literal-mutex rules, extraction with nogoods and the termination test. The figure’s data comes from the same class.
from collections import namedtuple
from itertools import combinations
# ---------------- STRIPS mínimo (el de la lección anterior) ----------------
Accion = namedtuple("Accion", "nombre pre add dele")
Tarea = namedtuple("Tarea", "atomos init meta acciones")
def accion(nombre, pre=(), add=(), dele=()):
return Accion(nombre, frozenset(pre), frozenset(add), frozenset(dele) - frozenset(add))
# ---------------- GraphPlan con literales (átomo, polaridad) ----------------
def neg(l):
return (l[0], not l[1])
def lit(s):
return (s[1:], False) if s.startswith("¬") else (s, True)
def nombre_lit(l):
return ("" if l[1] else "¬") + l[0]
class Op:
def __init__(self, nombre, pre=(), add=(), dele=(), noop=False):
self.nombre, self.noop = nombre, noop
self.pre = frozenset(pre) # literales
self.efe = frozenset([(p, True) for p in add] + [(p, False) for p in dele])
def op(nombre, pre=(), add=(), dele=()):
return Op(nombre, [lit(p) for p in pre], add, dele)
def noop(l):
return Op(f"mantener {nombre_lit(l)}", [l], [l[0]] if l[1] else [], [] if l[1] else [l[0]], noop=True)
class GrafoPlan:
def __init__(self, atomos, init, ops):
self.ops = ops
self.S = [frozenset((p, p in init) for p in atomos)] # S_0: mundo cerrado
self.muS = [set()] # exclusiones entre literales
self.A, self.muA = [], [] # niveles de acciones y sus exclusiones
self.nogood = {}
self.traza = [] # pasos de la extracción (para la figura)
def mutex_lit(self, i, l1, l2):
return frozenset((l1, l2)) in self.muS[i]
def expandir(self):
i, S = len(self.A), self.S[-1]
acts = [noop(l) for l in sorted(S)] + [o for o in self.ops
if o.pre <= S and not any(self.mutex_lit(i, p, q) for p, q in combinations(o.pre, 2))]
mu = set()
for a, b in combinations(acts, 2):
if (any(neg(e) in b.efe for e in a.efe) # efectos inconsistentes
or any(neg(e) in b.pre for e in a.efe) or any(neg(e) in a.pre for e in b.efe) # interferencia
or any(self.mutex_lit(i, p, q) for p in a.pre for q in b.pre)): # necesidades en competencia
mu.add(frozenset((a, b)))
S2 = frozenset(e for a in acts for e in a.efe)
logra = {l: [a for a in acts if l in a.efe] for l in S2}
muS = set()
for l1, l2 in combinations(sorted(S2), 2):
if l1 == neg(l2) or all(a is not b and frozenset((a, b)) in mu for a in logra[l1] for b in logra[l2]):
muS.add(frozenset((l1, l2))) # negación o apoyo inconsistente
self.A.append(acts); self.muA.append(mu); self.S.append(S2); self.muS.append(muS)
def extraer(self, metas, i):
"""Búsqueda hacia atrás desde el nivel i con memoria de conjuntos imposibles (nogoods)."""
if i == 0:
self.traza.append(("inicial", 0, metas))
return [] if metas <= self.S[0] else None
if metas in self.nogood.get(i, set()):
self.traza.append(("memo", i, metas))
return None
plan = self._elegir(sorted(metas), 0, [], i)
if plan is None:
self.nogood.setdefault(i, set()).add(metas)
self.traza.append(("falla", i, metas))
return plan
def _elegir(self, metas, k, elegidas, i):
if k == len(metas):
self.traza.append(("elige", i, [a.nombre for a in elegidas]))
sub = frozenset(p for a in elegidas for p in a.pre)
antes = self.extraer(sub, i - 1)
return None if antes is None else antes + [[a.nombre for a in elegidas if not a.noop]]
g = metas[k]
if any(g in a.efe for a in elegidas): # ya la logra una acción elegida
return self._elegir(metas, k + 1, elegidas, i)
cand = sorted((a for a in self.A[i - 1] if g in a.efe), key=lambda a: not a.noop)
for a in cand: # primero los mantenimientos
if all(frozenset((a, b)) not in self.muA[i - 1] for b in elegidas):
r = self._elegir(metas, k + 1, elegidas + [a], i)
if r is not None:
return r
return None
def resolver(self, metas, max_niveles=60, traza=True):
metas = frozenset(lit(m) for m in metas)
nivelado, nogoods_antes = None, -1
while len(self.A) < max_niveles:
i = len(self.S) - 1
if metas <= self.S[i] and not any(self.mutex_lit(i, p, q) for p, q in combinations(metas, 2)):
self.traza.append(("intento", i, metas))
plan = self.extraer(metas, i)
if traza:
print(f" nivel {i}: metas presentes y sin exclusiones -> extracción {'con éxito' if plan is not None else 'fallida'}")
if plan is not None:
return plan
if nivelado is not None: # prueba de terminación de Blum y Furst
n = len(self.nogood.get(nivelado, ()))
if n == nogoods_antes:
return None
nogoods_antes = n
else:
if traza:
print(f" nivel {i}: {'faltan metas' if not metas <= self.S[i] else 'hay metas en exclusión mutua'}")
if nivelado is not None:
return None # estabilizado sin las metas: no hay plan
self.expandir()
if nivelado is None and self.S[-1] == self.S[-2] and self.muS[-1] == self.muS[-2]:
nivelado = len(self.S) - 2
return None
def ver_nivel(G, i):
lits = sorted(nombre_lit(l) for l in G.S[i])
mu = sorted(" / ".join(sorted(nombre_lit(l) for l in m)) for m in G.muS[i])
print(f" S{i}: {lits}")
print(f" exclusiones: {mu}")
print("La tarta:")
tarta = GrafoPlan(["tengo", "comida"], {"tengo"},
[op("Comer", ["tengo"], ["comida"], ["tengo"]), op("Hornear", ["¬tengo"], ["tengo"])])
plan = tarta.resolver(["tengo", "comida"])
for i in range(len(tarta.S)):
ver_nivel(tarta, i)
print(" plan:", plan)
print("\nLa cena sorpresa:")
cena = GrafoPlan(["basura", "manos", "silencio", "cena", "regalo"], {"basura", "manos", "silencio"},
[op("cocinar", ["manos"], ["cena"]), op("envolver", ["silencio"], ["regalo"]),
op("sacar", [], [], ["basura", "manos"]), op("carretilla", [], [], ["basura", "silencio"])])
plan = cena.resolver(["cena", "regalo", "¬basura"])
ver_nivel(cena, 1)
print(" nogoods anotados en el nivel 1:", [sorted(nombre_lit(l) for l in s) for s in cena.nogood.get(1, ())])
print(" plan:", plan)
print("\nEl triángulo: tres metas compatibles dos a dos, nunca las tres a la vez")
tri = GrafoPlan(["p", "q", "r"], set(), [op("pq", [], ["p", "q"], ["r"]), op("qr", [], ["q", "r"], ["p"]), op("rp", [], ["r", "p"], ["q"])])
plan = tri.resolver(["p", "q", "r"])
print(" plan:", plan, " niveles de literales construidos:", len(tri.S),
" nogoods por nivel:", {i: len(v) for i, v in sorted(tri.nogood.items())})Output reproduces the figure. For cake, has four mutexes (the two negations, and ) and at the mutex disappears; the plan is Eat then Bake. In dinner, level-1 extraction fails, records as a nogood, and level-2 extraction finds the parallel plan: cook and wrap together, then take out garbage. The triangle tests termination. Each action achieves two of three atoms and deletes the third, so goals appear pairwise nonmutex (rp achieves and together, for example) but never all three. The graph quickly levels off, each extraction fails and records nogoods, and when an attempt adds none at the stabilized level, Blum and Furst’s test declares no plan.
Planning as satisfiability
Kautz and Selman proposed a direct reduction in 1992 (Planning as Satisfiability, ECAI): “is there an -step plan?” is a propositional formula, and a model is a plan. Four years later, Pushing the Envelope (AAAI 1996) showed careful encodings and stochastic local search solving larger logistics and blocks-world problems than GraphPlan. The idea is the usual reduction to SAT: one variable for each thing that can be true at each time.
Frame axioms are delicate, sharing the history of the frame problem seen in action representation. Effect clauses say what changes when an action executes, not what does not change: without more clauses the solver may set any atom true at any time. Classical one-axiom-per-action-and-unaffected-atom needs clauses per step. Explanatory axioms (Haas, 1987; Schubert, 1990) reverse this: rather than saying what each action preserves, any atom change must be explained by some action. There are two clauses per atom and step, total length proportional to effect count.
Proof
() Take a model, let and . By (3), every action’s preconditions are in . By (4), if is added by some action in then , and if some deletes it ; since the model exists no atom is both added and deleted in one step. If is neither added nor deleted by any action in , the frame axioms force . Therefore , with and the unions of deletes and adds of . Execute in any order. No action deletes another’s precondition (by (6)), so each finds preconditions that were in and no one deleted. Since no atom is added and deleted in one step, the sequence yields in any order. By (1) and (2), and .
() Given the sequence, assign true if and only if and according to state . Clauses (1)–(4) hold by construction (all orders giving the same state requires no atom be both added and deleted in a step, and reached state be ). If changes true to false, some action in deletes it, and if false to true, some action adds it: frame axioms hold. Finally, if and deletes an precondition, ordering “ before ” would not be executable, contradicting the assumption: mutexes hold.
∎Parallelism: ∀-steps and ∃-steps
Clause (6) decides what a step is, and how many are needed. Three common semantics were formalized by Rintanen, Heljanko and Niemelä (Planning as satisfiability: parallel plans and algorithms for plan search, Artificial Intelligence, 2006):
- Sequential: at most one action per step. Exclude all pairs, clauses per step (or an “at most one” cardinality encoding needing ). Minimum horizon equals optimal plan length.
- ∀-steps: an action set is a step if every ordering is executable and yields the same result. Exclude pairs interfering either way: GraphPlan’s and the preceding theorem’s semantics.
- ∃-steps: it suffices that some executable ordering yields the same result as applying all effects simultaneously. Fix a total action order in advance and exclude only pairs where an earlier action deletes a later precondition. With “unload before drive”, a truck may unload and leave for another city in one step.
Contradictory effects need no clauses: effect clauses already make them unsatisfiable. Fewer mutexes allow more actions per step, shorter horizon and smaller formula. Rintanen et al. also provide an ∃-step encoding linear in effects, using auxiliaries propagating “some earlier action deleted ” along the fixed order; we use the clearer quadratic version. Madagascar, Rintanen’s SAT planner, uses the linear encoding.
Lab 1: SATPlan with your CDCL
The solver is a compact version of the SAT lesson’s CDCL with 1-UIP analysis: two watched literals, 1-UIP learning with nonchronological backjumping, VSIDS with a lazy heap, saved phase (false by default, MiniSat’s choice, favoring few-action plans here), and Luby restarts. It lacks clause minimization and deletion, irrelevant at this size, and adds something needed: assumptions, literals fixed as each call’s first decisions, like Z3’s incremental solving.
import heapq
def luby(i):
k = 1
while (1 << k) - 1 < i:
k += 1
while True:
if i == (1 << k) - 1:
return 1 << (k - 1)
if i >= (1 << (k - 1)):
i -= (1 << (k - 1)) - 1; k -= 1
else:
k -= 1
class CDCL:
"""Dos literales vigilados, 1-UIP, salto no cronológico, VSIDS con montículo perezoso, fase guardada
(falso por defecto), reinicios de Luby y suposiciones a la MiniSat. Sin borrado ni minimización."""
def __init__(self, n=0):
self.n = 0
self.clauses, self.watches = [], {}
self.val, self.level, self.reason, self.act, self.phase = [0], [0], [-1], [0.0], [-1]
self.trail, self.lim, self.qhead = [], [], 0
self.heap, self.inc = [], 1.0
self.ok = True
self.conflicts = self.decisions = self.props = 0
self.nuevas_variables(n)
def nuevas_variables(self, k):
for _ in range(k):
self.n += 1
self.val.append(0); self.level.append(0); self.reason.append(-1)
self.act.append(0.0); self.phase.append(-1)
heapq.heappush(self.heap, (0.0, self.n))
return self.n
def value(self, l):
v = self.val[abs(l)]
return v if l > 0 else -v
def assign(self, l, r):
v = abs(l)
self.val[v] = 1 if l > 0 else -1
self.level[v] = len(self.lim)
self.reason[v] = r
self.trail.append(l)
def add_clause(self, c):
"""Cláusula permanente; se puede llamar entre dos solve (uso incremental)."""
self.backtrack(0)
c = list(dict.fromkeys(c))
if any(-l in c for l in c) or any(self.value(l) == 1 for l in c):
return
c = [l for l in c if self.value(l) == 0]
if not c:
self.ok = False
elif len(c) == 1:
self.assign(c[0], -1)
if self.propagate() is not None:
self.ok = False
else:
ci = len(self.clauses)
self.clauses.append(c)
self.watches.setdefault(c[0], []).append(ci)
self.watches.setdefault(c[1], []).append(ci)
def propagate(self):
while self.qhead < len(self.trail):
p = -self.trail[self.qhead]
self.qhead += 1
lista, nueva = self.watches.get(p, []), []
i, m = 0, len(lista)
while i < m:
ci = lista[i]; i += 1
c = self.clauses[ci]
if c[0] == p:
c[0], c[1] = c[1], c[0]
if self.value(c[0]) == 1:
nueva.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.watches.setdefault(c[1], []).append(ci)
break
else:
nueva.append(ci)
if self.value(c[0]) == -1:
nueva.extend(lista[i:])
self.watches[p] = nueva
return ci
self.assign(c[0], ci)
self.props += 1
self.watches[p] = nueva
return None
def backtrack(self, lvl):
if len(self.lim) <= lvl:
return
for l in self.trail[self.lim[lvl]:]:
v = abs(l)
self.phase[v] = self.val[v]
self.val[v] = 0
self.reason[v] = -1
heapq.heappush(self.heap, (-self.act[v], v))
del self.trail[self.lim[lvl]:]
del self.lim[lvl:]
self.qhead = len(self.trail)
def analyze(self, confl):
seen, dl = set(), len(self.lim)
learnt, counter, p, idx = [0], 0, 0, len(self.trail) - 1
while True:
c = self.clauses[confl]
for q in (c if p == 0 else c[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] >= dl:
counter += 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))
counter -= 1
if counter == 0:
break
confl = self.reason[abs(p)]
learnt[0] = -p
self.inc /= 0.95
if self.inc > 1e100:
self.act = [a * 1e-100 for a in self.act]; self.inc *= 1e-100
if len(learnt) == 1:
return learnt, 0
k = max(range(1, len(learnt)), key=lambda j: self.level[abs(learnt[j])])
learnt[1], learnt[k] = learnt[k], learnt[1]
return learnt, self.level[abs(learnt[1])]
def pick(self):
while self.heap:
_, v = heapq.heappop(self.heap)
if self.val[v] == 0:
return v if self.phase[v] == 1 else -v
return 0
def solve(self, assumptions=()):
if not self.ok:
return False
self.backtrack(0)
if self.propagate() is not None:
self.ok = False
return False
for v in range(1, self.n + 1):
if self.val[v] == 0:
heapq.heappush(self.heap, (-self.act[v], v))
run, budget, since = 1, 100, 0
while True:
confl = self.propagate()
if confl is not None:
self.conflicts += 1; since += 1
if not self.lim:
self.ok = False
return False
learnt, bj = self.analyze(confl)
self.backtrack(bj)
if len(learnt) == 1:
self.assign(learnt[0], -1)
else:
ci = len(self.clauses)
self.clauses.append(learnt)
self.watches.setdefault(learnt[0], []).append(ci)
self.watches.setdefault(learnt[1], []).append(ci)
self.assign(learnt[0], ci)
for q in learnt:
heapq.heappush(self.heap, (-self.act[abs(q)], abs(q)))
continue
if since >= budget: # reinicio de Luby
run += 1; since = 0; budget = 100 * luby(run)
self.backtrack(0)
continue
lit_ = 0
while len(self.lim) < len(assumptions): # las suposiciones, como primeras decisiones
a = assumptions[len(self.lim)]
if self.value(a) == 1:
self.lim.append(len(self.trail)) # nivel vacío: ya se cumple
elif self.value(a) == -1:
return False # insatisfacible bajo las suposiciones
else:
lit_ = a
break
if lit_ == 0:
lit_ = self.pick()
if lit_ == 0:
return True
self.decisions += 1
self.lim.append(len(self.trail))
self.assign(lit_, -1)
def modelo(self):
return [self.val[v] == 1 for v in range(self.n + 1)]
# comprobación rápida: el palomar de 4 palomas y 3 huecos es insatisfacible; con 3 huecos y 3 palomas, no
def palomar(p, h):
v = lambda i, j: i * h + j + 1
C = [[v(i, j) for j in range(h)] for i in range(p)]
C += [[-v(i, j), -v(k, j)] for j in range(h) for i in range(p) for k in range(i + 1, p)]
return p * h, C
for p, h in [(4, 3), (3, 3)]:
n, C = palomar(p, h)
S = CDCL(n)
for c in C:
S.add_clause(c)
print(f"palomar({p}, {h}): {'SAT' if S.solve() else 'UNSAT'} con {S.conflicts} conflictos")Now encoding. Class Codificacion numbers variables fixed by instant ( and always occupy the same position in instant ‘s block), so step clauses do not depend on total horizon. Lab 3 can add steps one by one. Function valida executes a step plan and checks validity under the corresponding semantics: do not simply trust the solver.
def interfiere(a, b):
"""a deshabilita b: a borra una precondición de b."""
return bool(a.dele & b.pre)
def pares_excluidos(tarea, semantica):
A, n = tarea.acciones, len(tarea.acciones)
if semantica == "secuencial":
return [(i, j) for i in range(n) for j in range(i + 1, n)]
if semantica == "todos": # pasos ∀: ninguna deshabilita a otra, en ningún sentido
return [(i, j) for i in range(n) for j in range(i + 1, n) if interfiere(A[i], A[j]) or interfiere(A[j], A[i])]
if semantica == "existe": # pasos ∃ con el orden de la lista: ninguna deshabilita a una posterior
return [(i, j) for i in range(n) for j in range(i + 1, n) if interfiere(A[i], A[j])]
if semantica == "ninguna":
return []
raise ValueError(semantica)
class Codificacion:
"""x(t, f): el átomo f es cierto en el instante t; a(t, i): la acción i se ejecuta en el paso t.
La numeración DIMACS es fija por instante, independiente del horizonte."""
def __init__(self, tarea, semantica="todos", marco=True):
self.tarea, self.marco = tarea, marco
self.F, self.A = list(tarea.atomos), tarea.acciones
self.fi = {f: j for j, f in enumerate(self.F)}
self.ancho = len(self.F) + len(self.A)
self.excl = pares_excluidos(tarea, semantica)
self.borran = {f: [i for i, a in enumerate(self.A) if f in a.dele] for f in self.F}
self.anaden = {f: [i for i, a in enumerate(self.A) if f in a.add] for f in self.F}
def x(self, t, f):
return t * self.ancho + self.fi[f] + 1
def a(self, t, i):
return t * self.ancho + len(self.F) + i + 1
def variables(self, T):
return T * self.ancho + len(self.F)
def inicial(self):
return [[self.x(0, f)] if f in self.tarea.init else [-self.x(0, f)] for f in self.F]
def metas(self, T):
return [self.x(T, g) for g in sorted(self.tarea.meta)]
def paso(self, t):
C, x, a = [], self.x, self.a
for i, ac in enumerate(self.A):
C += [[-a(t, i), x(t, p)] for p in sorted(ac.pre)] # precondiciones
C += [[-a(t, i), x(t + 1, q)] for q in sorted(ac.add)] # efectos positivos
C += [[-a(t, i), -x(t + 1, q)] for q in sorted(ac.dele)] # efectos negativos
if self.marco: # axiomas de marco explicativos
for f in self.F:
C.append([-x(t, f), x(t + 1, f)] + [a(t, i) for i in self.borran[f]])
C.append([x(t, f), -x(t + 1, f)] + [a(t, i) for i in self.anaden[f]])
C += [[-a(t, i), -a(t, j)] for i, j in self.excl] # exclusiones
return C
def formula(self, T):
C = self.inicial()
for t in range(T):
C += self.paso(t)
return C + [[g] for g in self.metas(T)]
def plan(self, modelo, T):
return [[ac.nombre for i, ac in enumerate(self.A) if modelo[self.a(t, i)]] for t in range(T)]
def estados(self, modelo, T):
return [sorted(f for f in self.F if modelo[self.x(t, f)]) for t in range(T + 1)]
def valida(tarea, pasos, semantica="todos"):
"""Ejecuta un plan por pasos: precondiciones ciertas al empezar cada paso y, según la semántica,
ninguna acción deshabilita a otra (∀) o a una posterior en el orden fijo (∃)."""
idx = {a.nombre: a for a in tarea.acciones}
orden = {a.nombre: k for k, a in enumerate(tarea.acciones)}
s = set(tarea.init)
for k, paso in enumerate(pasos):
acc = sorted((idx[n] for n in paso), key=lambda b: orden[b.nombre])
for b in acc:
if not b.pre <= s:
return False, f"paso {k}: {b.nombre} sin su precondición"
for i, b in enumerate(acc):
for c in acc[i + 1:]:
if b.add & c.dele or c.add & b.dele:
return False, f"paso {k}: {b.nombre} y {c.nombre} tienen efectos contradictorios"
if (semantica != "existe" and interfiere(c, b)) or interfiere(b, c):
return False, f"paso {k}: {b.nombre} y {c.nombre} interfieren"
for b in acc:
s = (s - b.dele) | b.add
return (True, "válido") if tarea.meta <= s else (False, "no alcanza la meta")
def satplan(tarea, semantica="todos", Tmax=30, marco=True, verbose=True):
"""Horizontes T = 0, 1, 2... con un resolvedor nuevo para cada uno (la estrategia de Kautz y Selman)."""
cod = Codificacion(tarea, semantica, marco)
for T in range(Tmax + 1):
F = cod.formula(T)
S = CDCL(cod.variables(T))
for c in F:
S.add_clause(c)
r = S.solve()
if verbose:
print(f" T = {T:2d}: {cod.variables(T):4d} variables, {len(F):5d} cláusulas -> {'SAT ' if r else 'UNSAT'} ({S.conflicts} conflictos)")
if r:
return T, cod.plan(S.modelo(), T), S.modelo()
return None, None, None
def logistica(camiones, paquetes, lugares):
"""camiones: {c: lugar}; paquetes: {p: (origen, destino)}. Orden de la lista: cargar, descargar, conducir
(es el orden fijo de los pasos ∃: cargar y descargar pueden preceder a conducir en el mismo paso)."""
A = [accion(f"cargar({p},{c},{x})", [f"en({p},{x})", f"en({c},{x})"], [f"dentro({p},{c})"], [f"en({p},{x})"])
for p in paquetes for c in camiones for x in lugares]
A += [accion(f"descargar({p},{c},{x})", [f"dentro({p},{c})", f"en({c},{x})"], [f"en({p},{x})"], [f"dentro({p},{c})"])
for p in paquetes for c in camiones for x in lugares]
A += [accion(f"conducir({c},{x},{y})", [f"en({c},{x})"], [f"en({c},{y})"], [f"en({c},{x})"])
for c in camiones for x in lugares for y in lugares if x != y]
atomos = sorted({f for a in A for f in a.pre | a.add | a.dele})
init = frozenset([f"en({c},{x})" for c, x in camiones.items()] + [f"en({p},{o})" for p, (o, d) in paquetes.items()])
meta = frozenset(f"en({p},{d})" for p, (o, d) in paquetes.items())
return Tarea(atomos, init, meta, A)
REPARTO = logistica({"c1": "D", "c2": "D"}, {"p1": ("A", "B"), "p2": ("D", "B"), "p3": ("C", "B")}, ["A", "B", "C", "D"])
print(f"REPARTO: {len(REPARTO.atomos)} átomos, {len(REPARTO.acciones)} acciones")
for sem in ["todos", "existe"]:
print(f"\nPasos {'∀' if sem == 'todos' else '∃'}:")
T, plan, _ = satplan(REPARTO, sem)
print(f" horizonte mínimo {T}, {sum(map(len, plan))} acciones, validación: {valida(REPARTO, plan, sem)}")
for t, paso in enumerate(plan):
print(f" paso {t}: {', '.join(paso)}")Output has three readings. First: minimum horizon is 5 for ∀-steps and 3 for ∃-steps versus sequential optimum 9 actions (A* calculates it below). In ∃ plan step 1, truck c1 loads p1 at A and drives to B in the same step, and c2 does likewise with p3 at C: driving deletes , a loading precondition, so the step is valid only in fixed order (load before drive), admitted by ∃ but not ∀ semantics. Second: unsatisfiable horizons are almost free (34 conflicts at most with ∀-steps) because precondition, effect and frame clauses propagate strongly. Third: size. With there are variables, and the formula grows linearly with .
for marco, sem, que in [(False, "todos", "sin axiomas de marco"), (True, "ninguna", "sin exclusiones")]:
T, plan, modelo = satplan(REPARTO, sem, marco=marco, verbose=False)
cod = Codificacion(REPARTO, sem, marco)
print(f"{que}: SAT ya con T = {T}, {sum(map(len, plan))} acciones; validación: {valida(REPARTO, plan, 'todos')}")
if not marco:
print(" estado del instante 1 según el modelo:", [f for f in cod.estados(modelo, T)[1] if f.startswith("en(p")])Minimum horizon does not give the shortest plan
Rintanen states in his 2012 paper that guaranteeing minimum horizon is not important, because for common notions of parallel plan horizon length corresponds to no relevant quality measure, and parallelism represents reorderability rather than actual concurrency. It reduces the search space, not an objective.
Compare heuristic search and GraphPlan
The next cell closes the loop. Solve REPARTO with the previous lesson’s A* and admissible heuristic , yielding the sequential optimum; greedy search and , fast but not optimal; and GraphPlan, which should find a plan with the ∀ encoding’s parallel step count because their semantics match.
import time
def h_relajada(tarea, s, agregar):
"""h_max (agregar=max) o h_add (agregar=sum) por punto fijo, como en la lección anterior."""
INF = float("inf")
c = {f: 0 for f in s}
cambio = True
while cambio:
cambio = False
for a in tarea.acciones:
if all(p in c for p in a.pre):
k = 1 + (agregar(c[p] for p in a.pre) if a.pre else 0)
for q in a.add:
if c.get(q, INF) > k:
c[q] = k; cambio = True
if not all(g in c for g in tarea.meta):
return INF
return agregar(c[g] for g in tarea.meta) if tarea.meta else 0
h_max = lambda T, s: h_relajada(T, s, max)
h_add = lambda T, s: h_relajada(T, s, sum)
def mejor_primero(tarea, h, w_g=1, limite=200000):
"""A* (w_g = 1) o búsqueda voraz (w_g = 0). Devuelve (plan, nodos expandidos)."""
s0 = frozenset(tarea.init)
abiertos, n = [(h(tarea, s0), 0, s0)], 1
g, padre, cerrados = {s0: 0}, {s0: None}, set()
while abiertos and len(cerrados) < limite:
_, _, s = heapq.heappop(abiertos)
if s in cerrados:
continue
if tarea.meta <= s:
plan = []
while padre[s] is not None:
s, nombre = padre[s]; plan.append(nombre)
return plan[::-1], len(cerrados)
cerrados.add(s)
for a in tarea.acciones:
if a.pre <= s:
t = (s - a.dele) | a.add
if t not in g or g[s] + 1 < g[t]:
g[t] = g[s] + 1; padre[t] = (s, a.nombre)
ht = h(tarea, t)
if ht < float("inf"):
heapq.heappush(abiertos, (w_g * g[t] + ht, n, t)); n += 1
return None, len(cerrados)
for nombre, h, w in [("A* con h_max", h_max, 1), ("voraz con h_add", h_add, 0)]:
t0 = time.perf_counter()
plan, exp = mejor_primero(REPARTO, h, w)
print(f"{nombre:16s}: {len(plan)} acciones, {exp} nodos expandidos, {time.perf_counter() - t0:.2f} s")
G = GrafoPlan(REPARTO.atomos, REPARTO.init, [Op(a.nombre, [(p, True) for p in a.pre], a.add, a.dele) for a in REPARTO.acciones])
plan = G.resolver(sorted(REPARTO.meta), traza=False)
print(f"GraphPlan : {len(plan)} pasos paralelos, {sum(map(len, plan))} acciones; validación ∀: {valida(REPARTO, plan, 'todos')}")A* confirms sequential optimum 9 actions after expanding just over a thousand states; greedy search expands very few nodes but gives 12 actions, three extra; GraphPlan reaches level 5, the ∀ encoding’s horizon, with a valid plan. All agree with what we proved: a sequential plan of actions is a ∀ plan of steps (one per action), so minimum ∀ horizon lower-bounds every sequential plan’s length; step count is not action count.
Horizons, assumptions and why SAT competes
The satplan loop is Kautz and Selman’s original strategy: try with a fresh solver each time. Two costs arise. First, repeated work: formula contains (except goal clauses), and all the solver learned about early steps is thrown away. Second, worse: proving unsatisfiable for just below optimum is often costliest, because a refutation must cover all plans of that length. The interactive’s sequential row, computed by your CDCL (reproduce with satplan(REPARTO, "secuencial"), a few seconds in the browser), shows refuting costs 3013 conflicts, more than finding a plan at (2642), while the last unsatisfiable ∀ horizon costs 34.
Two complementary remedies:
- Incremental SAT with assumptions. Step clauses are permanent and goals are requested as assumptions: to test , add clauses for step and call
solve(assumptions = metas en T). Since assumptions are decisions, never reasons, all learned clauses follow from permanent clauses and remain useful for later horizons (the Z3 lesson’s theorem). Lab 3 measures it. - Parallel horizons. Rintanen avoids completing unsatisfiability proofs: algorithm B shares CPU among many horizons, giving a fraction (0.9 in Madagascar) of the time for . A satisfiable horizon slightly above minimum often solves before refuting the one immediately below: in that sequential row, solves with 673 conflicts versus 3013 to refute .
Why can this compete with A* and greedy search? For years it did not: Rintanen notes early encodings were huge and quadratic, and SAT work did not even compare to planners like LAMA because of the performance gap. Three changes closed it: linear ∃-step encodings shortening horizon; parallel horizon evaluation; and a planning-specific decision heuristic. In Planning as satisfiability: Heuristics (2012), Rintanen replaces VSIDS with a rule searching backward in time for the latest action achieving each unexplained goal or subgoal and deciding it true. On 1646 competition instances from 1998–2011 with 30 minutes each, his Mp planner solved 1416 versus 1414 for LAMA 2011, 1332 LAMA 2008, 1238 FF and 1304 the same setup with VSIDS (paper table 5). The SAT solver is not magic: unit propagation over the encoding deduces invariants like “a truck is in one place”, and clause learning reuses them at all instants.
In competitions, SATPLAN04 won IPC-4’s optimal planning category (2004) and SATPLAN06 shared first place with MaxPlan at IPC-5 (2006).
Lab 3: incremental SAT with an industrial solver
PySAT exposes Armin Biere’s CaDiCaL to Python, including in the browser. The cell compares both approaches under three semantics: a fresh solver per horizon (goals also as assumptions, so only reuse differs) versus one solver with added steps. It then uses a cardinality encoding (Sinz sequential counter) to calculate minimum actions at each minimum horizon. Times depend on your machine; conflicts do not.
import random
from pysat.solvers import Solver
from pysat.card import CardEnc, EncType
def desde_cero(cod, Tmax=40):
conflictos, t0 = 0, time.perf_counter()
for T in range(Tmax + 1):
with Solver(name="cadical153", bootstrap_with=cod.inicial() + [c for t in range(T) for c in cod.paso(t)]) as s:
r = s.solve(assumptions=cod.metas(T))
conflictos += s.accum_stats()["conflicts"]
if r:
return T, conflictos, time.perf_counter() - t0
def incremental(cod, Tmax=40):
t0 = time.perf_counter()
s = Solver(name="cadical153", bootstrap_with=cod.inicial())
for T in range(Tmax + 1):
if T > 0:
s.append_formula(cod.paso(T - 1)) # solo las cláusulas del paso nuevo
if s.solve(assumptions=cod.metas(T)):
break
conflictos = s.accum_stats()["conflicts"]
s.delete()
return T, conflictos, time.perf_counter() - t0
def logistica_aleatoria(n_cam, n_lug, n_paq, semilla):
R = random.Random(semilla)
L = [f"L{i}" for i in range(n_lug)]
return logistica({f"c{i}": R.choice(L) for i in range(n_cam)},
{f"p{i}": tuple(R.sample(L, 2)) for i in range(n_paq)}, L)
GRANDE = logistica_aleatoria(3, 6, 8, 1)
print(f"GRANDE: {len(GRANDE.atomos)} átomos, {len(GRANDE.acciones)} acciones")
for nombre, tarea, sems in [("REPARTO", REPARTO, ["secuencial", "todos", "existe"]), ("GRANDE", GRANDE, ["todos", "existe"])]:
for sem in sems:
cod = Codificacion(tarea, sem)
T1, c1, t1 = desde_cero(cod)
T2, c2, t2 = incremental(cod)
assert T1 == T2
print(f"{nombre:8s} {sem:10s} T* = {T1:2d} desde cero: {c1:6d} conflictos, {t1:.2f} s incremental: {c2:6d} conflictos, {t2:.2f} s")The lab’s second part answers the warning: minimum actions at minimum horizon. Search top-down: solve without limit, count model actions , ask for at most , repeat until unsatisfiable. Each model improves the prior, and the final unsatisfiable answer proves the minimum is the last found.
def min_acciones(tarea, sem, T):
"""Menor número de acciones de un plan de T pasos: búsqueda descendente con «como mucho k» (Sinz)."""
cod = Codificacion(tarea, sem)
acts = [cod.a(t, i) for t in range(T) for i in range(len(tarea.acciones))]
F, mejor, cota = cod.formula(T), None, None
while True:
extra = [] if cota is None else CardEnc.atmost(lits=acts, bound=cota, top_id=cod.variables(T), encoding=EncType.seqcounter).clauses
with Solver(name="cadical153", bootstrap_with=F + extra) as s:
if not s.solve():
return mejor
modelo = set(l for l in s.get_model() if l > 0)
mejor = sum(1 for v in acts if v in modelo)
cota = mejor - 1
for sem, T in [("todos", 5), ("existe", 3), ("secuencial", 9)]:
print(f"REPARTO, pasos {sem}, T = {T}: ningún plan tiene menos de {min_acciones(REPARTO, sem, T)} acciones")Read carefully: savings vary. On GRANDE (3 trucks, 6 locations, 8 packages) with ∀-steps, incremental needs 2781 conflicts versus 9284 and about one-third the time: unsatisfiable horizons use prior learning, and early-step clauses are neither rebuilt nor repropagated, a fresh-run cost growing with squared. On sequential REPARTO, conflicts only drop from 5259 to 4468 and time is unchanged: work lies in refuting and shorter-horizon learning barely helps. With ∃-steps little can be saved because horizons are few and cheap. Incremental solving is a reliable improvement of variable size; shorter-horizon semantics and parallel evaluation avoiding refutations change the order of magnitude.
The second cell confirms the warning with an independent solver: at least 10 actions with 5 ∀-steps or 3 ∃-steps, and 9 with sequential horizon 9.
Partial-order planning
Both approaches return step sequences. But a plan is fundamentally an action set with dependencies, and committing early to a total order has two drawbacks: search explores irrelevant orderings and the plan loses executor information. Partial-order, or least-commitment, planning searches partial plans and orders only what is necessary. Its line runs from NOAH (Sacerdoti, 1975) and NONLIN (Tate, 1977) to TWEAK (Chapman, 1987), SNLP (McAllester and Rosenblitt, 1991) and UCPOP (Penberthy and Weld, 1992); Weld’s An Introduction to Least Commitment Planning (AI Magazine, 1994) is the reference tutorial.
The partial order is a directed acyclic graph over steps, and a linearization is any topological ordering. The result justifying the method: once complete, every linearization works.
Proof
Fix linearization and step with precondition (including , whose preconditions are goals). No open conditions means link exists, and , so precedes in . Immediately after , is true because adds it (if , because is initially true). Suppose is false at . Some step between and in deletes . That satisfies neither nor in the partial order, because in it follows and precedes and respects . Thus threatens the link, contradiction. Every step’s preconditions therefore hold when it executes, especially goals at .
∎The converse is false: a plan with threats can have valid linearizations, just not all. The interactive shows this. The first problem is security maintenance: download a patch, requiring a temporarily open port; hardening closes it and applies policy; also back up, and end with the port closed. The second is Sussman’s anomaly, the three-block problem used in 1975 to show planning goals one after another fails: stack A on B first and it must be undone to put B on C, and vice versa.
In the patch problem backup is unordered relative to everything and occupies all four possible positions in final linearizations: least commitment. Promotion versus demotion matters. “Harden” threatens link ; demoting it () seems reasonable, but “Open” then threatens and its only resolution closes a cycle. A planner discovers this when checking order consistency and backtracks, as the cell does.
def alcanzables(ordenes, pasos):
"""Cierre transitivo de las restricciones de orden; None si hay un ciclo."""
suc = {s: set() for s in pasos}
for a, b in ordenes:
suc[a].add(b)
alc = {}
for s in pasos:
vistos, pila = set(), list(suc[s])
while pila:
u = pila.pop()
if u not in vistos:
vistos.add(u); pila.extend(suc[u])
if s in vistos:
return None
alc[s] = vistos
return alc
class POP:
"""Búsqueda en el espacio de planes parciales (POP, Weld 1994) con profundización iterativa en el
número de pasos. Cuenta los planes parciales visitados."""
def __init__(self, operadores, init, metas):
self.ops, self.init, self.metas = operadores, frozenset(init), frozenset(metas)
self.nodos = 0
def amenaza(self, pasos, enlaces, alc):
for (p, q, c) in enlaces:
for s, a in pasos.items():
if s not in (p, c) and q in a.dele and p not in alc[s] and s not in alc[c]:
return s, (p, q, c) # s puede caer entre p y c
return None
def refinar(self, pasos, ordenes, enlaces, agenda, max_pasos):
self.nodos += 1
alc = alcanzables(ordenes, pasos)
if alc is None:
return None # orden con un ciclo: inconsistente
am = self.amenaza(pasos, enlaces, alc)
if am:
s, (p, q, c) = am
for nuevo in ((s, p), (c, s)): # degradación, promoción
r = self.refinar(pasos, ordenes | {nuevo}, enlaces, agenda, max_pasos)
if r:
return r
return None
if not agenda:
return pasos, ordenes, enlaces # sin condiciones abiertas ni amenazas
(q, c), resto = agenda[0], agenda[1:]
for s, a in pasos.items(): # 1) un paso existente que produzca q
if q in a.add and s != c and s not in alc[c]:
r = self.refinar(pasos, ordenes | {(s, c)}, enlaces + [(s, q, c)], resto, max_pasos)
if r:
return r
if len(pasos) - 2 < max_pasos: # 2) un paso nuevo
for op in self.ops:
if q in op.add:
s = f"{op.nombre}#{len(pasos) - 1}"
p2 = dict(pasos); p2[s] = op
o2 = ordenes | {("inicio", s), (s, "fin"), (s, c)}
r = self.refinar(p2, o2, enlaces + [(s, q, c)], resto + [(pre, s) for pre in sorted(op.pre)], max_pasos)
if r:
return r
return None
def planificar(self, max_pasos=8):
pasos = {"inicio": accion("inicio", add=self.init), "fin": accion("fin", pre=self.metas)}
for k in range(max_pasos + 1):
r = self.refinar(pasos, frozenset({("inicio", "fin")}), [], [(g, "fin") for g in sorted(self.metas)], k)
if r:
return r
return None
def linealizaciones(pasos, ordenes):
alc = alcanzables(ordenes, pasos)
medio = [s for s in pasos if s not in ("inicio", "fin")]
out = []
def rec(pref, resto):
if not resto:
out.append(pref); return
for s in resto:
if not any(u != s and s in alc[u] for u in resto):
rec(pref + [s], [u for u in resto if u != s])
rec([], medio)
return out
def ejecuta(pasos, orden, init, metas):
s = set(init)
for x in orden:
if not pasos[x].pre <= s:
return False
s = (s - pasos[x].dele) | pasos[x].add
return metas <= s
def bloques(nombres):
ops, lugares = [], nombres + ["mesa"]
for b in nombres:
for x in lugares:
for y in lugares:
if len({b, x, y}) == 3:
ops.append(accion(f"mover({b},{x},{y})",
[f"sobre({b},{x})", f"libre({b})"] + ([f"libre({y})"] if y != "mesa" else []),
[f"sobre({b},{y})"] + ([f"libre({x})"] if x != "mesa" else []),
[f"sobre({b},{x})"] + ([f"libre({y})"] if y != "mesa" else [])))
return ops
def informe(nombre, ops, init, metas):
P = POP(ops, init, metas)
pasos, ordenes, enlaces = P.planificar()
lin = linealizaciones(pasos, ordenes)
elegidas = sorted((a, b) for a, b in ordenes if "inicio" not in (a, b) and "fin" not in (a, b))
print(f"{nombre}: {P.nodos} planes parciales visitados, {len(pasos) - 2} pasos")
print(" orden:", [f"{a} < {b}" for a, b in elegidas])
print(f" linealizaciones: {len(lin)}, todas válidas: {all(ejecuta(pasos, l, init, metas) for l in lin)}")
for l in lin:
print(" ", " -> ".join(l))
informe("Anomalía de Sussman", bloques(["A", "B", "C"]),
{"sobre(A,mesa)", "sobre(B,mesa)", "sobre(C,A)", "libre(B)", "libre(C)"}, {"sobre(A,B)", "sobre(B,C)"})
informe("Parche con puerto temporal",
[accion("abrir_puerto", [], ["puerto_abierto"], ["puerto_cerrado"]),
accion("descargar_parche", ["puerto_abierto"], ["parche"]),
accion("endurecer", [], ["politica", "puerto_cerrado"], ["puerto_abierto"]),
accion("hacer_copia", [], ["copia"])],
{"puerto_cerrado"}, {"parche", "politica", "puerto_cerrado", "copia"})On Sussman’s anomaly, POP finds the three-move plan with a total order forced by two promotions: C to table, B on C, A on B. In patching it leaves four linearizations, one per backup position, all valid as the theorem guarantees. POP also first tries obtaining “port closed” from start: opening threatens that link without any possible resolution (neither before start nor after finish), so search backtracks and obtains closure from “Harden”.
Hierarchical task networks
Earlier approaches receive actions and search for combinations without further knowledge. In real domains that knowledge exists and is valuable: an incident-response manual specifies what to do, order, and acceptable methods. HTN planning writes methods refining abstract tasks into concrete tasks until executable actions.
The difference from classical planning is fundamental: an HTN goal is a task to do, not a fact set, and only decomposition-derived plans count. If methods omit a way to do something, the planner will not find it even if primitive actions permit it. This deliberate restriction lets the domain specify how things are done and the planner choose among ways and check fit.
SHOP: decompose in execution order
SHOP and SHOP2 (Nau et al.; SHOP2: An HTN Planning System, 2003) use ordered decomposition: decompose tasks in execution order. Thus when choosing a method they know the full world state at that point, and preconditions may be arbitrary queries (axioms, arithmetic or external functions), not just atom conjunctions. SHOP2 adds partially ordered subtask networks, allowing subtasks of different tasks to interleave, and received a distinguished performance award at the 2002 International Planning Competition; the 2003 paper explains enabling features, especially in temporal and numeric domains.
The algorithm searches depth-first. Take the first pending task. If primitive and applicable, apply it and continue; if inapplicable, fail. If compound, try methods in order: for each whose precondition holds now, replace the task with subtasks and continue; if later work fails, backtrack to the next method.
Expressiveness and complexity
Hierarchy does more than conveniently express knowledge: it increases expressiveness. Erol, Hendler and Nau (HTN Planning: Complexity and Expressivity, AAAI 1994) proved HTN plan existence undecidable in general, even without variables, once a network may contain two unordered compound tasks: their subtasks can interleave, enabling a decision whether two context-free grammars generate a common string, an undecidable problem. Restricting either restores decidability: with totally ordered networks the problem is EXPSPACE-hard and in 2-EXPTIME, and if also propositional, PSPACE-hard and in EXPTIME; without method recursion (acyclic), decomposition depth is bounded.
The intuition for greater HTN expressiveness than STRIPS is the Chomsky hierarchy. A STRIPS problem’s solutions as a language over actions are regular: recognized by a finite automaton whose states are problem states. If and are actions without relevant preconditions or effects, compound task with methods and generates exactly plans , a context-free nonregular language; no STRIPS problem over those actions has that solution set.
Lab 2: a SHOP-style HTN planner
The domain has the interactive’s primitive actions for any number of hosts, plus two no method uses (manually disconnect cable and dump memory locally, requiring physical access). Initial task responder(e1, ..., en) has a recursive method handling hosts one at a time. Solve the same task classically with goal “all hosts monitored”, using earlier A* and greedy search.
def primitivas(h):
"""Acciones primitivas para el equipo h (STRIPS con precondiciones positivas)."""
return [
accion(f"aislar_edr({h})", [f"comprometido({h})", f"edr({h})", f"encendido({h})"], [f"aislado({h})"]),
accion(f"bloquear_fw({h})", [f"comprometido({h})", f"fw({h})"], [f"aislado({h})"]),
accion(f"apagar({h})", [f"encendido({h})", f"no_critico({h})"], [f"aislado({h})", f"apagado({h})"], [f"encendido({h})"]),
accion(f"desconectar_cable({h})", [f"comprometido({h})", f"acceso_fisico({h})"], [f"aislado({h})"]),
accion(f"volcar_memoria({h})", [f"aislado({h})", f"encendido({h})", f"edr({h})"], [f"evidencia({h})"]),
accion(f"volcar_memoria_local({h})", [f"aislado({h})", f"encendido({h})", f"acceso_fisico({h})"], [f"evidencia({h})"]),
accion(f"copiar_disco({h})", [f"aislado({h})", f"apagado({h})"], [f"evidencia({h})"]),
accion(f"eliminar_malware({h})", [f"aislado({h})", f"evidencia({h})", f"firma({h})", f"encendido({h})"], [f"limpio({h})"], [f"comprometido({h})"]),
accion(f"reinstalar({h})", [f"aislado({h})", f"evidencia({h})", "imagen_limpia"], [f"limpio({h})", f"encendido({h})"], [f"comprometido({h})", f"apagado({h})"]),
accion(f"arrancar({h})", [f"apagado({h})"], [f"encendido({h})"], [f"apagado({h})"]),
accion(f"restaurar_copia({h})", [f"limpio({h})", f"copia({h})"], [f"datos({h})"]),
accion(f"reconectar({h})", [f"limpio({h})", f"datos({h})", f"encendido({h})", f"aislado({h})", "cred_seguras"], [f"servicio({h})"], [f"aislado({h})"]),
accion(f"vigilar({h})", [f"servicio({h})"], [f"vigilado({h})"]),
]
def tarea_incidente(equipos, hechos):
A = [accion("rotar_credenciales", ["cred_expuestas"], ["cred_seguras"], ["cred_expuestas"])]
A += [a for h in equipos for a in primitivas(h)]
atomos = sorted({f for a in A for f in a.pre | a.add | a.dele})
init = frozenset(hechos) | {f"comprometido({h})" for h in equipos} | {f"encendido({h})" for h in equipos}
return Tarea(atomos, init, frozenset(f"vigilado({h})" for h in equipos), A)
def metodos(tarea, s):
"""Métodos de una tarea compuesta: lista de (nombre, ¿precondición cierta en s?, subtareas).
None si la tarea es primitiva."""
nombre, args = tarea
h = args[0] if args else None
if nombre == "responder": # recursión sobre la lista de equipos
return [("uno a uno", True, [("atender", (args[0],)), ("responder", args[1:])])] if args else [("nada", True, [])]
if nombre == "atender":
return [("contener, erradicar, recuperar", True, [("contener", (h,)), ("erradicar", (h,)), ("recuperar", (h,))])]
if nombre == "contener":
return [("por firewall", f"fw({h})" in s, [("bloquear_fw", (h,))]),
("por EDR", f"edr({h})" in s and f"encendido({h})" in s, [("aislar_edr", (h,))]),
("apagando", f"no_critico({h})" in s and f"encendido({h})" in s, [("apagar", (h,))])]
if nombre == "erradicar":
return [("preservar y limpiar", True, [("preservar", (h,)), ("limpiar", (h,))])]
if nombre == "preservar":
return [("memoria por EDR", f"encendido({h})" in s and f"edr({h})" in s, [("volcar_memoria", (h,))]),
("disco", f"apagado({h})" in s, [("copiar_disco", (h,))])]
if nombre == "limpiar":
return [("con firma", f"firma({h})" in s and f"encendido({h})" in s, [("eliminar_malware", (h,))]),
("reinstalando", "imagen_limpia" in s, [("reinstalar", (h,))])]
if nombre == "recuperar":
return [("credenciales, datos, servicio", True, [("credenciales", ()), ("restaurar", (h,)), ("encender", (h,)),
("reconectar", (h,)), ("vigilar", (h,))])]
if nombre == "credenciales":
return [("rotar", "cred_expuestas" in s, [("rotar_credenciales", ())]), ("ya seguras", "cred_seguras" in s, [])]
if nombre == "restaurar":
return [("desde la copia", f"copia({h})" in s, [("restaurar_copia", (h,))])]
if nombre == "encender":
return [("ya encendido", f"encendido({h})" in s, []), ("arrancar", f"apagado({h})" in s, [("arrancar", (h,))])]
return None
def shop(acciones, s, tareas, stats):
"""Descomposición ordenada total con retroceso. Devuelve la lista de acciones o None."""
stats["nodos"] += 1
if not tareas:
return []
t, resto = tareas[0], tareas[1:]
ms = metodos(t, s)
if ms is None: # primitiva: se ejecuta sobre el estado actual
nombre = f"{t[0]}({','.join(t[1])})" if t[1] else t[0]
a = acciones[nombre]
if not a.pre <= s:
return None
r = shop(acciones, (s - a.dele) | a.add, resto, stats)
return None if r is None else [nombre] + r
for _, pre, sub in ms:
if pre:
r = shop(acciones, s, sub + resto, stats)
if r is not None:
return r
if len(ms) > 1:
stats["retrocesos"] += 1 # se abandona un método en un punto de elección
return None
def planificar_htn(tarea, equipos):
stats = {"nodos": 0, "retrocesos": 0}
acc = {a.nombre: a for a in tarea.acciones}
return shop(acc, frozenset(tarea.init), [("responder", tuple(equipos))], stats), stats
def hechos(equipos, extra=(), sin=()):
H = {"imagen_limpia", "cred_expuestas"}
for h in equipos:
H |= {f"fw({h})", f"no_critico({h})", f"firma({h})", f"copia({h})"}
return (H | set(extra)) - set(sin)
T1 = tarea_incidente(["srv"], hechos(["srv"]))
plan, st = planificar_htn(T1, ["srv"])
print("Un equipo:", plan)
print(" ", st)
print("\n n | HTN: nodos, retrocesos | voraz h_add: expandidos, acciones | A* h_max: expandidos, acciones")
for n in range(1, 7):
eqs = [f"e{i}" for i in range(1, n + 1)]
T = tarea_incidente(eqs, hechos(eqs))
p, st = planificar_htn(T, eqs)
pv, ev = mejor_primero(T, h_add, 0)
fila = f"{n:2d} | {st['nodos']:4d} {st['retrocesos']:3d} ({len(p)} acciones) | {ev:5d} {len(pv):3d}"
if n <= 3:
pa, ea = mejor_primero(T, h_max, 1)
fila += f" | {ea:6d} {len(pa):3d}"
print(fila)With one host, SHOP visits a few nodes and backtracks once: “via firewall” applies but leaves the host on without EDR, and no “preserve” method applies next; SHOP undoes it and contains by shutdown. The plan has 7 actions, as do optimal A* and greedy plans. The table shows scaling: SHOP grows linearly because procedure fixes order and there is nothing to explore. Optimal A* grows exponentially because hosts are independent and all action interleavings must be considered: an optimal plan has many orderings A* does not know are equivalent. Greedy search with goes straight to a plan in this delete-relaxation-friendly domain. The honest comparison is not “HTN is faster than heuristic search”: HTN is predictable and follows procedure, while heuristic search finds what the goal permits.
Two situations outside the domain show the other side:
# 1) Equipo crítico, sin EDR ni firewall, pero con acceso físico: ningún método de «contener» encaja
sin_metodo = hechos(["srv"], extra={"acceso_fisico(srv)"}, sin={"fw(srv)", "no_critico(srv)"})
T2 = tarea_incidente(["srv"], sin_metodo)
p, st = planificar_htn(T2, ["srv"])
pc, ec = mejor_primero(T2, h_add, 0)
print("HTN:", p, st)
print("Clásico:", pc)
# 2) La copia está comprometida, un hecho que el método «desde la copia» no comprueba
def ejecutar_en_el_mundo(plan, init, comprometida):
"""El mundo real: restaurar una copia comprometida reinfecta el equipo."""
s = set(init)
acc = {a.nombre: a for a in T1.acciones}
for n in plan:
s = (s - acc[n].dele) | acc[n].add
if n.startswith("restaurar_copia") and comprometida:
s |= {"comprometido(srv)"}; s.discard("limpio(srv)")
return s
plan, _ = planificar_htn(T1, ["srv"])
final = ejecutar_en_el_mundo(plan, T1.init, comprometida=True)
print("\nPlan del modelo:", plan)
print("En el mundo real, al final: vigilado =", "vigilado(srv)" in final, " comprometido =", "comprometido(srv)" in final)In the first, the classical planner finds a plan (disconnect cable, dump memory locally, remove malware…) and SHOP finds none: a critical host cannot be shut down, and there is neither firewall nor EDR. No containment method applies. The procedure did not anticipate this. That may be correct (perhaps the manual forbids improvising with the cable) or a domain gap; either way “no plan” should mean “escalate to a person”, not “nothing can be done”.
HTN in practice
Erol, Hendler and Nau already observed in 1994 that most practical work of the preceding fifteen years used HTN decomposition, such as NOAH, NONLIN, SIPE and DEVISER. Later documented cases: Bridge Baron 8 used HTN for declarer play and won the 1997 world computer bridge championship (Smith, Nau and Throop, Computer Bridge: A Big Win for AI Planning, AI Magazine, 1998); and Killzone 2 multiplayer bots (Guerrilla Games, 2009) used an HTN planner with 360 methods according to Champandard, Verweij and Straatman’s Paris Game AI Conference presentation that year. The reason is consistent: designers control possible behaviors and the plan is explainable by construction, each action under a named task. Language-model agents’ task decomposition has HTN as a formal ancestor, with “methods” in natural language rather than logic, sharing both risks: undescribed things are not attempted, and unwritten assumptions are not checked.
Beyond the classical model
The classical model assumes instantaneous actions, a finite fully observable state, deterministic effects and binary goals. Relaxing each gives a family of problems with languages and complexity. This map is planning beyond the classical model.
| Extension | What changes | Usual representation | Plan existence |
|---|---|---|---|
| Classical (STRIPS) | nothing | PDDL | PSPACE-complete (Bylander, 1994) |
| Numeric and temporal | numeric variables, durations, real concurrency | PDDL 2.1 | undecidable with unbounded numbers (Helmert, 2002) |
| Fully observable nondeterministic (FOND) | an action may have multiple outcomes | PDDL with oneof | EXPTIME-complete (Littman, 1997; Rintanen, 2004) |
| Conformant | uncertain initial state, no observations | belief states | EXPSPACE-complete (Haslum and Jonsson, 2000) |
| Conditional with partial observability | some state observed | belief trees or policies | 2-EXPTIME-complete (Rintanen, 2004) |
| Probabilistic | outcome probabilities | MDP, POMDP | depends on criterion (horizon, discount) |
Time and resources. PDDL 2.1 (Fox and Long, PDDL2.1: An Extension to PDDL for Expressing Temporal Planning Domains, 2003) organizes extensions into levels: level 1 is propositional planning; 2 adds numeric variables (fuel, money, capacity), increment/decrement effects and an optimization metric; 3 adds discretized durative actions, with conditions required at start (at start), end (at end) or throughout (over all), and effects at start or end; 4 adds continuous durative actions. A plan becomes actions with start times, and concurrency is a requirement rather than search reduction: some problems require actions to overlap. Temporal planners combine state search with simple temporal constraints and, like POPF, partial orders.
Nondeterminism. If abrir_puerta can fail, a plan is no longer a sequence but a policy specifying what to do depending on outcomes. Cimatti, Pistore, Roveri and Traverso (Weak, strong, and strong cyclic planning via symbolic model checking, Artificial Intelligence, 2003) distinguish weak solutions (some outcome reaches the goal), strong (all reach it in bounded steps) and strong cyclic (all executions not trapped in a loop reach it, assuming every outcome eventually occurs, as in “retry until success”).
Uncertainty without observation. In conformant planning the initial state is one of several and nothing is observed: the plan must work in all. Search uses belief states, sets of possible states, exponentially larger. Hence the PSPACE-to-EXPSPACE jump.
The jump to probability. With outcome probabilities and rewards replacing goals, the problem is a Markov decision process, and with partial observation a POMDP, which becomes an MDP over belief states. Prior ideas remain useful: factored representations like PDDL compactly describe huge MDPs, classical planning heuristics guide solutions (FF-Replan determinizes, plans with FF and replans after deviations; it won the first probabilistic competition in 2004), and hierarchical decomposition reappears in hierarchical reinforcement learning and robotic task-and-motion planning.
Common mistakes
Exercises
Step 1 of 4. What is the base case?
cargar(p1,c1,A), cargar(p3,c2,C), conducir(c1,A,B) and conducir(c2,C,B). Why is that set not a valid ∀-step?More than one answer may be correct.
codificar(atomos, init, meta, acciones, T), where acciones is a list of tuples (nombre, pre, add, dele) with atom sets. Return (nv, clausulas, x, a): variable count, DIMACS clause list (integer lists), x[t][f] the variable for atom f at instant t (0 to T), and a[t][i] for action i at step t (0 to T - 1). Include the complete initial state, goals, preconditions, effects, explanatory frame axioms and ∀-step mutexes (exclude pairs when one action deletes the other's precondition). Tests solve your formula using a PySAT solver.def codificar(atomos, init, meta, acciones, T):
nv = 0
x, a = [], []
for t in range(T + 1):
x.append({})
for f in atomos:
nv += 1
x[t][f] = nv
for t in range(T):
a.append([])
for _ in acciones:
nv += 1
a[t].append(nv)
C = [[x[0][f]] if f in init else [-x[0][f]] for f in atomos]
C += [[x[T][g]] for g in meta]
# tu código: precondiciones, efectos, marco y exclusiones
return nv, C, x, aSummary
- GraphPlan builds literal and action levels with pairwise mutexes in polynomial time. A mutex at proves no -step plan; its absence proves nothing, so backward extraction with nogoods and termination test is needed.
- SAT planning encodes “an -step plan exists” with time-indexed variables, effects, explanatory frame axioms and mutexes. Without frames atoms change without cause; without mutexes interfering actions run together.
- Parallel semantics determine horizon: sequential, ∀-steps (any order works) or ∃-steps (one fixed order works). Minimum horizon does not minimize actions: REPARTO’s 5 ∀-steps require 10 actions versus sequential optimum 9.
- SAT competes with heuristic search through linear encodings, parallel horizon evaluation, incremental solving with assumptions and planning-specific decision heuristics.
- Partial order resolves threats by promotion or demotion; a plan without open conditions or threats is valid in all linearizations.
- HTN plans by refining tasks through methods in execution order (SHOP). More expressive than STRIPS, predictable and auditable, it still misses what methods do not describe and inherits authors’ unwritten assumptions.
- Beyond classical planning lie time and numbers (PDDL 2.1), nondeterminism (strong and strong cyclic solutions), conformant belief states, and probabilistic MDPs and POMDPs.