# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Weighted script portfolios with progressive unpruning and MAP-Elites.
# @see https://doi.org/10.1109/CoG52621.2021.9619094
"""Search over weighted action scripts, then illuminate the resulting planners."""
from dataclasses import dataclass, field
from math import isfinite, log, log1p, sqrt
import numpy as np
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
from .subgoal_mcts import MCTSPlan, _Search, _backup, _return
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["PortfolioMCTSResult", "PortfolioQDResult", "portfolio_mcts", "portfolio_map_elites"]
## @brief A measured path and the planner's simulation and branching counts.
[docs]
@dataclass(frozen=True)
class PortfolioMCTSResult:
"""The root action list is in weighted script priority order."""
plan: MCTSPlan
simulator_calls: int
simulations: int
root_actions: tuple
root_open: int
root_expanded: int
## @brief A planner repertoire with separately counted outer and inner work.
[docs]
@dataclass(frozen=True)
class PortfolioQDResult:
"""A measurement attempt evaluates the whole scenario panel."""
archive: object
evaluations: int
plans: int
simulator_calls: int
admissions: int
@dataclass
class _Node:
state: object
terminated: bool = False
visits: int = 0
total: float = 0.
ranked: tuple | None = None
edges: list = field(default_factory=list)
@dataclass
class _Edge:
action: object
heuristic: float
reward: float
node: _Node
class _Planner(_Search):
def __init__(self, scripts, weights, simulate, budget, horizon, discount, exploration,
fraction, rate, unprune_at, bias, seed):
super().__init__(self._rank, simulate, budget, horizon, discount, exploration, seed)
self.scripts, self.weights = scripts, weights
self.fraction, self.rate, self.unprune_at, self.bias = fraction, rate, unprune_at, bias
def _rank(self, state):
priority = {}
for script, weight in zip(self.scripts, self.weights):
for action, value in script(state):
value = float(value)
if not 0 <= value <= 1.:
raise ValueError("Script action scores must be finite and in [0, 1].")
priority[action] = max(priority.get(action, 0.), value * weight)
return tuple(sorted(priority.items(), key=lambda row: -row[1]))
def _allowed(self, node):
n = len(node.ranked or ())
if n == 0:
return 0
initial = max(1, int(np.ceil(self.fraction * n)))
if node.visits < self.unprune_at:
return initial
extra = 1 + int(log(node.visits / self.unprune_at) / log(self.rate))
return min(n, initial + extra)
def _tree_phase(self, root):
node = root
nodes, actions, rewards = [root], [], []
for _ in range(self.horizon):
if node.terminated:
break
if node.ranked is None:
node.ranked = self._rank(node.state)
limit = self._allowed(node)
if not limit:
break
new_edge = len(node.edges) < limit
if new_edge:
action, heuristic = node.ranked[len(node.edges)]
state, reward, terminal = self._step(node.state, action, False)
edge = _Edge(action, heuristic, reward, _Node(state, terminal))
node.edges.append(edge)
else:
edge = max(node.edges, key=lambda entry: (
entry.reward + self.discount * entry.node.total / entry.node.visits
+ self.exploration * sqrt(log1p(node.visits) / entry.node.visits)
+ self.bias * entry.heuristic / (1 + entry.node.visits)
))
actions.append(edge.action)
rewards.append(edge.reward)
node = edge.node
nodes.append(node)
if new_edge:
break
return nodes, actions, rewards
def simulate_one(self, root):
nodes, actions, rewards = self._tree_phase(root)
state, term = nodes[-1].state, nodes[-1].terminated
tree_steps = len(rewards)
# A rollout samples only actions proposed by the scripts.
while tree_steps and len(actions) < self.horizon and self.calls < self.budget and not term:
options = self._rank(state)
if not options:
break
weights = np.asarray([value for _, value in options])
slot = self.rng.choice(len(options), p=weights / weights.sum() if weights.sum() else None)
action = options[slot][0]
state, reward, term = self._step(state, action, False)
actions.append(action)
rewards.append(reward)
if not actions:
return False
leaf_value = _return(rewards[tree_steps:], self.discount)
_backup(nodes[-1], leaf_value)
for i in range(tree_steps - 1, -1, -1):
leaf_value = rewards[i] + self.discount * leaf_value
_backup(nodes[i], leaf_value)
if not isfinite(leaf_value):
raise ValueError("The discounted plan return overflowed.")
candidate = MCTSPlan(tuple(actions), state, tuple(rewards), term)
key = (leaf_value, term, -len(actions))
if self.best is None or key > self._best_key:
self.best, self._best_key = candidate, key
self.simulations += 1
return True
## @brief Plan with weighted scripts and a visit-dependent expansion limit.
# @param start Initial simulator state.
# @param scripts Ordered callables (state) yielding legal (action, score) pairs.
# @param weights Nonnegative script weights in [0, 1].
# @param simulate Pure callable (state, action) returning (successor, reward, terminated).
# @param budget Hard cap on simulator transitions.
# @param horizon Maximum simulated actions in each path.
# @param simulations Maximum tree simulations, default equal to budget.
# @param initial_fraction Fraction of ranked actions eligible at the start.
# @param unprune_at Visits before the first extra action becomes eligible.
# @param unprune_rate Exponential growth in intervals between newly eligible actions.
# @param exploration UCB exploration coefficient.
# @param progressive_bias Coefficient of the decaying script heuristic.
# @param discount Return discount in (0, 1].
# @param seed Private seed for weighted rollouts.
# @return Best measured path and budget statistics.
[docs]
def portfolio_mcts(start, *, scripts, weights, simulate, budget, horizon, simulations=None,
initial_fraction=.5, unprune_at=4, unprune_rate=2., exploration=1.414,
progressive_bias=1., discount=1., seed=0):
"""Rank duplicate suggestions by their strongest weighted score.
At each node, start with the most preferred fraction of actions and
gradually expose the rest as visits accumulate. Score visited actions
by UCB with a decaying script bias. Cache deterministic tree edges,
and charge every actual simulator call, including rollouts.
"""
scripts = tuple(scripts)
weights = _finite_vector(weights, "Script weights", len(scripts))
if (not all(map(callable, scripts)) or not all(0 <= value <= 1. for value in weights)
or not (0 < initial_fraction <= 1 and 1 < unprune_rate < np.inf)
or not 0 <= progressive_bias < np.inf):
raise ValueError("Use callable scripts, weights in [0, 1], and finite exploration settings.")
budget = _attempt_budget(budget)
repeats = budget if simulations is None else _attempt_budget(simulations)
unprune_at = _positive_int(unprune_at, "unprune_at")
planner = _Planner(scripts, weights, simulate, budget, horizon, discount, exploration,
initial_fraction, unprune_rate, unprune_at, progressive_bias, seed)
root = _Node(start)
for _ in range(repeats):
if planner.calls >= budget or not planner.simulate_one(root):
break
plan = MCTSPlan((), start, (), False) if planner.best is None else planner.best
return PortfolioMCTSResult(plan, planner.calls, planner.simulations, tuple(a for a, _ in root.ranked or ()),
planner._allowed(root), len(root.edges))
## @brief Run the outer MAP-Elites search over script weights.
# @param archive Empty scalar Grid or CVTGrid for planner strategies.
# @param scenarios Ordered panel of initial simulator states.
# @param scripts Ordered action-ranking callbacks.
# @param simulate Deterministic transition callback used by every planner.
# @param summarize Callable (plans) returning ((fitness,), descriptors).
# @param budget Number of weight vectors to evaluate.
# @param plan_budget Maximum simulator calls per candidate and scenario.
# @param horizon Maximum path length in each plan.
# @param random_initial Number of random samples after single-script seeds.
# @param planner_options Optional keyword options for portfolio_mcts.
# @param seed Private outer search and scenario seed.
# @return PortfolioQDResult with the archive and counts.
[docs]
def portfolio_map_elites(archive, scenarios, *, scripts, simulate, summarize, budget, plan_budget, horizon,
random_initial=8, planner_options=None, seed=0):
"""Seed with one active script at a time and then mutate one weight per proposal."""
_validate_grid(archive)
if not callable(summarize) or not callable(simulate):
raise TypeError("Supply callable simulator and plan summarizer.")
budget, random_initial = _attempt_budget(budget), _attempt_budget(random_initial)
plan_budget, horizon = _attempt_budget(plan_budget), _positive_int(horizon, "horizon")
scripts, scenarios = tuple(scripts), tuple(scenarios)
if not scenarios or not scripts or not all(map(callable, scripts)):
raise ValueError("Supply a nonempty panel and callable scripts.")
options = {} if planner_options is None else dict(planner_options)
if archive.fitness_weights is None:
archive._set_fitness_weights((1.,))
rng = np.random.default_rng(seed)
plan_seeds = rng.integers(2**32, size=len(scenarios))
calls = 0
before = archive.nb_added
for step in range(budget):
if step < len(scripts):
weights = np.zeros(len(scripts))
weights[step] = 1.
elif step < len(scripts) + random_initial or not archive:
weights = rng.uniform(0., .1, size=len(scripts))
else:
weights = np.asarray(archive[rng.integers(len(archive))], dtype=float).copy()
weights[rng.integers(len(scripts))] = rng.random()
payload = tuple(map(float, weights))
planned = tuple(portfolio_mcts(state, scripts=scripts, weights=payload, simulate=simulate,
budget=plan_budget, horizon=horizon, seed=int(plan_seed), **options)
for state, plan_seed in zip(scenarios, plan_seeds))
calls += sum(row.simulator_calls for row in planned)
_offer(archive, _measurement(archive, summarize(tuple(row.plan for row in planned)), payload))
return PortfolioQDResult(archive, budget, budget * len(scenarios), calls, archive.nb_added - before)