Classical automated planning: STRIPS, PDDL and domain-independent heuristics
A planner is a general solver: given a domain and problem description it returns a plan without domain-specific knowledge. Study STRIPS and PDDL, grounding, planning complexity, progression and regression search, and automatically derived delete-relaxation heuristics (h_max, h_add, h_FF) and landmarks underlying FF, LAMA and Fast Downward.
After this lesson you can
- Write PDDL domains and problems and explain their STRIPS semantics.
- Implement grounding with reachability pruning and heuristic progression search.
- Calculate h_max, h_add and h_FF and reason about admissibility and informativeness.
- Explain landmarks and the architecture of LAMA and Fast Downward.
- Evaluate planners using coverage, time and quality metrics.
Before you start
Motivation: a solver that knows nothing about the problem
In the search lessons you solved the 8-puzzle and 15-puzzle with A* and heuristics you designed: Manhattan distance and pattern databases. Each new problem needed a new model (states and actions) and heuristic. Automated planning reverses that division of labor. A domain-independent planner receives a declarative world description (possible facts, actions, requirements and effects) and a concrete problem (where you are and what you want), and returns an action sequence. It knows nothing about blocks, trucks or robots: everything it uses, including the heuristic, is derived automatically from the description.
This is the same bet as earlier SAT and SMT solvers: a highly optimized general engine receives a model. Here the model describes actions transforming states, and the question is how to arrive. The lesson’s central idea, explaining planners dominating the field since the late 1990s (HSP, FF, Fast Downward, LAMA), is that a good heuristic comes from solving a relaxed version of the problem the planner constructs by reading the description: relaxed problems, automated.
Today these planners are the symbolic component of many systems: they decide robot task sequences before a motion planner executes them, validate or repair plans proposed by language models (LLM-Modulo, in the topic’s last lesson), and benchmark whether an agent truly plans.
The classical model and its assumptions
This is exactly the state space of the search problem formulation. The assumptions making it “classical” are strong; each broken assumption yields another branch of the field:
- Complete knowledge: the initial state is fully known and execution needs no observation.
- Deterministic actions: each action has one outcome.
- Static world: nothing changes except through the agent’s actions.
- Reachability goals: reach a state in , not maintain a condition or maximize cumulative reward.
- Implicit time: actions are instantaneous and sequential.
Probabilistic action outcomes give a Markov decision process; if the state is also unobserved, a POMDP. The next lesson reviews other departures from the classical model (temporal planning, HTN, nondeterminism). Here we stay inside it, where ideas reused outside originate.
Intuition: a blocks-world planner
Blocks world is planning’s historic testbed: blocks on a table, an arm taking the top block from a tower and placing it on the table or another tower. Before formalizing, try a complete planner. It uses the same definitions you will implement in the lesson’s cells: states as fact sets, actions with preconditions and effects, and four heuristics calculated without knowing the domain is blocks.
Three things the figure shows and the lesson explains:
- Domain-derived heuristics work. With six blocks, blind search expands thousands of states; with , dozens. No one told the planner what “well placed” means.
- Not all are admissible. With , A* may return a longer-than-optimal plan. A* guarantees optimality only with heuristics that never overestimate; and do overestimate.
- Subgoals interfere. In Sussman’s anomaly the goal is “ on and on ”. Place on first and placing on requires undoing it; place on first and is buried under . The optimal plan interleaves subgoals. This Sussman anomaly buried the 1970s idea of planning subgoals one at a time.
STRIPS: states as sets of facts
Richard Fikes and Nils Nilsson introduced STRIPS (Stanford Research Institute Problem Solver) in 1971 for SRI’s Shakey robot. Its lasting contribution was the representation, not the search algorithm.
The induced state model has , , and , so at most states: a reasonable atom count already describes an astronomical space. Formula deletes first then adds; if an atom is in both and , addition wins, PDDL’s semantics. Below assume without loss of generality (remove from anything also added).
How STRIPS avoids the frame problem
In situation calculus describing an action also requires saying everything that does not change: the frame problem, solved by successor-state axioms. STRIPS avoids it by construction. A state is a fact database and an action an update touching only what it names: every atom in neither nor retains its value. This STRIPS assumption makes formula fit on one line.
The cost is expressive. There are no indirect effects (move a case and its contents do not move unless the action says so), no disjunction or uncertainty in state (each atom true or false), and preconditions are conjunctions of positive atoms. The following PDDL extensions relax some restrictions, almost always compiling them back to something much like STRIPS before search.
PDDL and grounding
The language
Drew McDermott and colleagues defined PDDL (Planning Domain Definition Language) in 1998 for the first international planning competition (AIPS-98); it has been the common competition format (IPC) since. It separates two files:
- The domain: types, predicates and parameterized action schemas. Reusable.
- The problem: concrete objects, initial state and goal.
Here is blocks world in PDDL, appearing again in the first cell:
(:action unstack :parameters (?x ?y)
:precondition (and (on ?x ?y) (clear ?x) (handempty))
:effect (and (holding ?x) (clear ?y)
(not (clear ?x)) (not (handempty)) (not (on ?x ?y))))
A negated atom in :effect goes to the delete list, a positive one to the add list. Beyond that STRIPS core, PDDL adds features declared in :requirements:
- Types (
:typing):?t - truckrestricts a parameter to objects of a type, with hierarchy (truck airplane - vehicle). - Equality and negative preconditions (
:equality,:negative-preconditions):(not (= ?x ?y)). - Conditional and universal effects (
:conditional-effects):(forall (?o - objeto) (when (dentro ?o) (and (en ?o ?hasta) (not (en ?o ?desde)))))moves everything in the case. They can be eliminated by splitting actions by satisfied conditions, but independent conditional effects yield actions, so good planners handle them directly. - Action costs (
:action-costs, used since IPC 2008): a functiontotal-costminimized by the metric.
Later versions (Fox and Long’s PDDL2.1, 2003, and successors) added numeric variables, durative actions and preferences, outside the classical model. Here and in cells we use the fragment formalizing STRIPS with types and equality: PDDL and its grounding, next.
Grounding: from schemas to actions
A planner searches with concrete actions, not schemas. Grounding substitutes each parameter with an object of its type. If a schema has parameters of types and are objects of type , it produces
ground actions, and without types . This is polynomial in object count but exponential in arity, yielding millions of mostly impossible actions in real domains: a truck driving between cities without a road, a package loaded on a plane that never lands at its location.
Standard pruning uses relaxed reachability: start at the initial state and add positive effects of every action whose preconditions have been reached, ignoring deletes, to a fixed point. Ground only actions firing in that process. Preconditions on static predicates (modified by no action, such as in-city or carretera) are checked against the initial state and disappear from the task.
Proof
Induction on path length. . If and is applicable in , then , so the fixed point fires and adds to ; therefore .
∎The implication is one-way: overapproximates, and useless actions survive. In blocks world without equality, needs and , never true simultaneously but separately reachable, so the fixed point retains it. Fast Downward implements this exploration as a logic program: each schema is a rule whose body is its preconditions, and the fixed point is Datalog evaluation (Helmert, 2009), using familiar seminaive techniques.
Implementation: a PDDL parser and grounder
The first cell parses a subset of PDDL (STRIPS with types and inequalities) into nested lists and then schemas.
import re
def leer_sexpr(texto):
"""Texto PDDL -> listas anidadas de símbolos (sin comentarios, en minúsculas)."""
texto = re.sub(r";[^\n]*", "", texto).lower()
pila = [[]]
for ficha in re.findall(r"[()]|[^\s()]+", texto):
if ficha == "(":
pila.append([])
elif ficha == ")":
hecho = pila.pop()
pila[-1].append(hecho)
else:
pila[-1].append(ficha)
assert len(pila) == 1, "paréntesis desequilibrados"
return pila[0][0]
def lista_tipada(xs):
"""['?x', '?y', '-', 'bloque', '?z'] -> [('?x', 'bloque'), ('?y', 'bloque'), ('?z', 'object')]"""
res, pendientes, i = [], [], 0
while i < len(xs):
if xs[i] == "-":
res += [(v, xs[i + 1]) for v in pendientes]
pendientes, i = [], i + 2
else:
pendientes.append(xs[i])
i += 1
return res + [(v, "object") for v in pendientes]
def conjuncion(e):
"""(and a (not b) ...) -> [(True, a), (False, b), ...]"""
if not e:
return []
if e[0] == "and":
return [x for sub in e[1:] for x in conjuncion(sub)]
if e[0] == "not":
return [(False, tuple(e[1]))]
return [(True, tuple(e))]
class Esquema:
def __init__(self, nombre, params, pre, efecto):
self.nombre, self.params = nombre, params
self.pre = [a for pos, a in pre if pos]
self.distintos = [(a[1], a[2]) for pos, a in pre if not pos and a[0] == "="]
assert all(pos or a[0] == "=" for pos, a in pre), "este lector solo admite (not (= ?x ?y)) como negación"
self.add = [a for pos, a in efecto if pos]
self.dele = [a for pos, a in efecto if not pos]
def leer_dominio(texto):
d = leer_sexpr(texto)
dom = {"nombre": d[1][1], "tipos": {}, "constantes": {}, "esquemas": []}
for sec in d[2:]:
if sec[0] == ":types":
dom["tipos"].update(dict(lista_tipada(sec[1:])))
elif sec[0] == ":constants":
dom["constantes"] = dict(lista_tipada(sec[1:]))
elif sec[0] == ":action":
campos = dict(zip(sec[2::2], sec[3::2]))
dom["esquemas"].append(Esquema(sec[1], lista_tipada(campos.get(":parameters", [])),
conjuncion(campos.get(":precondition", [])),
conjuncion(campos.get(":effect", []))))
return dom
def leer_problema(texto):
p = leer_sexpr(texto)
prob = {"objetos": {}, "init": set(), "meta": []}
for sec in p[2:]:
if sec[0] == ":objects":
prob["objetos"] = dict(lista_tipada(sec[1:]))
elif sec[0] == ":init":
prob["init"] = {tuple(a) for a in sec[1:]}
elif sec[0] == ":goal":
prob["meta"] = [a for _, a in conjuncion(sec[1])]
return prob
BLOQUES = """
(define (domain blocksworld)
(:requirements :strips)
(:predicates (on ?x ?y) (ontable ?x) (clear ?x) (handempty) (holding ?x))
(:action pick-up :parameters (?x)
:precondition (and (clear ?x) (ontable ?x) (handempty))
:effect (and (not (ontable ?x)) (not (clear ?x)) (not (handempty)) (holding ?x)))
(:action put-down :parameters (?x)
:precondition (holding ?x)
:effect (and (not (holding ?x)) (clear ?x) (handempty) (ontable ?x)))
(:action stack :parameters (?x ?y)
:precondition (and (holding ?x) (clear ?y))
:effect (and (not (holding ?x)) (not (clear ?y)) (clear ?x) (handempty) (on ?x ?y)))
(:action unstack :parameters (?x ?y)
:precondition (and (on ?x ?y) (clear ?x) (handempty))
:effect (and (holding ?x) (clear ?y) (not (clear ?x)) (not (handempty)) (not (on ?x ?y)))))
"""
SUSSMAN = """
(define (problem sussman) (:domain blocksworld)
(:objects a b c)
(:init (on c a) (ontable a) (ontable b) (clear c) (clear b) (handempty))
(:goal (and (on a b) (on b c))))
"""
dom_bw = leer_dominio(BLOQUES)
for e in dom_bw["esquemas"]:
print(f"{e.nombre:9s} params={[v for v, _ in e.params]} pre={e.pre} add={e.add} del={e.dele}")
print(leer_problema(SUSSMAN))The second grounds with reachability pruning. Function casar is a Datalog-style join: traverse schema preconditions, starting with the predicate having fewest reached facts, binding variables against reached facts. Parameters absent from preconditions are enumerated by type. The cell also defines the lesson’s remaining domains (typed IPC-1998 logistics, gripper) and checks a closed-form counting model against actual grounding.
import itertools, math, random, tracemalloc
from collections import defaultdict
def objetos_de_tipo(dom, prob):
def es_subtipo(t, s):
while t != s and t in dom["tipos"]:
t = dom["tipos"][t]
return t == s or s == "object"
objs = {**dom["constantes"], **prob["objetos"]}
tipos = set(dom["tipos"]) | set(dom["tipos"].values()) | set(objs.values()) | {"object"}
return {t: sorted(o for o, to in objs.items() if es_subtipo(to, t)) for t in tipos}
def acciones_ingenuas(dom, prob):
"""Instancias de cada esquema sin ninguna poda: el producto de los dominios de sus parámetros."""
por_tipo = objetos_de_tipo(dom, prob)
return {e.nombre: math.prod(len(por_tipo[t]) for _, t in e.params) for e in dom["esquemas"]}
class Accion:
__slots__ = ("nombre", "pre", "add", "dele", "coste")
def __init__(self, nombre, pre, add, dele, coste=1):
self.nombre, self.pre, self.add, self.dele, self.coste = nombre, pre, add, dele, coste
def __repr__(self):
return self.nombre
class Tarea:
"""Tarea STRIPS instanciada: átomos, estado inicial, meta y acciones, con índices para las heurísticas."""
def __init__(self, atomos, init, meta, acciones):
self.atomos, self.init, self.meta, self.acciones = atomos, init, meta, acciones
self.consumidores = defaultdict(list) # átomo -> acciones que lo piden
self.logradores = defaultdict(list) # átomo -> acciones que lo añaden
for a in acciones:
for p in a.pre:
self.consumidores[p].append(a)
for p in a.add:
self.logradores[p].append(a)
self.sin_pre = [a for a in acciones if not a.pre]
def sustituir(atomo, b):
return tuple(b.get(x, x) for x in atomo)
def grounding(dom, prob):
"""Instancia solo las acciones alcanzables en la relajación de borrados (punto fijo al estilo Datalog)."""
por_tipo = objetos_de_tipo(dom, prob)
dinamicos = {a[0] for e in dom["esquemas"] for a in e.add + e.dele}
alcanzado = set(prob["init"])
indice = defaultdict(list) # predicado -> hechos alcanzados, en orden de llegada
for a in sorted(alcanzado):
indice[a[0]].append(a)
instancias = {}
cambio = True
while cambio:
cambio = False
for e in dom["esquemas"]:
tipo = dict(e.params)
pre = sorted(e.pre, key=lambda a: len(indice[a[0]])) # primero los predicados con menos hechos
def casar(i, b):
if i == len(pre): # parámetros que no salen en la precondición
libres = [v for v, _ in e.params if v not in b]
for vals in itertools.product(*(por_tipo[tipo[v]] for v in libres)):
yield {**b, **dict(zip(libres, vals))}
return
patron = pre[i]
for hecho in indice[patron[0]]:
nb = dict(b)
if len(hecho) == len(patron) and all(
(nb.setdefault(x, y) == y and y in por_tipo[tipo[x]]) if x.startswith("?") else x == y
for x, y in zip(patron[1:], hecho[1:])):
yield from casar(i + 1, nb)
for b in list(casar(0, {})):
if any(b[x] == b[y] for x, y in e.distintos):
continue
clave = (e.nombre,) + tuple(b[v] for v, _ in e.params)
if clave in instancias:
continue
instancias[clave] = (e, b)
for a in e.add:
g = sustituir(a, b)
if g not in alcanzado:
alcanzado.add(g); indice[g[0]].append(g); cambio = True
acciones = []
for clave, (e, b) in instancias.items():
pre = frozenset(sustituir(a, b) for a in e.pre if a[0] in dinamicos) # los estáticos ya se cumplen
add = frozenset(sustituir(a, b) for a in e.add)
dele = frozenset(sustituir(a, b) for a in e.dele) - add # si se borra y se añade, gana el añadido
acciones.append(Accion("(" + " ".join(clave) + ")", pre, add, dele))
atomos = {a for a in alcanzado if a[0] in dinamicos}
init = frozenset(a for a in prob["init"] if a[0] in dinamicos)
return Tarea(atomos, init, frozenset(prob["meta"]), acciones)
def tarea_de(dominio, problema):
dom, prob = leer_dominio(dominio), leer_problema(problema)
return dom, prob, grounding(dom, prob)
# --- generadores de problemas ---
def torres_aleatorias(bloques, rnd):
torres = []
for b in rnd.sample(bloques, len(bloques)):
i = rnd.randrange(len(torres) + 1)
if i == len(torres):
torres.append([b])
else:
torres[i].append(b)
return torres
def hechos_torres(torres):
hs = []
for t in torres:
hs += [f"(ontable {t[0]})"] + [f"(on {x} {y})" for y, x in zip(t, t[1:])] + [f"(clear {t[-1]})"]
return hs
def problema_bloques(n, semilla):
rnd = random.Random(semilla)
bs = [f"b{i}" for i in range(1, n + 1)]
ini, fin = torres_aleatorias(bs, rnd), torres_aleatorias(bs, rnd)
meta = [h for h in hechos_torres(fin) if h.startswith("(on")]
return f"""(define (problem bw-{n}-{semilla}) (:domain blocksworld) (:objects {' '.join(bs)})
(:init {' '.join(hechos_torres(ini))} (handempty)) (:goal (and {' '.join(meta)})))"""
LOGISTICA = """
(define (domain logistics)
(:requirements :strips :typing)
(:types truck airplane - vehicle package vehicle - physobj
airport location - place city place physobj - object)
(:predicates (in-city ?loc - place ?city - city) (at ?obj - physobj ?loc - place)
(in ?pkg - package ?veh - vehicle) (same-city ?a ?b - place))
(:action load-truck :parameters (?pkg - package ?truck - truck ?loc - place)
:precondition (and (at ?truck ?loc) (at ?pkg ?loc))
:effect (and (not (at ?pkg ?loc)) (in ?pkg ?truck)))
(:action load-airplane :parameters (?pkg - package ?airplane - airplane ?loc - place)
:precondition (and (at ?pkg ?loc) (at ?airplane ?loc))
:effect (and (not (at ?pkg ?loc)) (in ?pkg ?airplane)))
(:action unload-truck :parameters (?pkg - package ?truck - truck ?loc - place)
:precondition (and (at ?truck ?loc) (in ?pkg ?truck))
:effect (and (not (in ?pkg ?truck)) (at ?pkg ?loc)))
(:action unload-airplane :parameters (?pkg - package ?airplane - airplane ?loc - place)
:precondition (and (in ?pkg ?airplane) (at ?airplane ?loc))
:effect (and (not (in ?pkg ?airplane)) (at ?pkg ?loc)))
(:action drive-truck :parameters (?truck - truck ?loc-from - place ?loc-to - place ?city - city)
:precondition (and (at ?truck ?loc-from) (in-city ?loc-from ?city) (in-city ?loc-to ?city))
:effect (and (not (at ?truck ?loc-from)) (at ?truck ?loc-to)))
(:action fly-airplane :parameters (?airplane - airplane ?loc-from - airport ?loc-to - airport)
:precondition (at ?airplane ?loc-from)
:effect (and (not (at ?airplane ?loc-from)) (at ?airplane ?loc-to))))
"""
def problema_logistica(C, L, P, A, semilla):
"""C ciudades con L lugares (el primero es su aeropuerto), un camión por ciudad, P paquetes y A aviones."""
rnd = random.Random(semilla)
objs, init, lugares = [], [], []
for c in range(1, C + 1):
locs = [f"ap{c}"] + [f"l{c}-{j}" for j in range(1, L)]
objs += [f"c{c} - city", f"t{c} - truck", f"ap{c} - airport"] + [f"{l} - location" for l in locs[1:]]
init += [f"(in-city {l} c{c})" for l in locs] + [f"(same-city {l} {m})" for l in locs for m in locs]
init.append(f"(at t{c} {rnd.choice(locs)})")
lugares += locs
for a in range(1, A + 1):
objs.append(f"a{a} - airplane")
init.append(f"(at a{a} ap{rnd.randint(1, C)})")
meta = []
for p in range(1, P + 1):
o, d = rnd.sample(lugares, 2)
objs.append(f"p{p} - package")
init.append(f"(at p{p} {o})")
meta.append(f"(at p{p} {d})")
return f"""(define (problem log-{C}-{L}-{P}-{A}-{semilla}) (:domain logistics) (:objects {' '.join(objs)})
(:init {' '.join(init)}) (:goal (and {' '.join(meta)})))"""
# la misma logística con drive-truck de 3 parámetros: la relación estática same-city sustituye a ?city
LOGISTICA3 = LOGISTICA.replace(
"""(:action drive-truck :parameters (?truck - truck ?loc-from - place ?loc-to - place ?city - city)
:precondition (and (at ?truck ?loc-from) (in-city ?loc-from ?city) (in-city ?loc-to ?city))""",
"""(:action drive-truck :parameters (?truck - truck ?loc-from - place ?loc-to - place)
:precondition (and (at ?truck ?loc-from) (same-city ?loc-from ?loc-to))""")
GRIPPER = """
(define (domain gripper)
(:requirements :strips :typing)
(:types room ball gripper)
(:predicates (at-robby ?r - room) (at ?b - ball ?r - room) (free ?g - gripper) (carry ?b - ball ?g - gripper))
(:action move :parameters (?from ?to - room)
:precondition (at-robby ?from)
:effect (and (at-robby ?to) (not (at-robby ?from))))
(:action pick :parameters (?b - ball ?r - room ?g - gripper)
:precondition (and (at ?b ?r) (at-robby ?r) (free ?g))
:effect (and (carry ?b ?g) (not (at ?b ?r)) (not (free ?g))))
(:action drop :parameters (?b - ball ?r - room ?g - gripper)
:precondition (and (carry ?b ?g) (at-robby ?r))
:effect (and (at ?b ?r) (free ?g) (not (carry ?b ?g)))))
"""
def problema_gripper(n):
bolas = [f"ball{i}" for i in range(1, n + 1)]
return f"""(define (problem gripper-{n}) (:domain gripper)
(:objects rooma roomb - room left right - gripper {' '.join(bolas)} - ball)
(:init (at-robby rooma) (free left) (free right) {' '.join(f'(at {b} rooma)' for b in bolas)})
(:goal (and {' '.join(f'(at {b} roomb)' for b in bolas)})))"""
# el modelo de conteo del interactivo (C, L, P, A como en problema_logistica)
def modelo(C, L, P, A, drive4=True):
Pl = C * L
con_tipos = 2 * P * C * Pl + 2 * P * A * Pl + (C * Pl * Pl * C if drive4 else C * Pl * Pl) + A * C * C
alcanzables = 2 * P * C * L + 2 * P * A * C + C * L * L + A * C * C
return con_tipos, alcanzables
print(f"{'problema':24s}{'sin poda':>9s}{'alcanzables':>12s}{'átomos':>7s} modelo")
casos = [("bloques, 6", BLOQUES, problema_bloques(6, 2), None),
("gripper, 6 bolas", GRIPPER, problema_gripper(6), None),
("logística 2-3-3-1", LOGISTICA, problema_logistica(2, 3, 3, 1, 1), (2, 3, 3, 1, True)),
("logística 2-3-3-1, d3", LOGISTICA3, problema_logistica(2, 3, 3, 1, 1), (2, 3, 3, 1, False)),
("logística 3-4-6-2", LOGISTICA, problema_logistica(3, 4, 6, 2, 1), (3, 4, 6, 2, True)),
("logística 3-4-6-2, d3", LOGISTICA3, problema_logistica(3, 4, 6, 2, 1), (3, 4, 6, 2, False))]
for nombre, D, P, m in casos:
dom, prob, T = tarea_de(D, P)
medido = (sum(acciones_ingenuas(dom, prob).values()), len(T.acciones))
print(f"{nombre:24s}{medido[0]:>9d}{medido[1]:>12d}{len(T.atomos):>7d} {'' if m is None else modelo(*m) == medido}")
tracemalloc.start()
_, _, T = tarea_de(LOGISTICA, problema_logistica(4, 3, 10, 2, 1))
memoria = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
print(f"logística 4-3-10-2: {len(T.acciones)} acciones (modelo: {modelo(4, 3, 10, 2)[1]}), "
f"{memoria / len(T.acciones):.0f} bytes por acción según tracemalloc")In blocks world with 6 blocks nothing is pruned: all 84 actions are reachable, including 12 absurd ones like . In logistics the picture changes: with 2 cities of 3 locations, 3 packages and one plane, 70 of 256 typed instances survive; with 3 cities of 4 locations, 6 packages and 2 planes, 282 of 2034 remain. The model explains why. In the domain, drive-truck(?truck ?loc-from ?loc-to ?city) accepts any truck, any two locations and any city: with cities of locations there are instances, but a truck only drives in its city, so are reachable. With packages and planes, full counts are
and the cell confirms agreement with actual grounding for all four configurations (True). If instead of parameter ?city the domain uses static relation same-city on two locations (variant d3), drive-truck has 3 parameters and the typed count drops (2034 to 1170), but reachable count does not change: arity inflates naive grounding, not the task. The last line measures ground-task memory with tracemalloc: 605 bytes per action with this Python tuple-and-set representation in Pyodide.
With 30 cities of 10 locations, 200 packages and 10 planes, the untyped version exceeds actions and typed reaches , about 48 GiB at 605 bytes per action, while reachable actions are 252,000, about 145 MiB. This is the first common homemade-planner mistake: ground naively and exhaust memory before searching.
Semantics, validator and Sussman’s anomaly
With the task grounded, STRIPS semantics takes two lines and a planner-independent validator checks any plan. Write this first: validate every custom-planner plan before believing it (the community uses VAL, official competition validator). Search is that of early lessons with the task as state space: buscar is A* if w_g = 1 and greedy search if w_g = 0.
import heapq
def aplicar(a, s):
return (s - a.dele) | a.add
def validar(tarea, plan):
"""Comprueba un plan paso a paso: aplicabilidad de cada acción y meta al final."""
s = tarea.init
for i, a in enumerate(plan):
if not a.pre <= s:
return f"no válido: el paso {i + 1}, {a}, necesita {sorted(a.pre - s)}"
s = aplicar(a, s)
return "válido" if tarea.meta <= s else f"no válido: faltan {sorted(tarea.meta - s)}"
def sucesores(tarea, s):
for a in tarea.acciones:
if a.pre <= s:
yield a, aplicar(a, s)
INF = float("inf")
def buscar(tarea, h, w_g=1, limite=100000):
"""Mejor primero con f = w_g·g + h: A* si w_g = 1, voraz si w_g = 0. Desempate por h y por orden de llegada."""
h0 = h(tarea, tarea.init)
cola, n = [(h0, h0, 0, tarea.init)], 1
g, padre, cerrados = {tarea.init: 0}, {tarea.init: None}, set()
expandidos = 0
while cola:
_, _, _, s = heapq.heappop(cola)
if s in cerrados:
continue
if tarea.meta <= s:
plan = []
while padre[s] is not None:
s, a = padre[s]
plan.append(a)
return plan[::-1], expandidos
cerrados.add(s)
expandidos += 1
if expandidos > limite:
return None, expandidos
for a, t in sucesores(tarea, s):
gt = g[s] + a.coste
if gt < g.get(t, INF) and not (w_g == 0 and t in cerrados):
g[t], padre[t] = gt, (s, a)
cerrados.discard(t) # A* reabre si encuentra un camino mejor
ht = h(tarea, t)
if ht < INF:
n += 1
heapq.heappush(cola, (w_g * gt + ht, ht, n, t))
return None, expandidos
def ciega(tarea, s):
return 0
_, _, T_sus = tarea_de(BLOQUES, SUSSMAN)
plan, exp = buscar(T_sus, ciega)
print(f"Sussman: {len(T_sus.acciones)} acciones, plan óptimo de {len(plan)} pasos tras {exp} expansiones:")
print(" ", plan, "->", validar(T_sus, plan))
# el plan «por submetas»: primero on(a, b), después on(b, c)
nombre = {a.nombre: a for a in T_sus.acciones}
ingenuo = [nombre[x] for x in ["(unstack c a)", "(put-down c)", "(pick-up a)", "(stack a b)", "(pick-up b)", "(stack b c)"]]
print(" plan por submetas ->", validar(T_sus, ingenuo))The anomaly’s optimal plan has 6 steps and the validator accepts it. The “by subgoals” plan (first with its four actions and then ) fails at step five: picking up requires it to be clear, and is on top. The validator says not just that the plan is bad, but where and why, as needed to debug a domain.
Complexity: why there are no shortcuts
Call PLANSAT the problem of deciding whether a propositional (already grounded) STRIPS task has a plan, and PLANMIN whether one has cost at most .
Proof
We prove the first claim; the other two are from the same paper.
Membership. A nondeterministic algorithm guesses a plan action by action, storing only current state ( bits) and a step counter cutting off at , since a longer plan repeats a state and can be shortened. This uses polynomial space, so PLANSAT is in NPSPACE, which is PSPACE by Savitch’s theorem (space classes).
Hardness (sketch). Given a deterministic Turing machine using space and input , construct a task with one atom each for “cell contains symbol ”, “head is at ” and “machine is in state ”, an operator per transition and position (preconditions: head at , state , symbol in ; effects: write, move and change state, deleting prior values), and goal “accepting state”. The task is polynomial in and has a plan if and only if the machine accepts .
∎Notice what membership does not claim: that a plan is a short certificate. It need not be, because some tasks’ shortest plans are exponentially long. STRIPS Towers of Hanoi demonstrate this: the next cell generates disks and blind search finds optimal plans of steps, while atoms grow as .
HANOI = """
(define (domain hanoi)
(:requirements :strips)
(:predicates (clear ?x) (on ?x ?y) (smaller ?x ?y))
(:action move :parameters (?disc ?from ?to)
:precondition (and (smaller ?to ?disc) (on ?disc ?from) (clear ?disc) (clear ?to))
:effect (and (clear ?from) (on ?disc ?to) (not (on ?disc ?from)) (not (clear ?to)))))
"""
def problema_hanoi(n):
discos, postes = [f"d{i}" for i in range(1, n + 1)], ["p1", "p2", "p3"] # d1 es el más pequeño
debajo = discos[1:] + ["p1"]
init = ["(clear p2)", "(clear p3)", "(clear d1)"] + [f"(on {d} {x})" for d, x in zip(discos, debajo)]
init += [f"(smaller {x} {d})" for i, d in enumerate(discos) for x in postes + discos[i + 1:]]
meta = [f"(on {d} {x})" for d, x in zip(discos, discos[1:] + ["p3"])]
return f"""(define (problem hanoi-{n}) (:domain hanoi) (:objects {' '.join(postes + discos)})
(:init {' '.join(init)}) (:goal (and {' '.join(meta)})))"""
for n in range(1, 7):
_, _, T = tarea_de(HANOI, problema_hanoi(n))
plan, exp = buscar(T, ciega)
print(f"{n} discos: {len(T.atomos):3d} átomos, {len(T.acciones):3d} acciones, plan óptimo de {len(plan):2d} = 2^{n} - 1 pasos, {exp} expansiones")With 6 disks there are only 42 atoms and 199 actions, yet the optimal plan has 63 steps; with 30 disks it would exceed a billion. An NP problem has polynomial-size certificates, so PLANSAT cannot be placed in NP via the obvious “plan as certificate” route (and if it were in NP by any route, NP = PSPACE, since it is PSPACE-complete).
Other results defining tractability recur shortly:
- Without deletes, plan existence is easy: the relaxed-reachability fixed point suffices and is polynomial.
- Without deletes, an optimal plan is NP-hard (Bylander, 1994): the relaxation section proves this by reduction from set cover.
- In blocks world, finding a plan is trivial (put everything on the table and build goal towers), but an optimal plan is NP-hard (Gupta and Nau, 1992). This general pattern appears in competition domains: existence is often easy and optimality hard.
Worst-case PSPACE-complete does not mean impossible in practice. Real domains have structure, and the rest of the lesson shows how heuristics exploit it.
Progression and regression
There are two ways to traverse the space. Progression is the earlier lessons’ forward search: from , successors of are with applicable, and the goal is checked with . Regression searches backward from the goal, not in full states but subgoals: sets of atoms required true.
Progression and regression planning relies on a result justifying the formula.
Proof
() , so is applicable. Let . If , it is in . Otherwise , and since by consistency, it survives: .
() by applicability. If and , it must be in .
If , since we assume , for any .
∎Relevance is unnecessary for correctness, only to avoid wasted effort: if adds nothing to , is a harder subgoal than the original. Consistency is essential; forgetting it produces nonworking plans (an exercise asks you to find the mistake).
Impossible subgoals
Regression’s weakness is that many subgoals correspond to no reachable state. The cell regresses Sussman’s goal through and then , checking a domain invariant: the arm holds at most one block.
def regresar(g, a):
"""Submeta que debe cumplirse justo antes de a para que después se cumpla g (None si a no sirve)."""
if not (a.add & g): # relevante: aporta algo a g
return None
if a.dele & g: # consistente: no destruye nada de g
return None
return (g - a.add) | a.pre
def mutex_brazo(g):
"""Invariante del mundo de bloques: el brazo sostiene como mucho un bloque y, si sostiene, no está libre."""
sostenidos = [p for p in g if p[0] == "holding"]
return len(sostenidos) > 1 or (sostenidos and ("handempty",) in g)
g = T_sus.meta
print("meta:", sorted(g))
for paso in ["(stack a b)", "(stack b c)"]:
g = regresar(g, nombre[paso])
print(f" regresada por {paso}: {sorted(g)} ¿viola el invariante? {bool(mutex_brazo(g))}")The second subgoal requires holding and simultaneously. Regression is correct (if such a state existed, the suffix would work), but no reachable state satisfies it, and backward search may spend much time exploring such subgoals. Detecting them requires invariants or mutexes (atom pairs never simultaneously true), computed by next lesson’s Graphplan planning graph.
Regression has a compensating advantage for the heuristics studied next: every subgoal is evaluated relative to the same initial state, so each atom’s cost is computed once and each subgoal estimated by summing or maximizing. Bonet and Geffner (2001) exploit this in HSPr. Progression pays a full evaluation per state, but its states are real; nearly all modern planners (FF, Fast Downward, LAMA) progress.
Delete relaxation
All the power of this lesson’s heuristics comes from one idea: forget delete lists.
In atoms only accumulate: once true, always true. This is exactly analogous to Manhattan distance relaxing the 15-puzzle by allowing tiles to pass through each other: a truck driving from A to B also remains at A, and a gripper holding a ball remains free.
Proof
First, monotonicity of : if and is applicable in from , it is also applicable from , and the final state from contains that from . By induction: first-action preconditions are in , and afterward both states grow with the same , preserving inclusion.
Admissibility. Let be a real plan from , with real states and relaxed states . By induction : true for , and if , is applicable in and . Thus and is a relaxed plan: . Taking optimal yields .
Consistency. If is an optimal relaxed plan from , then is a relaxed plan from : applying in reaches , and monotonicity keeps working. Therefore .
∎Consistency means A* with finds optimal plans without reopening nodes (see consistent heuristics). Two more properties make manageable:
- Deciding relaxed-plan existence is polynomial. It is the reachability fixed point: if and only if the goal is not reached from ignoring deletes. Since , then no real plan exists either: relaxation safely detects dead ends (not all, as shown later).
- A relaxed plan never needs to repeat an action, since its second application adds nothing: an optimal one has at most actions.
But computing is costly.
Proof
In NP: a certificate is a set of at most actions; polynomial time checks that, applied in reachability fixed-point order, they reach .
NP-hard, by reduction from set cover (given universe , subsets and , are there subsets whose union is ?), which is NP-complete. Take , , and, for each , operator without preconditions, and cost 1. A set of operators is a relaxed plan if and only if its cover , so if and only if a cover of size exists. Construction is linear.
∎The reduction task has no deletes, so the same argument proves optimal planning without deletes NP-hard. Practical heuristics are therefore polynomial-time approximations of : from below (, LM-cut), above (, ) or with a particular relaxed plan ().
and : Bellman–Ford over atoms
The most direct approximation of estimates each atom’s cost separately and combines them. First look at the graph.
The and heuristics assign each atom an estimated cost to reach it from , defined by equations
where a set of atoms costs their maximum or sum:
with and . State heuristic is goal cost: and .
These are shortest-path equations on a hypergraph: an action can be “used” only when all preconditions are reached. Solve as in Bellman–Ford: start at for atoms in and for others, relax all actions on each sweep using prior-sweep values until nothing changes. Values only decrease and, with positive costs, each atom’s best supporter has strictly lower-valued preconditions, so after sweeps all atoms with supporter-chain depth are exact: at most sweeps, each costing . Practice uses generalized Dijkstra (Knuth, 1977): a priority queue of atoms and a pending-precondition counter per action, so each action fires once, after all preconditions are known.
REPARTO = """
(define (domain reparto)
(:requirements :strips :typing)
(:types lugar camion paquete)
(:predicates (carretera ?a ?b - lugar) (en ?t - camion ?l - lugar)
(esta ?p - paquete ?l - lugar) (dentro ?p - paquete ?t - camion))
(:action conducir :parameters (?t - camion ?a ?b - lugar)
:precondition (and (en ?t ?a) (carretera ?a ?b))
:effect (and (en ?t ?b) (not (en ?t ?a))))
(:action cargar :parameters (?p - paquete ?t - camion ?l - lugar)
:precondition (and (en ?t ?l) (esta ?p ?l))
:effect (and (dentro ?p ?t) (not (esta ?p ?l))))
(:action descargar :parameters (?p - paquete ?t - camion ?l - lugar)
:precondition (and (en ?t ?l) (dentro ?p ?t))
:effect (and (esta ?p ?l) (not (dentro ?p ?t)))))
"""
def problema_reparto(volver=False):
meta = "(esta p1 c) (esta p2 c)" + (" (en t a)" if volver else "")
return f"""(define (problem reparto) (:domain reparto)
(:objects a b c - lugar t - camion p1 p2 - paquete)
(:init (en t a) (esta p1 a) (esta p2 b) (carretera a b) (carretera b a) (carretera b c) (carretera c b))
(:goal (and {meta})))"""
def h_punto_fijo(tarea, s, combinar):
"""Definición literal: barridas al estilo Bellman-Ford hasta que nada cambia."""
coste = {p: (0 if p in s else INF) for p in tarea.atomos}
barridas = 0
while True:
barridas += 1
nuevo = dict(coste) # cada barrida lee solo los valores de la anterior
for a in tarea.acciones:
c = a.coste + combinar([coste[q] for q in a.pre] or [0])
for q in a.add:
nuevo[q] = min(nuevo[q], c)
cambio, coste = nuevo != coste, nuevo
if not cambio:
return combinar([coste[g] for g in tarea.meta]), coste, barridas
def costes_relajados(tarea, s, combinar):
"""Lo mismo con un Dijkstra generalizado: cada acción se dispara una vez, cuando ya conoce todas sus precondiciones."""
coste = {p: 0 for p in s}
cola = [(0, p) for p in s]
heapq.heapify(cola)
faltan = {a: len(a.pre) for a in tarea.acciones}
acum = defaultdict(int) # máximo o suma de los costes de las precondiciones ya fijadas
mejor, fijados = {}, set()
def disparar(a):
c = a.coste + acum[a]
for q in a.add:
if c < coste.get(q, INF):
coste[q], mejor[q] = c, a
heapq.heappush(cola, (c, q))
for a in tarea.sin_pre:
disparar(a)
while cola:
c, p = heapq.heappop(cola)
if p in fijados:
continue
fijados.add(p)
for a in tarea.consumidores[p]:
acum[a] = combinar((acum[a], c))
faltan[a] -= 1
if faltan[a] == 0:
disparar(a)
h = combinar([coste.get(g, INF) for g in tarea.meta])
return h, coste, mejor
def h_max(tarea, s):
return costes_relajados(tarea, s, max)[0]
def h_add(tarea, s):
return costes_relajados(tarea, s, sum)[0]
_, _, T_rep = tarea_de(REPARTO, problema_reparto())
for nombre_h, comb in [("h_max", max), ("h_add", sum)]:
hf, cf, barridas = h_punto_fijo(T_rep, T_rep.init, comb)
hd, cd, _ = costes_relajados(T_rep, T_rep.init, comb)
assert all(cf[p] == cd.get(p, INF) for p in T_rep.atomos)
print(f"{nombre_h} = {hd} (punto fijo en {barridas} barridas, la última sin cambios; Dijkstra da los mismos costes)")
print(" ", ", ".join(f"{' '.join(p)}: {cd[p]}" for p in sorted(cd)))
# las dos implementaciones coinciden también en estados de otros dominios
rnd, comprobados = random.Random(0), 0
for D, P in [(BLOQUES, problema_bloques(6, 2)), (GRIPPER, problema_gripper(4)), (LOGISTICA, problema_logistica(2, 3, 3, 1, 2))]:
_, _, T = tarea_de(D, P)
s = T.init
for _ in range(30):
for comb in (max, sum):
assert h_punto_fijo(T, s, comb)[0] == costes_relajados(T, s, comb)[0]
comprobados += 1
s = rnd.choice([t for _, t in sucesores(T, s)])
print(f"{comprobados} estados de paseos aleatorios: punto fijo y Dijkstra coinciden")With sweeps reading only prior values, delivery reaches the fixed point on the third and the fourth confirms it; the figure’s slider follows exactly those sweeps. Both methods yield identical costs in delivery and 90 random-walk states from three other domains. Notice values: because it adds (2: drive to B and load) and (2: drive to B and C), counting A-to-B twice in one subgoal. Adding , A→B appears three times and B→C twice, while the optimal plan uses each once: for any positive action costs, in this problem. Thus no cost change in the figure makes stop overestimating.
You prove the first inequality in the guided exercise (idea: any relaxed plan achieving an atom costs at least that atom’s ). The second is ‘s admissibility. The third follows by induction over sweeps because the maximum of nonnegative values never exceeds their sum. Interpretation matters:
- assumes achieving the costliest subgoal achieves all others for free. It is admissible but weak: in gripper it is 2 whether there are 4 balls or 400.
- assumes subgoals independent and adds their costs. It is much more informative but counts shared actions repeatedly. In delivery, while optimum is 6.
is member of Haslum and Geffner’s (2000) family, estimating costs of sets of up to atoms; captures pairwise interactions at higher-degree polynomial cost. is the heuristic with which Bonet and Geffner’s HSP (2001) showed heuristic search with automatic heuristics competing with the best planners of its time.
FF: relaxed plans and enforced hill-climbing
overestimates because it builds no plan, only sums estimates. FF’s heuristic (Hoffmann and Nebel, 2001) builds a concrete relaxed plan in which each shared action counts once.
Relaxed planning graph and backward extraction
The relaxed planning graph from alternates atom and action layers: ; are actions applicable in ; . Stop when or two layers coincide (then ). Each atom’s first layer is its with unit costs: the previous figure’s structure.
FF extraction traverses the graph backward. Put each goal atom in its first layer; from the highest layer, for each pending subgoal in layer choose an achieving action from , preferring easiest preconditions, and add them as subgoals in their own layers; subgoals already achieved by a chosen action are satisfied. The chosen action count is . With costs, Fast Downward does the same with each atom’s best supporter according to (the action attaining its equation’s minimum): start with goals, take each missing atom’s best supporter and repeat for preconditions. We implement that version.
With positive costs, sorting actions in by the of what they support yields a valid relaxed plan, so . Also : expanding equations from the goal, each required atom appears at least once with its best supporter’s cost; sums every occurrence and counts each action once. FF’s abstract says its heuristic, unlike HSP’s, does not assume facts independent.
is not admissible either. If each of three goals is achieved by its own cost-1 action , or all together by cost-1 action requiring atom produced by another cost-1 action, by and the relaxed plan is : , while optimum is 2.
The cell computes exactly (A* and on , viable only for small tasks) and compares the whole chain.
def plan_relajado(tarea, s):
"""Extracción hacia atrás con el mejor soporte de cada átomo según h_add (la variante de Fast Downward)."""
h, coste, mejor = costes_relajados(tarea, s, sum)
if h == INF:
return None
plan, vistos, pila = set(), set(), sorted(tarea.meta)
while pila:
p = pila.pop()
if p in s or p in vistos:
continue
vistos.add(p)
a = mejor[p]
if a not in plan:
plan.add(a)
pila.extend(sorted(a.pre))
return plan
def h_ff(tarea, s):
rp = plan_relajado(tarea, s)
return INF if rp is None else sum(a.coste for a in rp)
def h_mas(tarea, s):
"""h+ exacta: A* con h_max sobre la tarea sin borrados (solo para tareas pequeñas: es NP-difícil)."""
relajada = Tarea(tarea.atomos, s, tarea.meta, [Accion(a.nombre, a.pre, a.add, frozenset(), a.coste) for a in tarea.acciones])
plan, _ = buscar(relajada, h_max)
return INF if plan is None else sum(a.coste for a in plan)
def h_estrella(tarea):
plan, _ = buscar(tarea, ciega)
return INF if plan is None else sum(a.coste for a in plan)
print(f"{'problema':22s}{'h_max':>6s}{'h+':>5s}{'h_FF':>6s}{'h_add':>7s}{'h*':>5s}")
for nombre_p, D, P in [("reparto", REPARTO, problema_reparto()), ("reparto y volver", REPARTO, problema_reparto(True)),
("gripper, 4 bolas", GRIPPER, problema_gripper(4)), ("bloques, 5", BLOQUES, problema_bloques(5, 4)),
("logística 2-3-3-1", LOGISTICA, problema_logistica(2, 3, 3, 1, 2))]:
_, _, T = tarea_de(D, P)
s = T.init
print(f"{nombre_p:22s}{h_max(T, s):>6}{h_mas(T, s):>5}{h_ff(T, s):>6}{h_add(T, s):>7}{h_estrella(T):>5}")
print("plan relajado del reparto:", sorted(plan_relajado(T_rep, T_rep.init), key=str))
# A* con una heurística no admisible no garantiza el óptimo
_, _, T_g4 = tarea_de(GRIPPER, problema_gripper(4))
for nombre_h, h in [("h_max", h_max), ("h_add", h_add), ("h_FF", h_ff)]:
plan, exp = buscar(T_g4, h)
print(f"gripper, 4 bolas, A* con {nombre_h}: plan de {len(plan)} pasos ({exp} expansiones); el óptimo tiene {h_estrella(T_g4)}")All five rows satisfy , and in these tasks the FF relaxed plan is also optimal (), not guaranteed. Comparisons with are interesting:
- In gripper with 4 balls, : under relaxation a gripper remains free after picking up a ball, so the robot carries all four in one trip without returning. And genuinely overestimates.
- In “deliver and return”, and : goal is true initially and relaxation never deletes it, so return is free. The prior figure’s switch shows this.
- With A* on gripper with 4 balls, and return the optimal 11-step plan, but returns 13. A* with an inadmissible heuristic remains correct but is no longer optimal.
Helpful actions and enforced hill-climbing
FF does more than count its relaxed plan. Helpful actions are those applicable in achieving a first-layer relaxed-plan subgoal: actions the relaxed plan would “start” with. Fast Downward uses similar preferred operators: relaxed-plan actions applicable in . Restricting search to them prunes most successors.
FF’s search is enforced hill-climbing (EHC), a hill-climbing variant: from the current state, breadth-first search (helpful actions only) until finding a state with strictly lower ; jump there, discard the rest and repeat. Breadth-first search crosses plateaus instead of random steps. EHC is incomplete for two reasons: helpful-action pruning can remove every solution, and committing to a better state can enter a dead end relaxation misses. When EHC fails, FF restarts a complete greedy search with .
from collections import deque
def utiles(tarea, s):
"""Acciones del plan relajado aplicables ya en s (los «operadores preferidos» de Fast Downward)."""
rp = plan_relajado(tarea, s)
return {a for a in rp if a.pre <= s} if rp else set()
def ehc(tarea, h=h_ff, solo_utiles=True, limite=50000):
"""Enforced hill-climbing de FF: desde el estado actual, anchura hasta encontrar uno con h estrictamente menor."""
s, hs, plan, evaluados = tarea.init, h(tarea, tarea.init), [], 1
while hs > 0:
frontera, vistos, salto = deque([(s, [])]), {s}, None
while frontera and salto is None:
u, camino = frontera.popleft()
permitidas = utiles(tarea, u) if solo_utiles else None
for a, t in sucesores(tarea, u):
if (permitidas is not None and a not in permitidas) or t in vistos:
continue
vistos.add(t)
ht, evaluados = h(tarea, t), evaluados + 1
if ht < hs:
salto = (t, camino + [a], ht)
break
frontera.append((t, camino + [a]))
if evaluados > limite:
return None, evaluados
if salto is None:
return None, evaluados # sin salida: FF recurre aquí a una búsqueda mejor primero completa
s, tramo, hs = salto
plan += tramo
return plan, evaluados
for nombre_p, D, P in [("gripper, 6 bolas", GRIPPER, problema_gripper(6)), ("bloques, 7", BLOQUES, problema_bloques(7, 3)),
("logística 2-3-3-1", LOGISTICA, problema_logistica(2, 3, 3, 1, 2))]:
_, _, T = tarea_de(D, P)
print(f"{nombre_p}: {len(utiles(T, T.init))} acciones útiles de {sum(1 for _ in sucesores(T, T.init))} aplicables al principio")
for etiqueta, kw in [("solo útiles", {}), ("todas", {"solo_utiles": False})]:
plan, ev = ehc(T, **kw)
print(f" EHC, {etiqueta:12s} plan de {len(plan)} pasos, {ev:4d} estados evaluados, {validar(T, plan)}")
# en Hanoi, la poda por acciones útiles deja a EHC sin ningún estado mejor al alcance
_, _, T = tarea_de(HANOI, problema_hanoi(5))
for etiqueta, kw in [("solo útiles", {}), ("todas", {"solo_utiles": False})]:
plan, ev = ehc(T, **kw)
print(f"hanoi, 5 discos, EHC, {etiqueta:12s}", "sin plan" if plan is None else f"plan de {len(plan)} pasos", f"({ev} estados evaluados)")
# un callejón sin salida que la relajación no ve: la llave se gasta y salir de casa es irreversible
LLAVE = """
(define (domain llave)
(:predicates (llave) (casa) (fuera) (abierta1) (abierta2))
(:action usar1 :parameters () :precondition (llave) :effect (and (abierta1) (not (llave))))
(:action usar2 :parameters () :precondition (llave) :effect (and (abierta2) (not (llave))))
(:action salir :parameters () :precondition (casa) :effect (and (fuera) (not (casa))))
(:action coger-llave :parameters () :precondition (casa) :effect (llave)))
"""
PUERTAS = "(define (problem puertas) (:domain llave) (:init (llave) (casa)) (:goal (and (abierta1) (abierta2) (fuera))))"
_, _, T_ll = tarea_de(LLAVE, PUERTAS)
salir = next(a for a in T_ll.acciones if a.nombre == "(salir)")
s1 = aplicar(salir, T_ll.init)
print()
print(f"llave: h_FF(inicio) = {h_ff(T_ll, T_ll.init)}, h_FF(tras salir) = {h_ff(T_ll, s1)}, "
f"h* tras salir = {h_estrella(Tarea(T_ll.atomos, s1, T_ll.meta, T_ll.acciones))}")
print(" EHC:", ehc(T_ll)[0], " voraz con h_FF:", buscar(T_ll, h_ff, w_g=0)[0])With only helpful actions, EHC evaluates 38 states instead of 62 in gripper, 25 instead of 221 in blocks world and 86 instead of 182 in logistics, with identical plans. Pruning has a price: in 5-disk Hanoi, helpful-only EHC runs out of reachable better states after evaluating 22, while all-action EHC finds a 31-step plan. The final example is a designed dead end: two doors need opening with a consumed key and another key can only be picked up at home. Leaving home lowers from 3 to 2 (relaxation does not consume the key) but leaves the task unsolvable (). EHC jumps there and cannot escape; greedy search retains its frontier, backtracks and finds the 4-step plan.
Landmarks, LAMA and Fast Downward
What every plan must do
Delivering a package to C requires loading it sometime, and the truck must first have been at its location. These facts occur in every plan, and counting them gives another heuristic.
Landmarks were introduced by Porteous, Sebastia and Hoffmann in 2001; their journal version (Hoffmann, Porteous and Sebastia, 2004) proves deciding whether an atom is a landmark PSPACE-complete: as hard as planning. But a cheap sufficient condition exists.
Proof
Suppose a plan of in which is never true. Then uses no action adding (after it would be true), so it is a plan of without those actions and, by relaxation’s admissibility, a relaxed plan of that reduced task. Contradiction.
∎Our extraction uses Hoffmann, Porteous and Sebastia’s backward chaining: goals are landmarks; for each landmark not initially true, calculate its first achievers (actions adding and applicable in relaxation before is achieved, i.e. without any achiever of ), and any precondition common to all is a landmark greedy-necessarily ordered before . Repeat with new landmarks until none appear.
LAMA’s landmark-count heuristic tracks progress along the path: a landmark is accepted when it becomes true and all graph predecessors are already accepted; an accepted one is needed again if false now and a goal or greedy predecessor of an unaccepted one. With landmarks,
It depends on path reaching , not just . It is inadmissible: if one action achieves two landmarks at once (two goals with one action, as in ‘s counterexample), count is 2 and plan cost 1.
def alcanzables_sin(tarea, s, prohibidas):
"""Átomos alcanzables en la relajación de borrados sin usar las acciones prohibidas."""
R, cambio = set(s), True
while cambio:
cambio = False
for a in tarea.acciones:
if a not in prohibidas and a.pre <= R and not a.add <= R:
R |= a.add
cambio = True
return R
def es_landmark(tarea, p):
"""Condición suficiente: sin las acciones que añaden p, la relajación ya no alcanza la meta."""
return p in tarea.init or not tarea.meta <= alcanzables_sin(tarea, tarea.init, set(tarea.logradores[p]))
def landmarks(tarea):
"""Hacia atrás desde la meta: las precondiciones comunes a todos los primeros logradores son landmarks."""
lms, ordenes, pendientes = set(tarea.meta), set(), sorted(tarea.meta)
while pendientes:
p = pendientes.pop()
if p in tarea.init:
continue
logr = tarea.logradores[p]
R = alcanzables_sin(tarea, tarea.init, set(logr))
primeros = [a for a in logr if a.pre <= R] # pueden ser los que logran p por primera vez
if not primeros:
continue
for q in sorted(frozenset.intersection(*(a.pre for a in primeros))):
ordenes.add((q, p)) # q es cierto justo antes de lograr p por primera vez
if q not in lms:
lms.add(q)
pendientes.append(q)
return lms, ordenes
def aceptar(lms, ordenes, aceptados, s):
"""Un landmark se acepta cuando es cierto y todos sus predecesores ya estaban aceptados."""
nuevos = set(aceptados)
for L in lms - aceptados:
if L in s and all(q in aceptados for q, p in ordenes if p == L):
nuevos.add(L)
return frozenset(nuevos)
def h_lm(tarea, lms, ordenes, aceptados, s):
"""Recuento de LAMA: los que faltan más los aceptados que hacen falta otra vez."""
otra_vez = {L for L in aceptados if L not in s and
(L in tarea.meta or any(q == L and p not in aceptados for q, p in ordenes))}
return len(lms) - len(aceptados) + len(otra_vez)
_, _, T_rv = tarea_de(REPARTO, problema_reparto(volver=True))
lms, ordenes = landmarks(T_rv)
print(f"reparto y volver: {len(lms)} landmarks")
print(" ", ", ".join(" ".join(p) for p in sorted(lms)))
print(" órdenes:", ", ".join(f"{' '.join(q)} < {' '.join(p)}" for q, p in sorted(ordenes)))
assert all(es_landmark(T_rv, p) for p in lms)
plan, _ = buscar(T_rv, ciega)
s, acc = T_rv.init, aceptar(lms, ordenes, frozenset(), T_rv.init)
valores = [h_lm(T_rv, lms, ordenes, acc, s)]
for a in plan:
s = aplicar(a, s)
acc = aceptar(lms, ordenes, acc, s)
valores.append(h_lm(T_rv, lms, ordenes, acc, s))
print(" h_LM a lo largo del plan óptimo:", valores, " (h* restante:", list(range(len(plan), -1, -1)), ")")
def voraz_lm(tarea, limite=100000):
"""Búsqueda voraz con h_LM: la heurística depende del camino, así que cada nodo guarda sus aceptados."""
lms, ordenes = landmarks(tarea)
acc0 = aceptar(lms, ordenes, frozenset(), tarea.init)
cola = [(h_lm(tarea, lms, ordenes, acc0, tarea.init), 0, tarea.init, acc0)]
padre, cerrados, n = {tarea.init: None}, set(), 0
while cola:
_, _, s, acc = heapq.heappop(cola)
if s in cerrados:
continue
if tarea.meta <= s:
plan = []
while padre[s] is not None:
s, a = padre[s]
plan.append(a)
return plan[::-1], len(cerrados)
cerrados.add(s)
if len(cerrados) > limite:
return None, len(cerrados)
for a, t in sucesores(tarea, s):
if t not in padre:
padre[t] = (s, a)
acc_t = aceptar(lms, ordenes, acc, t)
n += 1
heapq.heappush(cola, (h_lm(tarea, lms, ordenes, acc_t, t), n, t, acc_t))
return None, len(cerrados)
# SAS+: en el reparto, las 11 variables binarias de STRIPS son 3 variables multivaluadas
vistos, pila = {T_rep.init}, [T_rep.init]
while pila:
for _, t in sucesores(T_rep, pila.pop()):
if t not in vistos:
vistos.add(t); pila.append(t)
print(f"reparto: {len(T_rep.atomos)} átomos, 2^{len(T_rep.atomos)} = {2 ** len(T_rep.atomos)} conjuntos posibles, "
f"{len(vistos)} estados alcanzables = 3 · 4 · 4 valores de (camión, p1, p2)")
for nombre_p, D, P in [("gripper, 6 bolas", GRIPPER, problema_gripper(6)), ("bloques, 7", BLOQUES, problema_bloques(7, 3)),
("logística 2-3-3-1", LOGISTICA, problema_logistica(2, 3, 3, 1, 2))]:
_, _, T = tarea_de(D, P)
plan, exp = voraz_lm(T)
print(f"{nombre_p}: {len(landmarks(T)[0])} landmarks; voraz con h_LM: plan de {len(plan)} pasos, {exp} expansiones, {validar(T, plan)}")In “deliver and return” there are 9 landmarks (3 initial facts, of which is also a goal, 2 other goals, two “inside truck” facts, and passing B and C) and 10 orderings, as shown. Along the optimal plan is 6, 5, 5, 4, 3, 2, 1, 1, 0 while actual remaining cost is 8, 7, …, 0: it never exceeds it here, and stalls twice, when the truck leaves A (goal becomes needed again) and on the return at the end, achieving no new landmark. Greedy search with solves three test problems with expansions of the same order as ; alone it is weaker, so LAMA combines it with FF.
For optimal planning, landmarks yield admissible heuristics by partitioning each action’s cost among achieved landmarks (Karpas and Domshlak, 2009). The most used is LM-cut (Helmert and Domshlak, 2009): compute , take the action justifying each atom’s , find a cut between state and goal in that justification graph, whose crossing actions form a disjunctive landmark; add minimum cut cost , subtract from those actions and repeat until the goal’s is 0. The result satisfies , and A* with LM-cut has been the optimal-planning benchmark for years.
Fast Downward and SAS+ representation
Fast Downward (Helmert, 2006) won IPC 2004’s classical category and is now a leading classical-planning research platform. Its architecture has three phases:
- Translation. Ground PDDL with the Datalog exploration already seen and, above all, find mutex groups by invariant synthesis: atom sets with at most one true in any reachable state (truck at A, B or C). Each group becomes a multivalued variable, adding a “none” value if no atom may be true. The result is a SAS+ task: variables with finite domains , states as complete assignments and actions with preconditions and effects as partial assignments.
- Knowledge compilation. Causal graph between variables, per-variable transition graphs and structures for fast successor generation.
- Search. Greedy search or A* with multiple heuristics and techniques: multiple alternating open queues (one per heuristic and, with preferred operators, another per heuristic containing only their successors), and lazy evaluation, computing when expanding rather than generating a node, giving children the parent’s as provisional priority, saving most evaluations with large branching factors.
SAS+ changes reachable-state description, not the space. In the relaxed-graph delivery, STRIPS has 11 atoms (thus possible sets), while SAS+ has 3 variables: the truck with 3 values and each package with 4 (three locations or truck). There are states, and the previous cell checks all 48 reachable. Compact representation makes regression’s needed invariants explicit and underlies causal-graph and abstraction heuristics.
LAMA (Richter and Westphal, 2010) is Fast Downward with two heuristics, and , alternating separate queues, preferred operators from both and lazy evaluation. It is anytime: Fast Downward configuration seq-sat-lama-2011 first runs greedy search and, once it has a plan, restarts with weighted A* at weights 5, 3, 2 and 1, pruning by best-known plan cost until time runs out. The paper’s abstract says LAMA led IPC 2008 sequential satisficing, landmarks improved performance and accounting for action costs in heuristics did not help (ignoring them solved considerably more tasks in some domains), while iterative search greatly improved plan quality.
Evaluating planners
A planner is measured with three numbers over the same tasks and equal time and memory limits:
- Coverage: tasks solved within limits. Main metric in optimal planning.
- Quality: at IPC 2008 each solved task scored , best-known plan cost divided by obtained plan cost (0 if unsolved), with 30 minutes and 2 GB per task and 30 tasks per domain. Summing by domain rewards coverage and quality.
- Time: to first plan, logarithmic scale, because planning times span orders of magnitude.
Three methodological cautions: results vary strongly across domains, so report by domain with many different domains. Quality score depends on the reference (best-known plan), and changes when a better one is found. Coverage depends on limits: comparing an hour for one planner to ten seconds for another measures nothing. For serious Fast Downward experiments, Downward Lab runs configurations, collects results and generates tables.
A browser benchmark
The next two cells run every lesson configuration on seven tasks from four domains, with the same limit of 1000 expanded states (1000 evaluated states for EHC). The limit is small to fit Pyodide; the pattern matters.
import time
banco = [("bw-7", BLOQUES, problema_bloques(7, 3)), ("bw-9", BLOQUES, problema_bloques(9, 5)),
("grip-6", GRIPPER, problema_gripper(6)), ("grip-8", GRIPPER, problema_gripper(8)),
("log-2331", LOGISTICA, problema_logistica(2, 3, 3, 1, 2)), ("log-2341", LOGISTICA, problema_logistica(2, 3, 4, 1, 4)),
("hanoi-5", HANOI, problema_hanoi(5))]
tareas = [(n, tarea_de(D, P)[2]) for n, D, P in banco]
LIM = 1000 # límite común: estados expandidos (en EHC, estados evaluados)
res = {}
def correr(nombre_c, f):
for tn, T in tareas:
t0 = time.perf_counter()
plan, trabajo = f(T)
ok = plan is not None and validar(T, plan) == "válido"
res[nombre_c, tn] = (len(plan) if ok else None, trabajo, time.perf_counter() - t0)
def tabla(nombres):
print(f"{'':12s}" + "".join(f"{tn:>10s}" for tn, _ in tareas) + " cobertura")
for cn in nombres:
celdas = [res[cn, tn] for tn, _ in tareas]
print(f"{cn:12s}" + "".join(f"{(str(r[0]) if r[0] else '-'):>4s}/{r[1]:<5d}" for r in celdas)
+ f"{sum(r[0] is not None for r in celdas):>7d}/{len(tareas)}")
optimas = [("A* ciega", lambda T: buscar(T, ciega, limite=LIM)), ("A* h_max", lambda T: buscar(T, h_max, limite=LIM))]
for cn, f in optimas:
correr(cn, f)
tabla([cn for cn, _ in optimas])
print("casilla: longitud del plan / estados expandidos; '-' = sin plan dentro del límite")satisfacientes = [("A* h_FF", lambda T: buscar(T, h_ff, limite=LIM)),
("voraz h_add", lambda T: buscar(T, h_add, w_g=0, limite=LIM)),
("voraz h_FF", lambda T: buscar(T, h_ff, w_g=0, limite=LIM)),
("EHC h_FF", lambda T: ehc(T, limite=LIM)),
("voraz h_LM", lambda T: voraz_lm(T, limite=LIM))]
for cn, f in satisfacientes:
correr(cn, f)
nombres = [cn for cn, _ in optimas + satisfacientes]
tabla(nombres)
mejor = {tn: min(r[0] for (c, t), r in res.items() if t == tn and r[0] is not None) for tn, _ in tareas}
print("mejor longitud de la tabla:", mejor)
print("puntuación de calidad (suma de mejor / propia):",
{cn: round(sum(mejor[tn] / res[cn, tn][0] for tn, _ in tareas if res[cn, tn][0]), 2) for cn in nombres})What the table says:
- Optimal configurations run out of budget. Blind A* solves 1 of 7 and A* with , 2 of 7. reduces expansions (400 instead of over 1000 on bw-7), but is too weak for the rest.
- A with solves 5 of 7 with best table lengths*, but has no guarantee: the second common mistake. Here plans match best known; in gripper with 4 balls A* with failed.
- Greedy searches solve all 7 with tens or hundreds of expansions, for longer plans: 48 and 44 steps on bw-9 versus 20 from A* with .
- EHC is most frugal where it works and fails on Hanoi: Hanoi has no dead ends (all moves reverse), so helpful-action pruning is responsible: the EHC cell shows all-action EHC does solve it (31 steps, 153 states evaluated). This is why FF has complete fallback search.
- Quality reference is the table’s: in gripper with 6 balls the best found plan has 21 steps, but optimum is 17: with balls (even), trips of 5 actions (pick two, move, drop two) and returns give total, confirmed by local A* with LM-cut. With that reference all gripper scores drop. This illustrates the previous warning.
Fast Downward via unified-planning
The unified-planning library from European project AIPlan4EU provides a common Python interface to many planners. Package up-fast-downward includes compiled Fast Downward: engine fast-downward defaults to alias lama-first (LAMA’s first greedy search, without improvement iterations), and fast-downward-opt runs A* with LM-cut. This cell runs locally (pip install unified-planning up-fast-downward) in another Python session, so repeats problem generators.
import os, random, tempfile, time
from unified_planning.io import PDDLReader
from unified_planning.shortcuts import OneshotPlanner, get_environment
from unified_planning.engines import PlanGenerationResultStatus as Estado
get_environment().credits_stream = None # sin el aviso de créditos de cada motor
# Los mismos dominios y generadores que las celdas del navegador (copiados: esta sesión es otra)
BLOQUES = """(define (domain blocksworld) (:requirements :strips)
(:predicates (on ?x ?y) (ontable ?x) (clear ?x) (handempty) (holding ?x))
(:action pick-up :parameters (?x) :precondition (and (clear ?x) (ontable ?x) (handempty))
:effect (and (not (ontable ?x)) (not (clear ?x)) (not (handempty)) (holding ?x)))
(:action put-down :parameters (?x) :precondition (holding ?x)
:effect (and (not (holding ?x)) (clear ?x) (handempty) (ontable ?x)))
(:action stack :parameters (?x ?y) :precondition (and (holding ?x) (clear ?y))
:effect (and (not (holding ?x)) (not (clear ?y)) (clear ?x) (handempty) (on ?x ?y)))
(:action unstack :parameters (?x ?y) :precondition (and (on ?x ?y) (clear ?x) (handempty))
:effect (and (holding ?x) (clear ?y) (not (clear ?x)) (not (handempty)) (not (on ?x ?y)))))"""
LOGISTICA = """(define (domain logistics) (:requirements :strips :typing)
(:types truck airplane - vehicle package vehicle - physobj airport location - place city place physobj - object)
(:predicates (in-city ?loc - place ?city - city) (at ?obj - physobj ?loc - place) (in ?pkg - package ?veh - vehicle)
(same-city ?a ?b - place))
(:action load-truck :parameters (?pkg - package ?truck - truck ?loc - place)
:precondition (and (at ?truck ?loc) (at ?pkg ?loc)) :effect (and (not (at ?pkg ?loc)) (in ?pkg ?truck)))
(:action load-airplane :parameters (?pkg - package ?airplane - airplane ?loc - place)
:precondition (and (at ?pkg ?loc) (at ?airplane ?loc)) :effect (and (not (at ?pkg ?loc)) (in ?pkg ?airplane)))
(:action unload-truck :parameters (?pkg - package ?truck - truck ?loc - place)
:precondition (and (at ?truck ?loc) (in ?pkg ?truck)) :effect (and (not (in ?pkg ?truck)) (at ?pkg ?loc)))
(:action unload-airplane :parameters (?pkg - package ?airplane - airplane ?loc - place)
:precondition (and (in ?pkg ?airplane) (at ?airplane ?loc)) :effect (and (not (in ?pkg ?airplane)) (at ?pkg ?loc)))
(:action drive-truck :parameters (?truck - truck ?loc-from - place ?loc-to - place ?city - city)
:precondition (and (at ?truck ?loc-from) (in-city ?loc-from ?city) (in-city ?loc-to ?city))
:effect (and (not (at ?truck ?loc-from)) (at ?truck ?loc-to)))
(:action fly-airplane :parameters (?airplane - airplane ?loc-from - airport ?loc-to - airport)
:precondition (at ?airplane ?loc-from) :effect (and (not (at ?airplane ?loc-from)) (at ?airplane ?loc-to))))"""
GRIPPER = """(define (domain gripper) (:requirements :strips :typing) (:types room ball gripper)
(:predicates (at-robby ?r - room) (at ?b - ball ?r - room) (free ?g - gripper) (carry ?b - ball ?g - gripper))
(:action move :parameters (?from ?to - room) :precondition (at-robby ?from)
:effect (and (at-robby ?to) (not (at-robby ?from))))
(:action pick :parameters (?b - ball ?r - room ?g - gripper) :precondition (and (at ?b ?r) (at-robby ?r) (free ?g))
:effect (and (carry ?b ?g) (not (at ?b ?r)) (not (free ?g))))
(:action drop :parameters (?b - ball ?r - room ?g - gripper) :precondition (and (carry ?b ?g) (at-robby ?r))
:effect (and (at ?b ?r) (free ?g) (not (carry ?b ?g)))))"""
HANOI = """(define (domain hanoi) (:requirements :strips) (:predicates (clear ?x) (on ?x ?y) (smaller ?x ?y))
(:action move :parameters (?disc ?from ?to)
:precondition (and (smaller ?to ?disc) (on ?disc ?from) (clear ?disc) (clear ?to))
:effect (and (clear ?from) (on ?disc ?to) (not (on ?disc ?from)) (not (clear ?to)))))"""
def torres_aleatorias(bloques, rnd):
torres = []
for b in rnd.sample(bloques, len(bloques)):
i = rnd.randrange(len(torres) + 1)
if i == len(torres):
torres.append([b])
else:
torres[i].append(b)
return torres
def hechos_torres(torres):
hs = []
for t in torres:
hs += [f"(ontable {t[0]})"] + [f"(on {x} {y})" for y, x in zip(t, t[1:])] + [f"(clear {t[-1]})"]
return hs
def problema_bloques(n, semilla):
rnd = random.Random(semilla)
bs = [f"b{i}" for i in range(1, n + 1)]
ini, fin = torres_aleatorias(bs, rnd), torres_aleatorias(bs, rnd)
meta = [h for h in hechos_torres(fin) if h.startswith("(on")]
return f"""(define (problem bw-{n}-{semilla}) (:domain blocksworld) (:objects {' '.join(bs)})
(:init {' '.join(hechos_torres(ini))} (handempty)) (:goal (and {' '.join(meta)})))"""
def problema_logistica(C, L, P, A, semilla):
rnd = random.Random(semilla)
objs, init, lugares = [], [], []
for c in range(1, C + 1):
locs = [f"ap{c}"] + [f"l{c}-{j}" for j in range(1, L)]
objs += [f"c{c} - city", f"t{c} - truck", f"ap{c} - airport"] + [f"{l} - location" for l in locs[1:]]
init += [f"(in-city {l} c{c})" for l in locs] + [f"(same-city {l} {m})" for l in locs for m in locs]
init.append(f"(at t{c} {rnd.choice(locs)})")
lugares += locs
for a in range(1, A + 1):
objs.append(f"a{a} - airplane")
init.append(f"(at a{a} ap{rnd.randint(1, C)})")
meta = []
for p in range(1, P + 1):
o, d = rnd.sample(lugares, 2)
objs.append(f"p{p} - package")
init.append(f"(at p{p} {o})")
meta.append(f"(at p{p} {d})")
return f"""(define (problem log-{C}-{L}-{P}-{A}-{semilla}) (:domain logistics) (:objects {' '.join(objs)})
(:init {' '.join(init)}) (:goal (and {' '.join(meta)})))"""
def problema_gripper(n):
bolas = [f"ball{i}" for i in range(1, n + 1)]
return f"""(define (problem gripper-{n}) (:domain gripper)
(:objects rooma roomb - room left right - gripper {' '.join(bolas)} - ball)
(:init (at-robby rooma) (free left) (free right) {' '.join(f'(at {b} rooma)' for b in bolas)})
(:goal (and {' '.join(f'(at {b} roomb)' for b in bolas)})))"""
def problema_hanoi(n):
discos, postes = [f"d{i}" for i in range(1, n + 1)], ["p1", "p2", "p3"]
debajo = discos[1:] + ["p1"]
init = ["(clear p2)", "(clear p3)", "(clear d1)"] + [f"(on {d} {x})" for d, x in zip(discos, debajo)]
init += [f"(smaller {x} {d})" for i, d in enumerate(discos) for x in postes + discos[i + 1:]]
meta = [f"(on {d} {x})" for d, x in zip(discos, discos[1:] + ["p3"])]
return f"""(define (problem hanoi-{n}) (:domain hanoi) (:objects {' '.join(postes + discos)})
(:init {' '.join(init)}) (:goal (and {' '.join(meta)})))"""
banco = [("bw-7", BLOQUES, problema_bloques(7, 3)), ("bw-9", BLOQUES, problema_bloques(9, 5)),
("bw-20", BLOQUES, problema_bloques(20, 5)), ("bw-40", BLOQUES, problema_bloques(40, 6)),
("grip-6", GRIPPER, problema_gripper(6)), ("grip-8", GRIPPER, problema_gripper(8)),
("grip-12", GRIPPER, problema_gripper(12)), ("grip-30", GRIPPER, problema_gripper(30)),
("log-2331", LOGISTICA, problema_logistica(2, 3, 3, 1, 2)), ("log-2341", LOGISTICA, problema_logistica(2, 3, 4, 1, 4)),
("log-4482", LOGISTICA, problema_logistica(4, 4, 8, 2, 7)), ("log-85203", LOGISTICA, problema_logistica(8, 5, 20, 3, 8)),
("hanoi-5", HANOI, problema_hanoi(5)), ("hanoi-8", HANOI, problema_hanoi(8))]
carpeta = tempfile.mkdtemp()
def leer(nombre, dominio, problema):
rutas = [os.path.join(carpeta, f"{nombre}-{x}.pddl") for x in ("dominio", "problema")]
for ruta, texto in zip(rutas, (dominio, problema)):
with open(ruta, "w", encoding="utf-8") as f:
f.write(texto)
return PDDLReader().parse_problem(*rutas)
LIMITE = 20 # segundos por tarea, el mismo para todos
configs = [("LAMA (lama-first)", "fast-downward"), ("A* + LM-cut", "fast-downward-opt")]
res = {}
for nombre, D, P in banco:
tarea = leer(nombre, D, P)
for etiqueta, motor in configs:
t0 = time.perf_counter()
with OneshotPlanner(name=motor) as planificador:
r = planificador.solve(tarea, timeout=LIMITE)
ok = r.status in (Estado.SOLVED_SATISFICING, Estado.SOLVED_OPTIMALLY)
res[etiqueta, nombre] = (len(r.plan.actions) if ok else None, time.perf_counter() - t0)
mejor = {n: min(v[0] for (c, m), v in res.items() if m == n and v[0] is not None) for n, _, _ in banco}
print(f"{'tarea':10s}" + "".join(f"{c:>26s}" for c, _ in configs))
for n, _, _ in banco:
print(f"{n:10s}" + "".join(f"{(str(res[c, n][0]) if res[c, n][0] else '-'):>18s} {res[c, n][1]:6.1f} s" for c, _ in configs))
for c, _ in configs:
resueltas = [n for n, _, _ in banco if res[c, n][0]]
calidad = sum(mejor[n] / res[c, n][0] for n in resueltas)
print(f"{c}: cobertura {len(resueltas)}/{len(banco)}, puntuación de calidad {calidad:.2f}")npm run lab and open the connection link.In this lesson’s verification run, with 20 seconds per task, LAMA solved all 14 tasks in under a second each (including call startup), and A* with LM-cut solved 9 of 14: all small tasks and gripper with 12 balls, which already took several seconds, timing out on large blocks, gripper and logistics. Times are indicative from a shared machine; ratios persist. The comparison shows:
- Coverage versus quality. LAMA solves everything but plans may be much worse than optimal: 56 steps on bw-9 versus 20, 26 versus 23 on small logistics and 287 versus 255 on 8-disk Hanoi. Full LAMA does not stop at the first plan: weighted A* iterations close that gap.
- Against your planner. On 7 common tasks, LM-cut finds the same optima as your A* when it finishes (10, 31), plus bw-9 (20) and logistics (23 and 18), confirming A* with was right in the table. On 8-ball gripper, LAMA gives the 23-step optimum; your greedy searches gave 29 to 31.
- Speed. Your Pyodide planner and Fast Downward in C++ are not comparable in seconds: beyond language, Fast Downward generates successors using specialized structures and evaluates heuristics incrementally. Compare expansions and quality; for times, compare under identical conditions.
Common mistakes
Exercises
move(?b - bloque ?desde ?hasta - lugar), where bloque is a subtype of lugar and the table is the only lugar object that is not a block. With 6 blocks plus the table and no pruning (neither inequalities nor reachability), how many grounded actions does the schema produce?Step 1 of 4. What strategy reduces the claim to something provable?
More than one answer may be correct.
h_add_pf(tarea, s) returning (h, coste, mejor): goal , a cost dictionary for every atom in tarea.atomos (float('inf') if unreachable), and dictionary mejor assigning each reachable atom not in s the action attaining its equation's minimum. Compute by fixed point (sweep tarea.acciones until nothing changes), without costes_relajados. Then implement plan_relajado_ff(tarea, s) returning the relaxed-plan action set extracted backward using these best supporters, or None if the goal is unreachable. Cell classes and functions are available (Tarea, Accion, tarea_de, GRIPPER, problema_gripper, REPARTO, problema_reparto).INF = float("inf")
def h_add_pf(tarea, s):
"""(h_add de la meta, coste de cada átomo, mejor soporte de cada átomo) por punto fijo."""
coste = {p: (0 if p in s else INF) for p in tarea.atomos}
mejor = {}
# tu código: barridas sobre tarea.acciones hasta que nada cambie
h = 0
return h, coste, mejor
def plan_relajado_ff(tarea, s):
"""Conjunto de acciones del plan relajado, hacia atrás desde la meta con los mejores soportes."""
h, coste, mejor = h_add_pf(tarea, s)
plan = set()
# tu código
return planSummary
- STRIPS describes states as atom sets and actions as with : the frame problem disappears because unmentioned facts do not change. PDDL adds parameterized schemas, types and conditional effects.
- Naive grounding is exponential in arity; relaxed-reachability pruning is safe and retains only what can happen.
- Plan existence is PSPACE-complete and plans can be exponentially long. Without deletes existence is polynomial but optimum is NP-hard.
- Regression is correct with relevance and consistency but generates impossible subgoals without invariants; progression dominates practice.
- : is admissible and weak, double-counts sharing, and extracts a concrete relaxed plan. The last two are inadmissible.
- FF adds helpful actions and enforced hill-climbing; Fast Downward adds SAS+, multiple queues and lazy evaluation; LAMA adds landmarks and anytime weighted A*. LM-cut turns landmarks into an admissible heuristic.
- Evaluate coverage, quality and time over many domains and common limits.
The next lesson, beyond state-space search, changes strategy: planning as satisfiability, Graphplan’s mutex planning graph, partial-order plans and hierarchical task networks.