QDpy
Loading...
Searching...
No Matches
forbid_planning.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Enumerate distinct plans in cost order, then select a deployment panel."""
7
8from collections import Counter
9from dataclasses import dataclass
10from heapq import heappop, heappush
11from itertools import count
12from math import fsum, isfinite
13from typing import Hashable
14
15import numpy as np
16from scipy.optimize import Bounds, LinearConstraint, milp
17from scipy.sparse import coo_matrix
18
19from ._population import _attempt_budget
20from .go_explore import _Path, _actions
21from .modern import _positive_int
22
23__all__ = ["CostedPlan", "ForbidPlanningResult", "action_multiset_distance", "forbid_iterative_planning"]
24
25
26
27@dataclass(frozen=True, slots=True)
29 """Action sequences are immutable tuples of hashable action identifiers."""
30
31 actions: tuple
32 cost: float
33 final_state: Hashable
34
35
36
37@dataclass(frozen=True)
39 """A diversity-bound certificate applies to the recorded candidate pool."""
40
41 plans: tuple[CostedPlan, ...]
42 candidates: tuple[CostedPlan, ...]
43 simulator_calls: int
44 solver_calls: int
45 stop_reason: str
46 selection_status: str
47 minimum_distance: float | None
48 mean_distance: float | None
49
50 @property
51 def total_cost(self):
52 """Return the sum of selected plan costs."""
53 return fsum(row.cost for row in self.plans)
54
55
56
60def action_multiset_distance(left, right):
61 """Count repeated actions and ignore their ordering."""
62 a, b = Counter(left.actions), Counter(right.actions)
63 total = sum((a | b).values())
64 return 1. - sum((a & b).values()) / total if total else 0.
65
66
67def _plan_pool(start, actions, simulate, goal, max_depth, cost_ceiling, limit, budget, distinct):
68 ids = count()
69 queue = [(0., next(ids), start, None)]
70 candidates, seen = [], set()
71 attempts = 0
72 exhausted = False
73 while queue:
74 cost, _, state, path = heappop(queue)
75 if goal(state):
76 sequence = _actions(path)
77 key = sequence if distinct == "sequence" else frozenset(Counter(sequence).items())
78 if key not in seen:
79 seen.add(key)
80 candidates.append(CostedPlan(sequence, cost, state))
81 if len(candidates) == limit:
82 return tuple(candidates), attempts, "budget-exhausted" if exhausted else "pool-limit"
83 continue
84 depth = 0 if path is None else path.length
85 if exhausted or depth >= max_depth:
86 continue
87 for action in dict.fromkeys(actions(state)):
88 if attempts == budget:
89 # Already simulated goals remain valid even if no more edges can be expanded.
90 exhausted = True
91 break
92 attempts += 1
93 outcome = simulate(state, action)
94 if outcome is None:
95 continue
96 successor, increment = outcome
97 increment = float(increment)
98 if not (0. <= increment < np.inf) or not isfinite(cost + increment):
99 raise ValueError("Every transition needs a finite nonnegative cost and finite accumulated cost.")
100 if cost + increment <= cost_ceiling:
101 heappush(queue, (cost + increment, next(ids), successor, _Path(path, action, depth + 1)))
102 return tuple(candidates), attempts, "budget-exhausted" if exhausted else "search-exhausted"
103
104
105def _dissimilarities(plans, distance):
106 matrix = np.zeros((len(plans), len(plans)))
107 for i, right in enumerate(plans):
108 for j in range(i):
109 value = float(distance(plans[j], right))
110 if not 0. <= value < np.inf:
111 raise ValueError("Plan distance must be finite and nonnegative.")
112 matrix[i, j] = matrix[j, i] = value
113 return matrix
114
115
116def _greedy(distances, size, diversity):
117 if size <= 1:
118 return list(range(size))
119 first, second = np.triu_indices(len(distances), 1)
120 best = int(np.argmax(distances[first, second]))
121 selected = [int(first[best]), int(second[best])]
122 while len(selected) < size:
123 connections = distances[:, selected]
124 if diversity == "mean":
125 values = (connections / len(selected)).sum(axis=1)
126 else:
127 current = distances[np.ix_(selected, selected)][np.triu_indices(len(selected), 1)].min()
128 values = np.minimum(current, connections.min(axis=1))
129 values[selected] = -np.inf
130 selected.append(int(np.argmax(values)))
131 return selected
132
133
134def _bounded_panel(plans, distances, size, floor):
135 left, right = np.where(np.triu(distances < floor, 1))
136 count = len(left)
137 conflicts = coo_matrix((np.ones(2 * count), (np.tile(np.arange(count), 2), np.r_[left, right])),
138 shape=(count, len(plans))).tocsr()
139 rows = [LinearConstraint(np.ones((1, len(plans))), size, size)]
140 if count:
141 rows.append(LinearConstraint(conflicts, -np.inf, 1.))
142 result = milp(np.asarray([row.cost for row in plans]), integrality=np.ones(len(plans)),
143 bounds=Bounds(0., 1.), constraints=rows, options={"mip_rel_gap": 0.})
144 if result.status == 2:
145 return [], "pool-infeasible"
146 if result.status != 0 or result.x is None:
147 return [], "unresolved"
148 rounded = np.rint(result.x)
149 selected = np.flatnonzero(rounded == 1.).tolist()
150 if (not np.all(np.abs(rounded - result.x) <= 1e-6) or not np.isin(rounded, (0., 1.)).all()
151 or len(selected) != size or np.any(distances[np.ix_(selected, selected)][np.triu_indices(size, 1)] < floor)):
152 return [], "unresolved"
153 return selected, "found"
154
155
156
172def forbid_iterative_planning(start, *, actions, simulate, goal, size, max_depth, budget, pool_size=64,
173 cost_ceiling=np.inf, distinct="multiset", selection="diverse", diversity="mean",
174 distance=action_multiset_distance, distance_floor=None):
175 """Adapt the forbid-and-select method to a bounded deterministic simulator.
176
177 A shared uniform-cost frontier enumerates goal plans and forbids
178 duplicate sequences or action multisets during collection. Plans may
179 visit the same state via different prefixes. Expansion ends at the
180 first goal of a path. Select a diverse subset from that pool by
181 growing the most distant pair, or solve the paper's clique formulation
182 to enforce a minimum pairwise separation.
183 """
184 size, max_depth = _positive_int(size, "size"), _attempt_budget(max_depth)
185 budget, pool_size = _attempt_budget(budget), _positive_int(pool_size, "pool_size")
186 if (distinct not in ("sequence", "multiset") or selection not in ("diverse", "cost")
187 or diversity not in ("mean", "minimum") or not 0. <= cost_ceiling <= np.inf
188 or (distance_floor is not None and not 0. <= distance_floor < np.inf)):
189 raise ValueError("Use valid selection and distinctness modes and nonnegative quality/diversity bounds.")
190 if not all(callable(fn) for fn in (actions, simulate, goal, distance)):
191 raise TypeError("Supply callable actions, simulate, goal, and distance.")
192 pool, attempts, stop = _plan_pool(start, actions, simulate, goal, max_depth, cost_ceiling, pool_size,
193 budget, distinct)
194 distances = _dissimilarities(pool, distance)
195 available, solver_calls = min(size, len(pool)), 0
196 status = "found" if len(pool) >= size else "insufficient"
197 if distance_floor is not None and status == "found":
198 selected, status = _bounded_panel(pool, distances, size, distance_floor)
199 solver_calls = 1
200 elif distance_floor is not None:
201 selected = []
202 elif selection == "cost":
203 selected = list(range(available))
204 else:
205 selected = _greedy(distances, available, diversity)
206 gaps = distances[np.ix_(selected, selected)][np.triu_indices(len(selected), 1)]
207 return ForbidPlanningResult(tuple(pool[i] for i in selected), pool, attempts, solver_calls, stop, status,
208 float(gaps.min()) if gaps.size else None,
209 fsum(float(gap) / len(gaps) for gap in gaps) if gaps.size else None)
A complete goal-reaching plan with its measured cost and final state.
Keep the candidate pool, selected subset, and the cost of both stages.