Module contents
Lesson 20 of 23Core 110 min

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 SGS_G, 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.

InteractiveBlocks-world planner
Initial state
ABCDEF
Goal
FEDCBA
Plan execution: step 0 of 12
ABCDEFarm
initial state
1 / 13
A* with each heuristic
hexpandedplanms
blind215412
hmax⁡h_{\max}27712
haddh_{\text{add}}6016
hFFh_{\text{FF}}1412
Plan in red: longer than optimal. Milliseconds depend on your browser; node counts do not.
Search graph: expanded nodes by depth g (first 1500 drawn); the plan path is colored
01234567891011g
Heuristic
Search
Expanded nodes2154
Generated states7251
Plan length12
Optimal length12
Define initial state and goal by dragging blocks (or touching a block then its destination). The planner solves with A∗^* or greedy search and all four heuristics: the table compares expanded nodes, plan length and time, marking plans longer than optimal in red. The player executes the chosen heuristic's plan; below, the search graph positions expanded nodes by depth, highlighting the plan path. Start with ‘Two towers into one’: compare nodes expanded by A∗^* with blind heuristic and hFFh_{\text{FF}}, and see which heuristic makes A∗^* return a longer-than-optimal plan. Then load Sussman's anomaly and rearrange blocks yourself.

Three things the figure shows and the lesson explains:

  1. Domain-derived heuristics work. With six blocks, blind search expands thousands of states; with hFFh_{\text{FF}}, dozens. No one told the planner what “well placed” means.
  2. Not all are admissible. With haddh_{\text{add}}, A* may return a longer-than-optimal plan. A* guarantees optimality only with heuristics that never overestimate; haddh_{\text{add}} and hFFh_{\text{FF}} do overestimate.
  3. Subgoals interfere. In Sussman’s anomaly the goal is “aa on bb and bb on cc”. Place aa on bb first and placing bb on cc requires undoing it; place bb on cc first and aa is buried under cc. 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 S⊆2FS \subseteq 2^F, s0=Is_0 = I, SG={s:G⊆s}S_G = \{s : G \subseteq s\} and f(o,s)=s[o]f(o, s) = s[o], so at most 2∣F∣2^{\abs{F}} states: a reasonable atom count already describes an astronomical space. Formula s[o]s[o] deletes first then adds; if an atom is in both add(o)\mathrm{add}(o) and del(o)\mathrm{del}(o), addition wins, PDDL’s semantics. Below assume without loss of generality add(o)∩del(o)=∅\mathrm{add}(o) \cap \mathrm{del}(o) = \emptyset (remove from del(o)\mathrm{del}(o) 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 add(o)\mathrm{add}(o) nor del(o)\mathrm{del}(o) retains its value. This STRIPS assumption makes formula s[o]s[o] 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 - truck restricts 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 kk independent conditional effects yield 2k2^k actions, so good planners handle them directly.
  • Action costs (:action-costs, used since IPC 2008): a function total-cost minimized 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 x1,…,xkx_1, \dots, x_k of types T1,…,TkT_1, \dots, T_k and D(T)D(T) are objects of type TT, it produces

∏i=1k∣D(Ti)∣\prod_{i=1}^{k} \abs{D(T_i)}

ground actions, and without types ∣objetos∣k\abs{\text{objetos}}^k. 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. I⊆RI \subseteq R. If s⊆Rs \subseteq R and oo is applicable in ss, then pre(o)⊆s⊆R\mathrm{pre}(o) \subseteq s \subseteq R, so the fixed point fires oo and adds add(o)\mathrm{add}(o) to RR; therefore s[o]=(s∖del(o))∪add(o)⊆Rs[o] = (s \setminus \mathrm{del}(o)) \cup \mathrm{add}(o) \subseteq R.

∎

The implication is one-way: RR overapproximates, and useless actions survive. In blocks world without equality, stack(b,b)\mathit{stack}(b, b) needs holding(b)\mathit{holding}(b) and clear(b)\mathit{clear}(b), 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.

[ ]A PDDL parserBrowser
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.

[ ]Grounding with reachability pruningBrowser
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 stack(b,b)\mathit{stack}(b, b). 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 CC cities of LL locations there are C⋅(CL)2⋅CC \cdot (CL)^2 \cdot C instances, but a truck only drives in its city, so C⋅L2C \cdot L^2 are reachable. With PP packages and AA planes, full counts are

con tipos:2PC⋅CL+2PA⋅CL+C2(CL)2+AC2,alcanzables:2PCL+2PAC+CL2+AC2,\begin{aligned} \text{con tipos:}\quad & 2PC\cdot CL + 2PA\cdot CL + C^2 (CL)^2 + AC^2,\\ \text{alcanzables:}\quad & 2PCL + 2PAC + CL^2 + AC^2, \end{aligned}

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.

InteractiveGrounding explosion
110¹10²10³10⁴10⁵10⁶10⁷load-truck3 parameters141 k2000400unload-truck3 parameters141 k2000400load-airplane3 parameters141 k800200unload-airplane3 parameters141 k800200drive-truck4 parameters7.31 M10.0 k80fly-airplane3 parameters141 k5050total8.01 M15.7 k1330
  • untyped
  • typed
  • reachable
5
4
20
2
drive-truck parameters
Objects52
Untyped8.01 M actions
Typed15.7 k actions
Reachable1330 actions
Memory: typed → reachable9.03 MiB → 786 KiB
Pruning leaves 8.5 % of typed actions. The most pruned now is drive-truck (factor 125): a truck never leaves its city.
Ground logistics actions by schema on a logarithmic scale: untyped (each parameter ranges over all objects), typed (product of parameter domains), and after relaxed-reachability pruning. Counts use the previous cell's model checked against actual grounding, and memory uses its measured bytes per action. Increase cities: which schema grows fastest without pruning, and which with pruning? Change drive-truck from 4 to 3 parameters and see which columns change and which does not.

With 30 cities of 10 locations, 200 packages and 10 planes, the untyped version exceeds 101110^{11} actions and typed reaches 8.6×1078.6 \times 10^{7}, 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.

[ ]Semantics, validator and searchBrowser
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 on(a,b)\mathit{on}(a, b) with its four actions and then on(b,c)\mathit{on}(b, c)) fails at step five: picking up bb requires it to be clear, and aa 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 kk.

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 (∣F∣\abs{F} bits) and a step counter cutting off at 2∣F∣2^{\abs{F}}, 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 p(n)p(n) space and input ww, construct a task with one atom each for “cell ii contains symbol σ\sigma”, “head is at ii” and “machine is in state qq”, an operator per transition (q,σ)(q, \sigma) and position ii (preconditions: head at ii, state qq, symbol σ\sigma in ii; effects: write, move and change state, deleting prior values), and goal “accepting state”. The task is polynomial in nn and has a plan if and only if the machine accepts ww.

∎

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 nn disks and blind search finds optimal plans of 2n−12^n - 1 steps, while atoms grow as n2n^2.

[ ]Exponentially long plansBrowser
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 II, successors of ss are s[o]s[o] with oo applicable, and the goal is checked with G⊆sG \subseteq s. 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

(⇒\Rightarrow) pre(o)⊆regr(g,o)⊆s\mathrm{pre}(o) \subseteq \mathrm{regr}(g, o) \subseteq s, so oo is applicable. Let p∈gp \in g. If p∈add(o)p \in \mathrm{add}(o), it is in s[o]s[o]. Otherwise p∈g∖add(o)⊆sp \in g \setminus \mathrm{add}(o) \subseteq s, and since p∉del(o)p \notin \mathrm{del}(o) by consistency, it survives: p∈s∖del(o)⊆s[o]p \in s \setminus \mathrm{del}(o) \subseteq s[o].

(⇐\Leftarrow) pre(o)⊆s\mathrm{pre}(o) \subseteq s by applicability. If p∈g∖add(o)p \in g \setminus \mathrm{add}(o) and p∈s[o]=(s∖del(o))∪add(o)p \in s[o] = (s \setminus \mathrm{del}(o)) \cup \mathrm{add}(o), it must be in s∖del(o)⊆ss \setminus \mathrm{del}(o) \subseteq s.

If p∈del(o)∩gp \in \mathrm{del}(o) \cap g, since we assume add(o)∩del(o)=∅\mathrm{add}(o) \cap \mathrm{del}(o) = \emptyset, p∉s[o]p \notin s[o] for any ss.

∎

Relevance is unnecessary for correctness, only to avoid wasted effort: if oo adds nothing to gg, regr(g,o)⊇g\mathrm{regr}(g, o) \supseteq g 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 stack(a,b)\mathit{stack}(a, b) and then stack(b,c)\mathit{stack}(b, c), checking a domain invariant: the arm holds at most one block.

[ ]RegressionBrowser
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 aa and bb 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 Π+\Pi^+ 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 Π+\Pi^+: if s⊆ts \subseteq t and π\pi is applicable in Π+\Pi^+ from ss, it is also applicable from tt, and the final state from tt contains that from ss. By induction: first-action preconditions are in s⊆ts \subseteq t, and afterward both states grow with the same add\mathrm{add}, preserving inclusion.

Admissibility. Let π=o1,…,on\pi = o_1, \dots, o_n be a real plan from ss, with real states sis_i and relaxed states si+s_i^+. By induction si⊆si+s_i \subseteq s_i^+: true for i=0i = 0, and if si−1⊆si−1+s_{i-1} \subseteq s_{i-1}^+, oio_i is applicable in si−1+s_{i-1}^+ and si=(si−1∖del)∪add⊆si−1+∪add=si+s_i = (s_{i-1} \setminus \mathrm{del}) \cup \mathrm{add} \subseteq s_{i-1}^+ \cup \mathrm{add} = s_i^+. Thus G⊆sn⊆sn+G \subseteq s_n \subseteq s_n^+ and π\pi is a relaxed plan: h+(s)≤coste(π)h^+(s) \le \mathrm{coste}(\pi). Taking optimal π\pi yields h+(s)≤h∗(s)h^+(s) \le h^*(s).

Consistency. If π′\pi' is an optimal relaxed plan from s[o]s[o], then o,π′o, \pi' is a relaxed plan from ss: applying o+o^+ in ss reaches s∪add(o)⊇s[o]s \cup \mathrm{add}(o) \supseteq s[o], and monotonicity keeps π′\pi' working. Therefore h+(s)≤c(o)+h+(s[o])h^+(s) \le c(o) + h^+(s[o]).

∎

Consistency means A* with h+h^+ finds optimal plans without reopening nodes (see consistent heuristics). Two more properties make Π+\Pi^+ manageable:

  • Deciding relaxed-plan existence is polynomial. It is the reachability fixed point: h+(s)=∞h^+(s) = \infty if and only if the goal is not reached from ss ignoring deletes. Since h+≤h∗h^+ \le h^*, 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 ∣O∣\abs{O} actions.

But computing h+h^+ is costly.

Proof

In NP: a certificate is a set of at most kk actions; polynomial time checks that, applied in reachability fixed-point order, they reach GG.

NP-hard, by reduction from set cover (given universe UU, subsets S1,…,SmS_1, \dots, S_m and kk, are there kk subsets whose union is UU?), which is NP-complete. Take F=UF = U, I=∅I = \emptyset, G=UG = U and, for each SjS_j, operator ojo_j without preconditions, add(oj)=Sj\mathrm{add}(o_j) = S_j and cost 1. A set of operators is a relaxed plan if and only if its SjS_j cover UU, so h+(I)≤kh^+(I) \le k if and only if a cover of size kk 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 h+h^+: from below (hmax⁡h_{\max}, LM-cut), above (haddh_{\text{add}}, hFFh_{\text{FF}}) or with a particular relaxed plan (hFFh_{\text{FF}}).

hmax⁡h_{\max} and haddh_{\text{add}}: Bellman–Ford over atoms

The most direct approximation of h+h^+ estimates each atom’s cost separately and combines them. First look at the graph.

InteractiveThe relaxed planning graph
F0A0F1A1F2A2F3con A→Bc = 1con B→Ac = 1con B→Cc = 1con C→Bc = 1car p1 Ac = 1des p1 Ac = 1car p1 Bc = 1des p1 Bc = 1des p1 Cc = 1des p2 Ac = 1car p2 Bc = 1des p2 Bc = 1des p2 Cc = 1t@A0t@B1t@C2p1@A0p1@B3p1@C4p1∈t1p2@A3p2@B0p2@C5p2∈t2
  • atom (blue border for goal) and its value
  • action and cost (select to change)
  • FF relaxed plan
t@B: the truck is at B; p1∈t: p1 is inside the truck; car, des, con: load, unload, drive. Each node appears in the first layer where it is reachable.
Value of each atom
fixed point
hmax⁡h_{\max}3
h+h^+ (exact)6
hFFh_{\text{FF}}6
haddh_{\text{add}}9
h∗h^* (true optimum)6
hadd=9>h∗=6h_{\text{add}} = 9 > h^* = 6: summing goals separately counts shared work twice (the journey to C). It is not admissible.
hmax⁡=3h_{\max} = 3 considers only the most expensive goal: admissible, but an underestimate.
Delivery problem: a truck at A, a road connecting A to B and B to C, package p1 at A and p2 at B, both destined for C. Each atom (pill) and action (rectangle) appears in its first layer reachable ignoring deletes. Under each atom is hmax⁡h_{\max} or haddh_{\text{add}}; orange shows FF's extracted relaxed plan. Readings compare hmax⁡≤h+≤hFF≤haddh_{\max} \le h^+ \le h_{\text{FF}} \le h_{\text{add}} with real optimum h∗h^*. Move sweeps from 0 and watch values drop from ∞ to the fixed point. Enable ‘truck must return to A’: which reading changes and which does not? Touch actions to increase costs: can you make haddh_{\text{add}} stop overestimating?

The hmax⁡h_{\max} and haddh_{\text{add}} heuristics assign each atom pp an estimated cost to reach it from ss, defined by equations

h(p;s)={0si p∈s,min⁡o : p∈add(o)[c(o)+h(pre(o);s)]si no,h(p; s) = \begin{cases} 0 & \text{si } p \in s,\\ \displaystyle\min_{o \,:\, p \in \mathrm{add}(o)} \big[c(o) + h(\mathrm{pre}(o); s)\big] & \text{si no,} \end{cases}

where a set of atoms costs their maximum or sum:

hmax⁡(C;s)=max⁡q∈Chmax⁡(q;s),hadd(C;s)=∑q∈Chadd(q;s),h_{\max}(C; s) = \max_{q \in C} h_{\max}(q; s), \qquad h_{\text{add}}(C; s) = \sum_{q \in C} h_{\text{add}}(q; s),

with h(∅;s)=0h(\emptyset; s) = 0 and min⁡∅=∞\min \emptyset = \infty. State heuristic is goal cost: hmax⁡(s)=hmax⁡(G;s)h_{\max}(s) = h_{\max}(G; s) and hadd(s)=hadd(G;s)h_{\text{add}}(s) = h_{\text{add}}(G; s).

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 00 for atoms in ss and ∞\infty 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 kk sweeps all atoms with supporter-chain depth ≤k\le k are exact: at most ∣F∣\abs{F} sweeps, each costing O(∑o∣pre(o)∣+∣add(o)∣)\bigO(\sum_o \abs{\mathrm{pre}(o)} + \abs{\mathrm{add}(o)}). 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.

[ ]h_max and h_add by fixed point and DijkstraBrowser
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: hadd(esta(p2,C))=5h_{\text{add}}(\mathit{esta}(p_2, C)) = 5 because it adds dentro(p2)\mathit{dentro}(p_2) (2: drive to B and load) and en(t,C)\mathit{en}(t, C) (2: drive to B and C), counting A-to-B twice in one subgoal. Adding esta(p1,C)=4\mathit{esta}(p_1, C) = 4, A→B appears three times and B→C twice, while the optimal plan uses each once: for any positive action costs, hadd−h∗=2c(A→B)+c(B→C)h_{\text{add}} - h^* = 2c(A{\to}B) + c(B{\to}C) in this problem. Thus no cost change in the figure makes haddh_{\text{add}} stop overestimating.

You prove the first inequality in the guided exercise (idea: any relaxed plan achieving an atom costs at least that atom’s hmax⁡h_{\max}). The second is h+h^+‘s admissibility. The third follows by induction over sweeps because the maximum of nonnegative values never exceeds their sum. Interpretation matters:

  • hmax⁡h_{\max} 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.
  • haddh_{\text{add}} assumes subgoals independent and adds their costs. It is much more informative but counts shared actions repeatedly. In delivery, hadd=9h_{\text{add}} = 9 while optimum is 6.

hmax⁡h_{\max} is member m=1m = 1 of Haslum and Geffner’s (2000) hmh^m family, estimating costs of sets of up to mm atoms; h2h^2 captures pairwise interactions at higher-degree polynomial cost. haddh_{\text{add}} 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

haddh_{\text{add}} 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 ss alternates atom and action layers: F0=sF_0 = s; AkA_k are actions applicable in FkF_k; Fk+1=Fk∪⋃o∈Akadd(o)F_{k+1} = F_k \cup \bigcup_{o \in A_k} \mathrm{add}(o). Stop when G⊆FkG \subseteq F_k or two layers coincide (then h=∞h = \infty). Each atom’s first layer is its hmax⁡h_{\max} 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 kk choose an achieving action from Ak−1A_{k-1}, 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 hFF(s)h_{\text{FF}}(s). With costs, Fast Downward does the same with each atom’s best supporter according to haddh_{\text{add}} (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 π+(s)\pi^+(s) by the haddh_{\text{add}} of what they support yields a valid relaxed plan, so h+≤hFFh^+ \le h_{\text{FF}}. Also hFF≤haddh_{\text{FF}} \le h_{\text{add}}: expanding haddh_{\text{add}} equations from the goal, each required atom appears at least once with its best supporter’s cost; haddh_{\text{add}} sums every occurrence and hFFh_{\text{FF}} counts each action once. FF’s abstract says its heuristic, unlike HSP’s, does not assume facts independent.

hFFh_{\text{FF}} is not admissible either. If each of three goals g1,g2,g3g_1, g_2, g_3 is achieved by its own cost-1 action bib_i, or all together by cost-1 action aa requiring atom pp produced by another cost-1 action, hadd(gi)=1h_{\text{add}}(g_i) = 1 by bib_i and the relaxed plan is {b1,b2,b3}\{b_1, b_2, b_3\}: hFF=3h_{\text{FF}} = 3, while optimum is 2.

The cell computes h+h^+ exactly (A* and hmax⁡h_{\max} on Π+\Pi^+, viable only for small tasks) and compares the whole chain.

[ ]h+, FF relaxed plan and the chain of inequalitiesBrowser
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 hmax⁡≤h+≤hFF≤haddh_{\max} \le h^+ \le h_{\text{FF}} \le h_{\text{add}}, and in these tasks the FF relaxed plan is also optimal (hFF=h+h_{\text{FF}} = h^+), not guaranteed. Comparisons with h∗h^* are interesting:

  • In gripper with 4 balls, h+=9<h∗=11h^+ = 9 < h^* = 11: under relaxation a gripper remains free after picking up a ball, so the robot carries all four in one trip without returning. And hadd=12>h∗=11h_{\text{add}} = 12 > h^* = 11 genuinely overestimates.
  • In “deliver and return”, h+=6h^+ = 6 and h∗=8h^* = 8: goal en(t,A)\mathit{en}(t, A) 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, hmax⁡h_{\max} and hFFh_{\text{FF}} return the optimal 11-step plan, but haddh_{\text{add}} 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 ss 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 ss. 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 hFFh_{\text{FF}}; 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 hFFh_{\text{FF}}.

[ ]Helpful actions and enforced hill-climbingBrowser
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 hFFh_{\text{FF}} from 3 to 2 (relaxation does not consume the key) but leaves the task unsolvable (h∗=∞h^* = \infty). 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 π\pi of Π\Pi in which pp is never true. Then π\pi uses no action adding pp (after it pp would be true), so it is a plan of Π\Pi 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 pp not initially true, calculate its first achievers (actions adding pp and applicable in relaxation before pp is achieved, i.e. without any achiever of pp), and any precondition common to all is a landmark greedy-necessarily ordered before pp. 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 nn landmarks,

hLM(s,π)=n−∣aceptados(π)∣+∣otra vez(s,π)∣.h_{\text{LM}}(s, \pi) = n - \abs{\text{aceptados}(\pi)} + \abs{\text{otra vez}(s, \pi)}.

It depends on path π\pi reaching ss, not just ss. It is inadmissible: if one action achieves two landmarks at once (two goals with one action, as in haddh_{\text{add}}‘s counterexample), count is 2 and plan cost 1.

InteractiveLandmarks of a problem
ABCt p1p2
Landmark graph (arrow: must be achieved before)
t@At@Bt@Cp1@Ap1@Cp1∈tp2@Bp2@Cp2∈t
  • accepted
  • needed again
  • pending
Thick border: a landmark that is a goal. hLMh_{\text{LM}} values along the traversal: 6
initial state
1 / 9
Problem
Traversal
Landmarks nn9
Accepted3
Needed again0
hLM=n−accepted+needed againh_{\text{LM}} = n - \text{accepted} + \text{needed again}6
h∗h^* remaining8
Above: road with truck t and packages. Below: the backward-extracted landmark graph with ‘must be achieved before’ orderings; goals have thick borders. Advance the optimal plan step by step: each landmark turns green when accepted and hLMh_{\text{LM}} decreases. With ‘truck returns to origin’ enabled, inspect step two: the truck leaves A, an accepted goal, and the count does not decrease despite progress. Then choose actions yourself: unload a package in the wrong place and inspect landmarks and h∗h^*.
[ ]Landmarks and LAMA landmark-count heuristicBrowser
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 en(t,A)\mathit{en}(t, A) 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 hLMh_{\text{LM}} 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 en(t,A)\mathit{en}(t, A) becomes needed again) and on the return at the end, achieving no new landmark. Greedy search with hLMh_{\text{LM}} solves three test problems with expansions of the same order as hFFh_{\text{FF}}; 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 hmax⁡h_{\max}, take the action justifying each atom’s hmax⁡h_{\max}, find a cut between state and goal in that justification graph, whose crossing actions form a disjunctive landmark; add minimum cut cost mm, subtract mm from those actions and repeat until the goal’s hmax⁡h_{\max} is 0. The result satisfies hmax⁡≤hLM-cut≤h+h_{\max} \le h_{\text{LM-cut}} \le h^+, 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:

  1. 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 vv with finite domains DvD_v, states as complete assignments and actions with preconditions and effects as partial assignments.
  2. Knowledge compilation. Causal graph between variables, per-variable transition graphs and structures for fast successor generation.
  3. 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 hh when expanding rather than generating a node, giving children the parent’s hh 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 211=20482^{11} = 2048 possible sets), while SAS+ has 3 variables: the truck with 3 values and each package with 4 (three locations or truck). There are 3⋅4⋅4=483 \cdot 4 \cdot 4 = 48 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, hFFh_{\text{FF}} and hLMh_{\text{LM}}, 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 cmejor/cc^{\text{mejor}} / c, 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.

[ ]Benchmark: optimal configurationsBrowser
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")
[ ]Benchmark: satisficing configurations and scoringBrowser
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 hmax⁡h_{\max}, 2 of 7. hmax⁡h_{\max} reduces expansions (400 instead of over 1000 on bw-7), but is too weak for the rest.
  • A with hFFh_{\text{FF}} 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 haddh_{\text{add}} 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 hFFh_{\text{FF}}.
  • 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 nn balls (even), n/2n/2 trips of 5 actions (pick two, move, drop two) and n/2−1n/2 - 1 returns give 3n−13n - 1 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.

[ ]Fast Downward: LAMA and A* with LM-cutLocal GPU
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}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 hFFh_{\text{FF}} 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

Numericmove instances
A blocks domain uses one schema 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?
QuizRegressing through an action that deletes
You search backward. The plan suffix starts with pick-up(b)\mathit{pick\text{-}up}(b), so the pending subgoal is its precondition, g={clear(b),ontable(b),handempty}g = \{\mathit{clear}(b), \mathit{ontable}(b), \mathit{handempty}\}. A colleague regresses gg through unstack(a,b)\mathit{unstack}(a, b), which adds clear(b)\mathit{clear}(b), calculates (g∖add)∪pre={ontable(b),handempty,on(a,b),clear(a)}(g \setminus \mathrm{add}) \cup \mathrm{pre} = \{\mathit{ontable}(b), \mathit{handempty}, \mathit{on}(a, b), \mathit{clear}(a)\} and, since it holds initially (aa on bb and bb on the table), returns plan unstack(a,b),pick-up(b)\mathit{unstack}(a, b), \mathit{pick\text{-}up}(b). What went wrong?
Proofh_max is admissible; h_add is not
Prove: For every state ss of a STRIPS task with nonnegative costs, hmax⁡(s)≤h+(s)≤h∗(s)h_{\max}(s) \le h^+(s) \le h^*(s). Conversely, there are tasks with hadd(s)>h∗(s)h_{\text{add}}(s) > h^*(s).
0
Let π=o1,…,on\pi = o_1, \dots, o_n be any relaxed plan from ss, and sks_k the relaxed state after its first kk actions.

Step 1 of 4. What strategy reduces the claim to something provable?

Numerich_add with two packages together
Same delivery domain (road A–B and B–C, one truck, load, unload and drive cost 1), but truck and both packages start at A and both packages must reach C. What is haddh_{\text{add}} initially?
QuizSTRIPS versus SAS+
A delivery domain has 4 locations connected in a line, 2 trucks and 3 packages. STRIPS atoms are ‘truck at location’, ‘package at location’ and ‘package inside truck’. Fast Downward finds one variable per truck and package. Which statement is correct?
QuizKnown planning complexity
Which claims about propositional STRIPS are true?

More than one answer may be correct.

QuizA* with h_FF
You run A∗^* with hFFh_{\text{FF}} on a unit-cost task and get a 40-action plan. What can you assert?
QuizWhen h_LM does not decrease
In delivery with return (truck must end at A), the optimal plan starts by loading p1 at A and driving A to B. After loading hLM=5h_{\text{LM}} = 5; after driving to B it remains 5, although landmark en(t,B)\mathit{en}(t, B) was accepted. Why?
Codeh_add by fixed point and the FF relaxed plan
Implement h_add_pf(tarea, s) returning (h, coste, mejor): goal haddh_{\text{add}}, 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 plan
Shift+Enter to run

Summary

Key idea
A classical planner knows nothing about its domain: it reads a STRIPS or PDDL description, grounds only what is reachable and derives heuristics by approximately solving delete relaxation, where facts only accumulate.
  • STRIPS describes states as atom sets and actions as ⟨pre,add,del⟩\langle \mathrm{pre}, \mathrm{add}, \mathrm{del} \rangle with s[o]=(s∖del)∪adds[o] = (s \setminus \mathrm{del}) \cup \mathrm{add}: 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 h+h^+ is NP-hard.
  • Regression is correct with relevance and consistency but generates impossible subgoals without invariants; progression dominates practice.
  • hmax⁡≤h+≤hFF≤haddh_{\max} \le h^+ \le h_{\text{FF}} \le h_{\text{add}}: hmax⁡h_{\max} is admissible and weak, haddh_{\text{add}} double-counts sharing, and hFFh_{\text{FF}} 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.