QDpy
Loading...
Searching...
No Matches
temporal_planning.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Find short plans with distinct finite-trace temporal profiles."""
7
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
14
15from .go_explore import _Path, _actions
16from .modern import _positive_int
17
18__all__ = ["TemporalMonitor", "eventually", "always", "ordered_visit", "DiversePlan",
19 "DiversePlanningResult", "feature_based_planning"]
20
21
22
23@dataclass(frozen=True)
25 """Update one formula state for every observed label set.
26
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.
31 """
32
33 initial: Hashable
34 advance: Callable
35 accepts: Callable
36
37 def __post_init__(self):
38 hash(self.initial)
39 if not (callable(self.advance) and callable(self.accepts)):
40 raise TypeError("A monitor needs callable advance and accepts functions.")
41
42
43
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)
47
48
49
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)
53
54
55
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)
61
62 return TemporalMonitor((False, False), advance, lambda memory: memory[1])
63
64
65
66@dataclass(frozen=True)
68 """Keep the simulator's final state and one Boolean per named monitor."""
69
70 actions: tuple
71 profile: tuple[bool, ...]
72 final_state: Hashable
73
74
75
76@dataclass(frozen=True)
78 """Report goal plans in discovery order and simulator calls, including illegal actions."""
79
80 plans: tuple[DiversePlan, ...]
81 feature_names: tuple[str, ...]
82 simulator_calls: int
83 expanded_states: int
84 width_passes: int
85 budget_exhausted: bool
86
87
88def _novel(atoms, width, seen):
89 if not atoms:
90 if not seen:
91 seen.add(frozenset())
92 return True
93 return False
94 novel = False
95 # Store all tuples on first encounter, even if an earlier tuple in
96 # the same state already made it novel.
97 for size in range(1, min(width, len(atoms)) + 1):
98 for group in combinations(atoms, size):
99 key = frozenset(group)
100 if key not in seen:
101 seen.add(key)
102 novel = True
103 return novel
104
105
106
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.
111
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.
117
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.
123
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.
135 """
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())
150 plans = {}
151 calls = expanded = 0
152
153 def progress(state, memories):
154 propositions = frozenset(labels(state))
155 return tuple(monitor.advance(memory, propositions) for monitor, memory in zip(configured, memories))
156
157 def result(passes, exhausted):
158 return DiversePlanningResult(tuple(plans.values()), names, calls, expanded, passes, exhausted)
159
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)
164
165 first = progress(start, tuple(monitor.initial for monitor in configured))
166 if goal(start):
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])
175 pruned = False
176 while queue:
177 state, memories, path = queue.popleft()
178 length = 0 if path is None else path.length
179 if depth == length:
180 continue
181 expanded += 1
182 for action in actions(state):
183 if calls == budget:
184 return result(width, True)
185 calls += 1
186 successor = simulate(state, action)
187 if successor is None:
188 continue
189 next_memories = progress(successor, memories)
190 if goal(successor):
191 keep(successor, next_memories, _Path(path, action, length + 1))
192 if len(plans) == max_plans:
193 return result(width, False)
194 continue
195 key = successor, next_memories
196 if key in visited:
197 continue
198 if state_features is not None:
199 atoms = tuple(dict.fromkeys(state_features(successor)))
200 if not _novel(atoms, width, novelty[next_memories]):
201 pruned = True
202 continue
203 visited.add(key)
204 queue.append((successor, next_memories, _Path(path, action, length + 1)))
205 if not pruned:
206 break
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.