Source code for qdpy.algorithms.forbid_planning

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Find bounded-cost plan pools and select diverse subsets.
# @see https://doi.org/10.1609/AAAI.V34I06.6543

"""Enumerate distinct plans in cost order, then select a deployment panel."""

from collections import Counter
from dataclasses import dataclass
from heapq import heappop, heappush
from itertools import count
from math import fsum, isfinite
from typing import Hashable

import numpy as np
from scipy.optimize import Bounds, LinearConstraint, milp
from scipy.sparse import coo_matrix

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

__all__ = ["CostedPlan", "ForbidPlanningResult", "action_multiset_distance", "forbid_iterative_planning"]


## @brief A complete goal-reaching plan with its measured cost and final state.
[docs] @dataclass(frozen=True, slots=True) class CostedPlan: """Action sequences are immutable tuples of hashable action identifiers.""" actions: tuple cost: float final_state: Hashable
## @brief Keep the candidate pool, selected subset, and the cost of both stages.
[docs] @dataclass(frozen=True) class ForbidPlanningResult: """A diversity-bound certificate applies to the recorded candidate pool.""" plans: tuple[CostedPlan, ...] candidates: tuple[CostedPlan, ...] simulator_calls: int solver_calls: int stop_reason: str selection_status: str minimum_distance: float | None mean_distance: float | None @property def total_cost(self): """Return the sum of selected plan costs.""" return fsum(row.cost for row in self.plans)
## @brief Compute one minus weighted Jaccard similarity of the action multisets. # @param left First CostedPlan. # @param right Second CostedPlan. # @return A dissimilarity in [0, 1], zero for two empty plans.
[docs] def action_multiset_distance(left, right): """Count repeated actions and ignore their ordering.""" a, b = Counter(left.actions), Counter(right.actions) total = sum((a | b).values()) return 1. - sum((a & b).values()) / total if total else 0.
def _plan_pool(start, actions, simulate, goal, max_depth, cost_ceiling, limit, budget, distinct): ids = count() queue = [(0., next(ids), start, None)] candidates, seen = [], set() attempts = 0 exhausted = False while queue: cost, _, state, path = heappop(queue) if goal(state): sequence = _actions(path) key = sequence if distinct == "sequence" else frozenset(Counter(sequence).items()) if key not in seen: seen.add(key) candidates.append(CostedPlan(sequence, cost, state)) if len(candidates) == limit: return tuple(candidates), attempts, "budget-exhausted" if exhausted else "pool-limit" continue depth = 0 if path is None else path.length if exhausted or depth >= max_depth: continue for action in dict.fromkeys(actions(state)): if attempts == budget: # Already simulated goals remain valid even if no more edges can be expanded. exhausted = True break attempts += 1 outcome = simulate(state, action) if outcome is None: continue successor, increment = outcome increment = float(increment) if not (0. <= increment < np.inf) or not isfinite(cost + increment): raise ValueError("Every transition needs a finite nonnegative cost and finite accumulated cost.") if cost + increment <= cost_ceiling: heappush(queue, (cost + increment, next(ids), successor, _Path(path, action, depth + 1))) return tuple(candidates), attempts, "budget-exhausted" if exhausted else "search-exhausted" def _dissimilarities(plans, distance): matrix = np.zeros((len(plans), len(plans))) for i, right in enumerate(plans): for j in range(i): value = float(distance(plans[j], right)) if not 0. <= value < np.inf: raise ValueError("Plan distance must be finite and nonnegative.") matrix[i, j] = matrix[j, i] = value return matrix def _greedy(distances, size, diversity): if size <= 1: return list(range(size)) first, second = np.triu_indices(len(distances), 1) best = int(np.argmax(distances[first, second])) selected = [int(first[best]), int(second[best])] while len(selected) < size: connections = distances[:, selected] if diversity == "mean": values = (connections / len(selected)).sum(axis=1) else: current = distances[np.ix_(selected, selected)][np.triu_indices(len(selected), 1)].min() values = np.minimum(current, connections.min(axis=1)) values[selected] = -np.inf selected.append(int(np.argmax(values))) return selected def _bounded_panel(plans, distances, size, floor): left, right = np.where(np.triu(distances < floor, 1)) count = len(left) conflicts = coo_matrix((np.ones(2 * count), (np.tile(np.arange(count), 2), np.r_[left, right])), shape=(count, len(plans))).tocsr() rows = [LinearConstraint(np.ones((1, len(plans))), size, size)] if count: rows.append(LinearConstraint(conflicts, -np.inf, 1.)) result = milp(np.asarray([row.cost for row in plans]), integrality=np.ones(len(plans)), bounds=Bounds(0., 1.), constraints=rows, options={"mip_rel_gap": 0.}) if result.status == 2: return [], "pool-infeasible" if result.status != 0 or result.x is None: return [], "unresolved" rounded = np.rint(result.x) selected = np.flatnonzero(rounded == 1.).tolist() if (not np.all(np.abs(rounded - result.x) <= 1e-6) or not np.isin(rounded, (0., 1.)).all() or len(selected) != size or np.any(distances[np.ix_(selected, selected)][np.triu_indices(size, 1)] < floor)): return [], "unresolved" return selected, "found" ## @brief Collect cost-ordered distinct plans and choose a bounded diverse subset. # @param start Initial simulator state. # @param actions Callable (state) returning hashable action identifiers in stable order. # @param simulate Pure callable (state, action) returning (successor, cost) or None for illegal moves. # @param goal Predicate on the state. # @param size Desired number of selected plans. # @param max_depth Maximum number of actions in a candidate plan. # @param budget Maximum number of simulator calls, including illegal moves. # @param pool_size Maximum number of distinct candidate plans to collect. # @param cost_ceiling Maximum cost per plan. # @param distinct Treat reordered action multisets as equivalent, or use "sequence". # @param selection Greedy diversity selection or cheapest-plan control ("cost"). # @param diversity Greedy aggregation, "mean" or "minimum" pair distance. # @param distance Symmetric nonnegative dissimilarity between completed CostedPlan values. # @param distance_floor If supplied, find the cheapest size-plan clique with that pairwise floor. # @return Plan pool, deployment panel, and simulation and selection costs.
[docs] def forbid_iterative_planning(start, *, actions, simulate, goal, size, max_depth, budget, pool_size=64, cost_ceiling=np.inf, distinct="multiset", selection="diverse", diversity="mean", distance=action_multiset_distance, distance_floor=None): """Adapt the forbid-and-select method to a bounded deterministic simulator. A shared uniform-cost frontier enumerates goal plans and forbids duplicate sequences or action multisets during collection. Plans may visit the same state via different prefixes. Expansion ends at the first goal of a path. Select a diverse subset from that pool by growing the most distant pair, or solve the paper's clique formulation to enforce a minimum pairwise separation. """ size, max_depth = _positive_int(size, "size"), _attempt_budget(max_depth) budget, pool_size = _attempt_budget(budget), _positive_int(pool_size, "pool_size") if (distinct not in ("sequence", "multiset") or selection not in ("diverse", "cost") or diversity not in ("mean", "minimum") or not 0. <= cost_ceiling <= np.inf or (distance_floor is not None and not 0. <= distance_floor < np.inf)): raise ValueError("Use valid selection and distinctness modes and nonnegative quality/diversity bounds.") if not all(callable(fn) for fn in (actions, simulate, goal, distance)): raise TypeError("Supply callable actions, simulate, goal, and distance.") pool, attempts, stop = _plan_pool(start, actions, simulate, goal, max_depth, cost_ceiling, pool_size, budget, distinct) distances = _dissimilarities(pool, distance) available, solver_calls = min(size, len(pool)), 0 status = "found" if len(pool) >= size else "insufficient" if distance_floor is not None and status == "found": selected, status = _bounded_panel(pool, distances, size, distance_floor) solver_calls = 1 elif distance_floor is not None: selected = [] elif selection == "cost": selected = list(range(available)) else: selected = _greedy(distances, available, diversity) gaps = distances[np.ix_(selected, selected)][np.triu_indices(len(selected), 1)] return ForbidPlanningResult(tuple(pool[i] for i in selected), pool, attempts, solver_calls, stop, status, float(gaps.min()) if gaps.size else None, fsum(float(gap) / len(gaps) for gap in gaps) if gaps.size else None)