5"""Small reproducible pilots for portfolios and behaviour repertoires."""
8from dataclasses
import asdict
9from itertools
import combinations, product
11from pathlib
import Path
14from scipy.optimize
import LinearConstraint
16from qdpy.algorithms import fit_tabular_successor_features, solve_binary_portfolio
20def _distance(first, second):
21 return sum(a != b
for a, b
in zip(first, second, strict=
True))
25def portfolio_trials(seed):
26 """Write exact, quality-ranked, and greedy portfolios for a binary selection task."""
27 rng = np.random.default_rng(seed)
28 objective = rng.permutation(np.arange(1, 8))
29 constraint = LinearConstraint([[1] * 7, [1, 1, 0, 0, 0, 0, 0]], [3., 0.], [3., 1.])
30 exact = solve_binary_portfolio(objective, 3, quality_loss=4., constraints=constraint)
31 candidates = sorted((int(objective @ point), point)
for point
in product((0, 1), repeat=7)
32 if sum(point) == 3
and sum(point[:2]) <= 1)
33 best = candidates[-1][0]
34 candidates = [(quality, point)
for quality, point
in reversed(candidates)
if quality >= best - 4]
35 points = [point
for _, point
in candidates]
36 expected = max(min(_distance(a, b)
for a, b
in combinations(group, 2))
37 for group
in combinations(points, 3))
38 assert exact.status ==
"optimal" and exact.minimum_distance == expected
and exact.optimum == best
40 while len(greedy) < 3:
41 greedy.append(max((p
for p
in points
if p
not in greedy),
42 key=
lambda p: min(_distance(p, q)
for q
in greedy)))
43 for method, designs
in ((
"joint-milp", exact.designs), (
"quality-rank", points[:3]), (
"greedy", greedy)):
44 yield dict(task=
"portfolio", method=method, seed=seed, reference_optimum=best,
45 eligible_designs=len(points), oracle_distance=expected,
46 mean_quality=float(np.mean([objective @ point
for point
in designs])),
47 distance=min(_distance(a, b)
for a, b
in combinations(designs, 2)),
48 solver_calls=exact.solver_calls
if method ==
"joint-milp" else 0)
52def transfer_trials(seed):
53 """Preserve two source policies for a sequence of gates with different payoffs."""
54 rng = np.random.default_rng(seed)
55 dynamics = np.zeros((5, 2, 5))
56 dynamics[np.arange(4), :, np.arange(1, 5)] = 1.
57 features = np.zeros((5, 2, 2))
58 regimes = np.array([0, 1, 0, 1, 1])
59 features[np.arange(5), 0, regimes] = rng.uniform(1.3, 2.3, 5)
60 features[np.arange(5), 1, 1 - regimes] = rng.uniform(1.3, 2.3, 5)
61 source = np.stack((regimes, 1 - regimes))
63 repertoire = fit_tabular_successor_features(dynamics, features, source, gamma=gamma)
64 results = {
"gpi": [],
"best-source": [],
"oracle": []}
65 for ratio
in np.linspace(.1, .9, 9):
66 reward = np.array([ratio, 1 - ratio])
67 table = features @ reward
68 discount = gamma ** np.arange(len(table))
69 indices = np.arange(len(table))
70 results[
"gpi"].append(float(discount @ table[indices, repertoire.action_table(reward)]))
71 results[
"best-source"].append(float(np.max(table[indices, source] @ discount)))
72 results[
"oracle"].append(float(discount @ table.max(axis=1)))
73 for method, values
in results.items():
74 yield dict(task=
"transfer", method=method, seed=seed, heldout_weights=len(values),
75 mean_return=float(np.mean(values)), regret=float(np.mean(np.subtract(results[
"oracle"], values))),
76 source_policies=len(source), real_steps=0)
80def branch_trials(seed, budget):
81 """Use one native grid and matched real-step budgets across all methods."""
82 import gymnasium
as gym
85 from qdpy.rl import PGAMAPElites, PolicyConfig, SVQDRL, TD3Config
87 torch.set_num_threads(1)
89 class Velocity(gym.Env):
90 observation_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
91 action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32)
93 def reset(self, *, seed=None, options=None):
94 super().reset(seed=seed)
95 self.velocity, self.goal = self.np_random.uniform(-.2, .2), self.np_random.uniform(-.7, .7)
96 return np.array([self.velocity, self.goal], np.float32), {}
98 def step(self, action):
99 self.velocity = .65 * self.velocity + .35 * float(action[0])
100 reward = 1. / (1. + (self.velocity - self.goal) ** 2)
101 return np.array([self.velocity, self.goal], np.float32), reward,
False,
False, {}
105 def descriptor(episode):
106 return (float(episode.observations[1:, 0].mean(dtype=np.float64)),)
109 return Grid(shape=9, features_domain=((-1., 1.),), fitness_domain=((0., horizon),),
110 fitness_weights=(1.,))
113 cells, returns, steps = {}, [], 0
114 with Velocity()
as env:
115 for elite
in search.archive:
116 actor = search.policy_for(elite)
117 positions, scores = [], []
118 for reset
in range(3):
119 observation, _ = env.reset(seed=100000 + 4 * seed + reset)
121 for _
in range(horizon):
122 observation, reward, _, _, _ = env.step(actor.act(observation))
123 positions.append(float(observation[0]))
126 scores.append(sum(run))
127 quality = float(np.mean(scores))
128 cell = search.archive.index_grid([np.mean(positions)])
129 cells[cell] = max(cells.get(cell, 0.), quality)
130 returns.append(quality)
131 return dict(audit_cells=len(cells), audit_qd_score=sum(cells.values()), audit_steps=steps,
132 audit_mean_return=float(np.mean(returns))
if returns
else None)
134 td3 = TD3Config(replay_capacity=96, batch_size=12, learning_starts=12, critic_hidden_sizes=(16,))
135 for method
in (
"sv-qd-rl",
"dense-branches",
"shared-critic",
"pga-me"):
137 options = dict(descriptor=descriptor, policy=PolicyConfig((12, 8)), td3=td3,
138 max_episode_steps=horizon, seed=seed)
139 if method ==
"pga-me":
140 search = PGAMAPElites(Velocity, archive, initial_policies=4, batch_size=4,
141 critic_steps=4, pg_steps=2, **options)
143 search = SVQDRL(Velocity, archive, branch_capacity=8, training_steps_per_candidate=24,
144 keep_fractions=(.5, .25), masks=method !=
"dense-branches",
145 private_critics=method !=
"shared-critic", **options)
146 result = search.train(budget)
147 sparsity = [entry.sparsity
for entry
in getattr(search,
"branches", ())]
148 yield dict(task=
"velocity-branches", method=method, seed=seed, env_steps=result.env_steps,
149 archive_cells=len(archive), archive_qd_score=archive.qd_score(),
150 mean_branch_sparsity=float(np.mean(sparsity))
if sparsity
else None,
151 **audit(search), **asdict(result))
156 parser = argparse.ArgumentParser(description=__doc__)
157 parser.add_argument(
"task", choices=(
"portfolio",
"transfer",
"branches"), nargs=
"?")
158 parser.add_argument(
"--seeds", nargs=
"+", type=int, default=[11, 23, 47])
159 parser.add_argument(
"--steps", type=int, default=1536)
160 parser.add_argument(
"--output", type=Path)
161 args = parser.parse_args()
163 parser.error(
"--steps must be positive.")
164 trials = dict(portfolio=portfolio_trials, transfer=transfer_trials,
165 branches=
lambda seed: branch_trials(seed, args.steps))
167 for task
in (args.task,)
if args.task
else (
"portfolio",
"transfer"):
168 for seed
in args.seeds:
169 for row
in trials[task](seed):
170 line = json.dumps(row, allow_nan=
False, sort_keys=
True)
173 if args.output
is not None:
174 args.output.parent.mkdir(parents=
True, exist_ok=
True)
175 args.output.write_text(
"\n".join(records) +
"\n", encoding=
"utf-8")
178if __name__ ==
"__main__":