6"""Find short plans with distinct finite-trace temporal profiles."""
8from collections
import defaultdict, deque
9from collections.abc
import Mapping
10from dataclasses
import dataclass
11from itertools
import combinations
12from operator
import index
13from typing
import Callable, Hashable
15from .go_explore
import _Path, _actions
16from .modern
import _positive_int
18__all__ = [
"TemporalMonitor",
"eventually",
"always",
"ordered_visit",
"DiversePlan",
19 "DiversePlanningResult",
"feature_based_planning"]
23@dataclass(frozen=True)
25 """Update one formula state for every observed label set.
27 Both the initial simulator state and successors contribute labels.
28 Use a memory value that includes all information needed to compute
29 future monitor updates and acceptance. Memory values must be immutable
30 and hashable. Custom monitors can represent additional LTLf formulas.
37 def __post_init__(self):
40 raise TypeError(
"A monitor needs callable advance and accepts functions.")
44def eventually(proposition):
45 """Accept when proposition holds at least once, including at the start."""
46 return TemporalMonitor(
False,
lambda seen, labels: seen
or proposition
in labels, bool)
50def always(proposition):
51 """Accept when proposition holds at every visited state."""
52 return TemporalMonitor(
True,
lambda valid, labels: valid
and proposition
in labels, bool)
56def ordered_visit(first, second):
57 """Accept a trace with a first visit followed at a later state by a second visit."""
58 def advance(memory, labels):
59 seen, completed = memory
60 return seen
or first
in labels, completed
or (seen
and second
in labels)
62 return TemporalMonitor((
False,
False), advance,
lambda memory: memory[1])
66@dataclass(frozen=True)
68 """Keep the simulator's final state and one Boolean per named monitor."""
71 profile: tuple[bool, ...]
76@dataclass(frozen=True)
78 """Report goal plans in discovery order and simulator calls, including illegal actions."""
80 plans: tuple[DiversePlan, ...]
81 feature_names: tuple[str, ...]
85 budget_exhausted: bool
88def _novel(atoms, width, seen):
97 for size
in range(1, min(width, len(atoms)) + 1):
98 for group
in combinations(atoms, size):
99 key = frozenset(group)
108def feature_based_planning(start, *, actions, simulate, goal, labels, monitors, max_plans, budget,
109 max_depth=None, state_features=None, max_width=2):
110 """Search simulator states crossed with the temporal monitor memories.
112 Use a pure deterministic simulate(state, action) callback on immutable,
113 hashable states. Return None for an illegal move. The planner stops
114 expanding a path at its first goal, records its Boolean profile, and
115 continues looking for new profiles. Reaching the same physical state
116 with a different monitor memory can produce a different plan.
118 Supply state_features(state) to use iterative-width novelty pruning,
119 repeating breadth-first passes with widths 1 through max_width.
120 Novelty is tracked separately for each vector of monitor memories.
121 Without state_features, a single exact product-state pass is used.
122 Goal plans are shortest within the pass that discovered them.
124 :param start: Initial simulator state.
125 :param actions: Callable (state) generating legal or attempted actions in stable order.
126 :param simulate: Pure callable (state, action) returning successor or None.
127 :param goal: Callable returning whether the state completes the task.
128 :param labels: Callable returning the true atomic propositions for a state.
129 :param monitors: Ordered mapping from feature names to TemporalMonitor objects.
130 :param max_plans: Stop after finding this many distinct profiles.
131 :param budget: Maximum simulator calls across all passes. Zero permits the initial goal check.
132 :param max_depth: Optional maximum action sequence length.
133 :param state_features: Optional callable returning hashable novelty atoms.
134 :param max_width: Maximum novelty tuple size when state_features is supplied.
136 if (
not all(map(callable, (actions, simulate, goal, labels)))
137 or (state_features
is not None and not callable(state_features))):
138 raise TypeError(
"Supply callable simulator and feature functions.")
139 if (
not isinstance(monitors, Mapping)
140 or any(
not isinstance(name, str)
or not name
or not isinstance(monitor, TemporalMonitor)
141 for name, monitor
in monitors.items())):
142 raise ValueError(
"Supply a mapping of distinct nonempty names to temporal monitors.")
143 max_plans = _positive_int(max_plans,
"max_plans")
144 max_width = _positive_int(max_width,
"max_width")
145 budget = index(budget)
146 depth =
None if max_depth
is None else index(max_depth)
147 if budget < 0
or (depth
is not None and depth < 0):
148 raise ValueError(
"budget and max_depth must be nonnegative.")
149 names, configured = tuple(monitors), tuple(monitors.values())
153 def progress(state, memories):
154 propositions = frozenset(labels(state))
155 return tuple(monitor.advance(memory, propositions)
for monitor, memory
in zip(configured, memories))
157 def result(passes, exhausted):
160 def keep(state, memories, path):
161 profile = tuple(bool(monitor.accepts(memory))
for monitor, memory
in zip(configured, memories))
162 if profile
not in plans:
163 plans[profile] =
DiversePlan(_actions(path), profile, state)
165 first = progress(start, tuple(monitor.initial
for monitor
in configured))
167 keep(start, first,
None)
168 return result(1,
False)
169 for width
in range(1, (max_width
if state_features
is not None else 1) + 1):
170 queue = deque([(start, first,
None)])
171 visited = {(start, first)}
172 novelty = defaultdict(set)
173 if state_features
is not None:
174 _novel(tuple(dict.fromkeys(state_features(start))), width, novelty[first])
177 state, memories, path = queue.popleft()
178 length = 0
if path
is None else path.length
182 for action
in actions(state):
184 return result(width,
True)
186 successor = simulate(state, action)
187 if successor
is None:
189 next_memories = progress(successor, memories)
191 keep(successor, next_memories,
_Path(path, action, length + 1))
192 if len(plans) == max_plans:
193 return result(width,
False)
195 key = successor, next_memories
198 if state_features
is not None:
199 atoms = tuple(dict.fromkeys(state_features(successor)))
200 if not _novel(atoms, width, novelty[next_memories]):
204 queue.append((successor, next_memories,
_Path(path, action, length + 1)))
207 return result(width,
False)
A goal-reaching sequence and its temporal-feature truth values.
Result and search cost across all width passes.
Recognize a property of the trace using finite, hashable monitor memory.