Source code for qdpy.algorithms.temporal_planning

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Feature-based diverse planning on deterministic simulators.
# @see https://arxiv.org/abs/2510.17418

"""Find short plans with distinct finite-trace temporal profiles."""

from collections import defaultdict, deque
from collections.abc import Mapping
from dataclasses import dataclass
from itertools import combinations
from operator import index
from typing import Callable, Hashable

from .go_explore import _Path, _actions
from .modern import _positive_int

__all__ = ["TemporalMonitor", "eventually", "always", "ordered_visit", "DiversePlan",
           "DiversePlanningResult", "feature_based_planning"]


## @brief Recognize a property of the trace using finite, hashable monitor memory.
[docs] @dataclass(frozen=True) class TemporalMonitor: """Update one formula state for every observed label set. Both the initial simulator state and successors contribute labels. Use a memory value that includes all information needed to compute future monitor updates and acceptance. Memory values must be immutable and hashable. Custom monitors can represent additional LTLf formulas. """ initial: Hashable advance: Callable accepts: Callable def __post_init__(self): hash(self.initial) if not (callable(self.advance) and callable(self.accepts)): raise TypeError("A monitor needs callable advance and accepts functions.")
## @brief Recognize F p on a finite trace.
[docs] def eventually(proposition): """Accept when proposition holds at least once, including at the start.""" return TemporalMonitor(False, lambda seen, labels: seen or proposition in labels, bool)
## @brief Recognize G p on a finite trace.
[docs] def always(proposition): """Accept when proposition holds at every visited state.""" return TemporalMonitor(True, lambda valid, labels: valid and proposition in labels, bool)
## @brief Require the second proposition to hold strictly after the first.
[docs] def ordered_visit(first, second): """Accept a trace with a first visit followed at a later state by a second visit.""" def advance(memory, labels): seen, completed = memory return seen or first in labels, completed or (seen and second in labels) return TemporalMonitor((False, False), advance, lambda memory: memory[1])
## @brief A goal-reaching sequence and its temporal-feature truth values.
[docs] @dataclass(frozen=True) class DiversePlan: """Keep the simulator's final state and one Boolean per named monitor.""" actions: tuple profile: tuple[bool, ...] final_state: Hashable
## @brief Result and search cost across all width passes.
[docs] @dataclass(frozen=True) class DiversePlanningResult: """Report goal plans in discovery order and simulator calls, including illegal actions.""" plans: tuple[DiversePlan, ...] feature_names: tuple[str, ...] simulator_calls: int expanded_states: int width_passes: int budget_exhausted: bool
def _novel(atoms, width, seen): if not atoms: if not seen: seen.add(frozenset()) return True return False novel = False # Store all tuples on first encounter, even if an earlier tuple in # the same state already made it novel. for size in range(1, min(width, len(atoms)) + 1): for group in combinations(atoms, size): key = frozenset(group) if key not in seen: seen.add(key) novel = True return novel ## @brief Collect one feasible plan per temporal profile using bounded breadth-first search. # @return DiversePlanningResult with distinct plans and exact simulator-call accounting.
[docs] def feature_based_planning(start, *, actions, simulate, goal, labels, monitors, max_plans, budget, max_depth=None, state_features=None, max_width=2): """Search simulator states crossed with the temporal monitor memories. Use a pure deterministic simulate(state, action) callback on immutable, hashable states. Return None for an illegal move. The planner stops expanding a path at its first goal, records its Boolean profile, and continues looking for new profiles. Reaching the same physical state with a different monitor memory can produce a different plan. Supply state_features(state) to use iterative-width novelty pruning, repeating breadth-first passes with widths 1 through max_width. Novelty is tracked separately for each vector of monitor memories. Without state_features, a single exact product-state pass is used. Goal plans are shortest within the pass that discovered them. :param start: Initial simulator state. :param actions: Callable (state) generating legal or attempted actions in stable order. :param simulate: Pure callable (state, action) returning successor or None. :param goal: Callable returning whether the state completes the task. :param labels: Callable returning the true atomic propositions for a state. :param monitors: Ordered mapping from feature names to TemporalMonitor objects. :param max_plans: Stop after finding this many distinct profiles. :param budget: Maximum simulator calls across all passes. Zero permits the initial goal check. :param max_depth: Optional maximum action sequence length. :param state_features: Optional callable returning hashable novelty atoms. :param max_width: Maximum novelty tuple size when state_features is supplied. """ if (not all(map(callable, (actions, simulate, goal, labels))) or (state_features is not None and not callable(state_features))): raise TypeError("Supply callable simulator and feature functions.") if (not isinstance(monitors, Mapping) or any(not isinstance(name, str) or not name or not isinstance(monitor, TemporalMonitor) for name, monitor in monitors.items())): raise ValueError("Supply a mapping of distinct nonempty names to temporal monitors.") max_plans = _positive_int(max_plans, "max_plans") max_width = _positive_int(max_width, "max_width") budget = index(budget) depth = None if max_depth is None else index(max_depth) if budget < 0 or (depth is not None and depth < 0): raise ValueError("budget and max_depth must be nonnegative.") names, configured = tuple(monitors), tuple(monitors.values()) plans = {} calls = expanded = 0 def progress(state, memories): propositions = frozenset(labels(state)) return tuple(monitor.advance(memory, propositions) for monitor, memory in zip(configured, memories)) def result(passes, exhausted): return DiversePlanningResult(tuple(plans.values()), names, calls, expanded, passes, exhausted) def keep(state, memories, path): profile = tuple(bool(monitor.accepts(memory)) for monitor, memory in zip(configured, memories)) if profile not in plans: plans[profile] = DiversePlan(_actions(path), profile, state) first = progress(start, tuple(monitor.initial for monitor in configured)) if goal(start): keep(start, first, None) return result(1, False) for width in range(1, (max_width if state_features is not None else 1) + 1): queue = deque([(start, first, None)]) visited = {(start, first)} novelty = defaultdict(set) if state_features is not None: _novel(tuple(dict.fromkeys(state_features(start))), width, novelty[first]) pruned = False while queue: state, memories, path = queue.popleft() length = 0 if path is None else path.length if depth == length: continue expanded += 1 for action in actions(state): if calls == budget: return result(width, True) calls += 1 successor = simulate(state, action) if successor is None: continue next_memories = progress(successor, memories) if goal(successor): keep(successor, next_memories, _Path(path, action, length + 1)) if len(plans) == max_plans: return result(width, False) continue key = successor, next_memories if key in visited: continue if state_features is not None: atoms = tuple(dict.fromkeys(state_features(successor))) if not _novel(atoms, width, novelty[next_memories]): pruned = True continue visited.add(key) queue.append((successor, next_memories, _Path(path, action, length + 1))) if not pruned: break return result(width, False)