6"""Search over weighted action scripts, then illuminate the resulting planners."""
8from dataclasses
import dataclass, field
9from math
import isfinite, log, log1p, sqrt
13from ._population
import _attempt_budget, _finite_vector
14from .modern
import _positive_int
15from .subgoal_mcts
import MCTSPlan, _Search, _backup, _return
16from .task_search
import _measurement, _offer, _validate_grid
18__all__ = [
"PortfolioMCTSResult",
"PortfolioQDResult",
"portfolio_mcts",
"portfolio_map_elites"]
22@dataclass(frozen=True)
24 """The root action list is in weighted script priority order."""
35@dataclass(frozen=True)
37 """A measurement attempt evaluates the whole scenario panel."""
49 terminated: bool =
False
52 ranked: tuple |
None =
None
53 edges: list = field(default_factory=list)
65 def __init__(self, scripts, weights, simulate, budget, horizon, discount, exploration,
66 fraction, rate, unprune_at, bias, seed):
67 super().__init__(self.
_rank, simulate, budget, horizon, discount, exploration, seed)
71 def _rank(self, state):
74 for action, value
in script(state):
76 if not 0 <= value <= 1.:
77 raise ValueError(
"Script action scores must be finite and in [0, 1].")
78 priority[action] = max(priority.get(action, 0.), value * weight)
79 return tuple(sorted(priority.items(), key=
lambda row: -row[1]))
81 def _allowed(self, node):
82 n = len(node.ranked
or ())
85 initial = max(1, int(np.ceil(self.
fraction * n)))
88 extra = 1 + int(log(node.visits / self.
unprune_at) / log(self.
rate))
89 return min(n, initial + extra)
91 def _tree_phase(self, root):
93 nodes, actions, rewards = [root], [], []
97 if node.ranked
is None:
98 node.ranked = self.
_rank(node.state)
102 new_edge = len(node.edges) < limit
104 action, heuristic = node.ranked[len(node.edges)]
105 state, reward, terminal = self.
_step(node.state, action,
False)
106 edge =
_Edge(action, heuristic, reward,
_Node(state, terminal))
107 node.edges.append(edge)
109 edge = max(node.edges, key=
lambda entry: (
110 entry.reward + self.
discount * entry.node.total / entry.node.visits
111 + self.
exploration * sqrt(log1p(node.visits) / entry.node.visits)
112 + self.
bias * entry.heuristic / (1 + entry.node.visits)
114 actions.append(edge.action)
115 rewards.append(edge.reward)
120 return nodes, actions, rewards
122 def simulate_one(self, root):
124 state, term = nodes[-1].state, nodes[-1].terminated
125 tree_steps = len(rewards)
127 while tree_steps
and len(actions) < self.
horizon and self.
calls < self.
budget and not term:
128 options = self.
_rank(state)
131 weights = np.asarray([value
for _, value
in options])
132 slot = self.
rng.choice(len(options), p=weights / weights.sum()
if weights.sum()
else None)
133 action = options[slot][0]
134 state, reward, term = self.
_step(state, action,
False)
135 actions.append(action)
136 rewards.append(reward)
139 leaf_value = _return(rewards[tree_steps:], self.
discount)
140 _backup(nodes[-1], leaf_value)
141 for i
in range(tree_steps - 1, -1, -1):
142 leaf_value = rewards[i] + self.
discount * leaf_value
143 _backup(nodes[i], leaf_value)
144 if not isfinite(leaf_value):
145 raise ValueError(
"The discounted plan return overflowed.")
146 candidate =
MCTSPlan(tuple(actions), state, tuple(rewards), term)
147 key = (leaf_value, term, -len(actions))
170def portfolio_mcts(start, *, scripts, weights, simulate, budget, horizon, simulations=None,
171 initial_fraction=.5, unprune_at=4, unprune_rate=2., exploration=1.414,
172 progressive_bias=1., discount=1., seed=0):
173 """Rank duplicate suggestions by their strongest weighted score.
175 At each node, start with the most preferred fraction of actions and
176 gradually expose the rest as visits accumulate. Score visited actions
177 by UCB with a decaying script bias. Cache deterministic tree edges,
178 and charge every actual simulator call, including rollouts.
180 scripts = tuple(scripts)
181 weights = _finite_vector(weights,
"Script weights", len(scripts))
182 if (
not all(map(callable, scripts))
or not all(0 <= value <= 1.
for value
in weights)
183 or not (0 < initial_fraction <= 1
and 1 < unprune_rate < np.inf)
184 or not 0 <= progressive_bias < np.inf):
185 raise ValueError(
"Use callable scripts, weights in [0, 1], and finite exploration settings.")
186 budget = _attempt_budget(budget)
187 repeats = budget
if simulations
is None else _attempt_budget(simulations)
188 unprune_at = _positive_int(unprune_at,
"unprune_at")
189 planner =
_Planner(scripts, weights, simulate, budget, horizon, discount, exploration,
190 initial_fraction, unprune_rate, unprune_at, progressive_bias, seed)
192 for _
in range(repeats):
193 if planner.calls >= budget
or not planner.simulate_one(root):
195 plan =
MCTSPlan((), start, (),
False)
if planner.best
is None else planner.best
196 return PortfolioMCTSResult(plan, planner.calls, planner.simulations, tuple(a
for a, _
in root.ranked
or ()),
197 planner._allowed(root), len(root.edges))
213def portfolio_map_elites(archive, scenarios, *, scripts, simulate, summarize, budget, plan_budget, horizon,
214 random_initial=8, planner_options=None, seed=0):
215 """Seed with one active script at a time and then mutate one weight per proposal."""
216 _validate_grid(archive)
217 if not callable(summarize)
or not callable(simulate):
218 raise TypeError(
"Supply callable simulator and plan summarizer.")
219 budget, random_initial = _attempt_budget(budget), _attempt_budget(random_initial)
220 plan_budget, horizon = _attempt_budget(plan_budget), _positive_int(horizon,
"horizon")
221 scripts, scenarios = tuple(scripts), tuple(scenarios)
222 if not scenarios
or not scripts
or not all(map(callable, scripts)):
223 raise ValueError(
"Supply a nonempty panel and callable scripts.")
224 options = {}
if planner_options
is None else dict(planner_options)
225 if archive.fitness_weights
is None:
226 archive._set_fitness_weights((1.,))
227 rng = np.random.default_rng(seed)
228 plan_seeds = rng.integers(2**32, size=len(scenarios))
230 before = archive.nb_added
231 for step
in range(budget):
232 if step < len(scripts):
233 weights = np.zeros(len(scripts))
235 elif step < len(scripts) + random_initial
or not archive:
236 weights = rng.uniform(0., .1, size=len(scripts))
238 weights = np.asarray(archive[rng.integers(len(archive))], dtype=float).copy()
239 weights[rng.integers(len(scripts))] = rng.random()
240 payload = tuple(map(float, weights))
241 planned = tuple(portfolio_mcts(state, scripts=scripts, weights=payload, simulate=simulate,
242 budget=plan_budget, horizon=horizon, seed=int(plan_seed), **options)
243 for state, plan_seed
in zip(scenarios, plan_seeds))
244 calls += sum(row.simulator_calls
for row
in planned)
245 _offer(archive, _measurement(archive, summarize(tuple(row.plan
for row
in planned)), payload))
246 return PortfolioQDResult(archive, budget, budget * len(scenarios), calls, archive.nb_added - before)
A measured path and the planner's simulation and branching counts.
A planner repertoire with separately counted outer and inner work.
A measured simulator path, with its primitive actions and rewards.
_step(self, state, action, low_level)