QDpy
Loading...
Searching...
No Matches
layered_illumination.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3
5
6"""Run six reproducible demonstrations with independent measurement budgets."""
7
8import argparse
9import json
10
11import numpy as np
12
13from qdpy.algorithms import age_layered_map_elites, minimize_surprise_map_elites, multi_decoder_map_elites
14from qdpy.benchmarks import generate_local_optima_benchmarks
15from qdpy.containers import Grid
16from qdpy.phenotype import Features, Fitness, Individual
17
18
19def _grid(shape, features=None, direction=1.):
20 return Grid(shape=shape, features_domain=((0., 1.),) * len(shape) if features is None else features,
21 fitness_domain=((-np.inf, np.inf),), fitness_weights=(direction,))
22
23
24def _update(grid, genome, fitness, descriptor):
25 grid.add(Individual(genome, fitness=Fitness((fitness,), weights=grid.fitness_weights),
26 features=Features(descriptor)))
27
28
29def layers(seed):
30 def sample(rng):
31 return rng.random(3)
32
33 def mutate(parent, rng):
34 return np.clip(parent + rng.normal(0., .13, 3), 0., 1.)
35
36 def evaluate(genome):
37 x, y, z = genome
38 return max(0., 1. - (z - np.cos(3 * x + 2 * y) ** 2) ** 2), ((x,), (y,))
39
40 budgets = 192
41 search = age_layered_map_elites((_grid((8,)), _grid((8,))), evaluate, sample=sample,
42 mutate=mutate, max_ages=(22,), budget=budgets,
43 immigrant_interval=6, seed=seed)
44 control = _grid((4, 4))
45 rng = np.random.default_rng(seed)
46 for i in range(budgets):
47 child = sample(rng) if i % 6 == 0 or not control else mutate(control[int(rng.integers(len(control)))], rng)
48 quality, features = evaluate(child)
49 _update(control, child, quality, (features[0][0], features[1][0]))
50 for method, archives, promotions in (("age-layered", search.archives, sum(search.promotions)),
51 ("joint-grid", (control,), 0)):
52 audit = _grid((8, 8))
53 for grid in archives:
54 for row in grid:
55 _update(audit, row, row.fitness.values[0], tuple(row[:2]))
56 yield dict(method=method, evaluations=budgets, capacity=16, promotions=promotions,
57 audit_cells=len(audit), audit_score=float(sum(row.fitness.values[0] for row in audit)))
58
59
60def decoders(seed):
61 rng = np.random.default_rng(982)
62 positions = rng.random((10, 2))
63 demands = (2, 2, 3, 3, 2, 1, 3, 2, 2, 2)
64 capacity = 6
65 depot = np.array((.5, .5))
66
67 def decode(tour, first_fit):
68 routes, loads = [], []
69 for visit in tour:
70 slots = range(len(routes)) if first_fit else range(max(0, len(routes) - 1), len(routes))
71 slot = next((i for i in slots if loads[i] + demands[visit] <= capacity), len(routes))
72 if slot == len(routes):
73 routes.append([])
74 loads.append(0)
75 routes[slot].append(visit)
76 loads[slot] += demands[visit]
77 return routes
78
79 def evaluate(routes):
80 distances = []
81 for route in routes:
82 points = np.vstack((depot, positions[route], depot))
83 distances.append(float(np.linalg.norm(np.diff(points, axis=0), axis=1).sum()))
84 return sum(distances), (float(len(routes)), max(distances))
85
86 def swap(parent, rng):
87 child = list(parent)
88 i, j = map(int, rng.choice(len(child), 2, replace=False))
89 child[i], child[j] = child[j], child[i]
90 return child
91
92 def reverse(parent, rng):
93 i, j = sorted(map(int, rng.choice(len(parent), 2, replace=False)))
94 return (*parent[:i], *reversed(parent[i:j+1]), *parent[j+1:])
95
96 both = (lambda genome: decode(genome, False), lambda genome: decode(genome, True))
97 for name, rule, choices in (("single-decoder", "round_robin", both[:1]), ("multi-round-robin", "round_robin", both),
98 ("multi-bandit", "ucb1", both)):
99 grid = _grid((6, 12), ((3., 9.), (0., 6.)), -1.)
100 result = multi_decoder_map_elites(grid, evaluate, sample=lambda rng: rng.permutation(len(demands)),
101 emitters=(swap, reverse), decoders=choices, budget=200, seed=seed)
102 yield dict(method=name, calls=result.objective_calls, proposals=result.proposals, cells=len(grid),
103 best_distance=grid.best.fitness.values[0], emitter_calls=result.emitter_calls)
104
105
106def predict(seed):
107 def rollout(genome, world):
108 target, feedback, gain, drift = genome
109 rng = np.random.default_rng(world)
110 state = rng.random(4)
111 predicted, measured = [], []
112 for _ in range(12):
113 action = np.clip(.65 * (target - state) + .4 * feedback * (state.mean() - state), -.5, .5)
114 predicted.append(np.clip(state + gain * action + .2 * (drift - .5), 0., 1.))
115 state = np.clip(state + .55 * action + rng.normal(0., .02, size=4), 0., 1.)
116 measured.append(state.copy())
117 return predicted, measured
118
119 def describe(sensors):
120 return (float(np.mean(sensors[-1])),)
121
122 for name, mutate in (("actor-predictor", lambda row, rng: np.clip(row + rng.normal(0., .12, 4), 0., 1.)),
123 ("random-pairs", lambda row, rng: rng.random(4))):
124 grid = _grid((12,))
125 result = minimize_surprise_map_elites(grid, rollout, describe=describe, sample=lambda rng: rng.random(4),
126 mutate=mutate, budget=144, repeats=3, seed=seed)
127 errors = [np.abs(np.asarray(predicted) - measured).mean() for row in grid for case in (8191, 4099, 6151)
128 for predicted, measured in [rollout(tuple(row), case)]]
129 yield dict(method=name, rollouts=result.rollout_calls, steps=result.sensor_steps, cells=len(grid),
130 audit_rollouts=len(errors), heldout_error=float(np.mean(errors)))
131
132
133def _policy_fixture(seed):
134 import gymnasium as gym
135 import torch
136 from qdpy.rl import PolicyConfig, TD3Config
137
138 torch.set_num_threads(1)
139
140 class Track(gym.Env):
141 observation_space = gym.spaces.Box(-3., 3., (2,), dtype=np.float32)
142 action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32)
143
144 def reset(self, *, seed=None, options=None):
145 super().reset(seed=seed)
146 self.x = float(self.np_random.uniform(-.12, .12))
147 self.v, self.t = 0., 0
148 return np.array([self.x, self.v], np.float32), {}
149
150 def step(self, action):
151 self.t += 1
152 self.v = .6 * self.v + .16 * float(action[0])
153 self.x += self.v
154 quality = 1. - abs(self.x - .34)
155 return np.array([self.x, self.v], np.float32), quality, self.t == 6, False, {}
156
157 config = dict(seed=seed, initial_policies=8, batch_size=5, max_episode_steps=6, critic_steps=2, pg_steps=1,
158 policy=PolicyConfig((8,)), td3=TD3Config(learning_starts=24, batch_size=16,
159 replay_capacity=512, critic_hidden_sizes=(12,)))
160 return Track, config
161
162
163def _audit_policy(search, environment):
164 result = _grid((14,), ((-1.6, 1.6),))
165 for elite in search.archive:
166 actor = search.policy_for(elite)
167 returns, locations = [], []
168 with environment() as env:
169 for seed in (417, 641, 991):
170 observation, _ = env.reset(seed=seed)
171 quality = 0.
172 for _ in range(6):
173 observation, reward, _, _, _ = env.step(actor.act(observation))
174 quality += reward
175 returns.append(quality)
176 locations.append(float(observation[0]))
177 _update(result, elite, float(np.mean(returns)), (float(np.mean(locations)),))
178 return dict(audit_steps=18 * len(search.archive), audit_cells=len(result),
179 best_return=result.best.fitness.values[0],
180 audit_score=float(sum(row.fitness.values[0] for row in result)))
181
182
183def pga(seed):
184 from qdpy.rl import PGAAURORA, PGAMAPElites
185
186 env, config = _policy_fixture(seed)
187 common = dict(capacity=24, training_period=8, encoder_epochs=3, size_gain=.04)
188 candidates = (("pga-aurora", PGAAURORA(env, **common, **config)),
189 ("genetic-aurora", PGAAURORA(env, gradient=False, **common, **config)),
190 ("pga-known", PGAMAPElites(env, _grid((14,), ((-1.6, 1.6),)),
191 descriptor=lambda episode: (float(episode.observations[-1, 0]),), **config)))
192 for name, search in candidates:
193 stats = search.train(360)
194 yield dict(method=name, steps=stats.env_steps, gradient=stats.pg_offspring,
195 refits=getattr(stats, "encoder_refits", 0), **_audit_policy(search, env))
196
197
198def adaptive(seed):
199 from qdpy.rl import AdaHOME
200
201 env, config = _policy_fixture(seed)
202 modes = (("ada-home", True, .1, .25), ("fixed-with-replay", False, .1, .25), ("base-pga", False, 0., 0.))
203 for name, use_bandit, crossover, replay in modes:
204 search = AdaHOME(env, _grid((14,), ((-1.6, 1.6),)),
205 descriptor=lambda episode: (float(episode.observations[-1, 0]),),
206 adaptive=use_bandit, swap_probability=crossover, elite_capacity=128, elite_fraction=replay,
207 **config)
208 stats = search.train(360)
209 yield dict(method=name, steps=stats.env_steps, operator_trials=stats.operator_trials,
210 elite_replay=stats.elite_replay_size, **_audit_policy(search, env))
211
212
213def landscapes(seed):
214 for use_novelty in (True, False):
215 result = generate_local_optima_benchmarks(peaks=14, budget=100, population_size=10, offspring=10,
216 samples=48, novelty=use_novelty, seed=seed)
217 signatures = {(int(net.descriptors[0]), int(net.descriptors[2]), min(4, int(5 * net.descriptors[-1])))
218 for net in result.networks}
219 yield dict(method="network-novelty" if use_novelty else "random", evaluations=result.evaluations,
220 basin_probes=result.basin_probes, signatures=len(signatures),
221 max_optima=max(net.descriptors[0] for net in result.networks))
222
223
224def main():
225 cases = dict(layers=layers, decoders=decoders, predict=predict, pga=pga, adaptive=adaptive, landscapes=landscapes)
226 parser = argparse.ArgumentParser(description=__doc__)
227 parser.add_argument("case", choices=cases)
228 parser.add_argument("--seeds", nargs="+", type=int, default=[11])
229 arguments = parser.parse_args()
230 for seed in arguments.seeds:
231 for result in cases[arguments.case](seed):
232 print(json.dumps(dict(case=arguments.case, seed=seed, **result), sort_keys=True), flush=True)
233
234
235if __name__ == "__main__":
236 main()