5"""Seeded CPU examples for Trace-Elites, MEMES, and the Asymmetric Island Model."""
9from pathlib
import Path
11from time
import perf_counter
22 return Grid(shape=shape, features_domain=((0., 1.),) * len(shape),
23 fitness_domain=((0., 2.),), fitness_weights=(1.,))
28 """Return scalar quality and the sampled path of a quadratic Bézier curve."""
29 x_end, y_end, turn = genome
30 start = np.array([.12, .13])
31 bend = np.array([.14 + .76 * turn, .87 - .7 * turn])
32 end = np.array([x_end, y_end])
33 time = np.linspace(0., 1., 17)[:,
None]
34 trace = (1. - time)**2 * start + 2 * (1. - time) * time * bend + time**2 * end
35 length = np.linalg.norm(np.diff(trace, axis=0), axis=1).sum()
36 score = 1.85 - .64 * np.linalg.norm(end - [.82, .76])**2 - .25 * length
37 return float(score), tuple(map(tuple, trace))
40def _endpoint_search(evaluate, grid, budget, seed):
41 rng = np.random.default_rng(seed)
42 for step
in range(budget):
43 if step < 16
or not len(grid):
44 genome = rng.random(3)
46 first, second = rng.integers(len(grid), size=2)
47 genome = iso_line_dd(grid[first], grid[second], bounds=(0., 1.), iso_sigma=.05,
48 line_sigma=.2, rng=rng)
49 value, trace = evaluate(genome)
50 grid.add(Individual(list(genome), fitness=Fitness((value,), weights=(1.,)),
51 features=Features(trace[-1]), scores={
"trace": trace}))
55def trace_trial(seed, budget, plot=None):
56 """Make one rollout per proposal and draw retained routes if requested."""
57 for method
in (
"trace-elites",
"endpoint"):
58 start = perf_counter()
66 geometry = _grid((10, 10))
67 if method ==
"trace-elites":
68 archive = TraceArchive(geometry)
69 TraceElites(archive, 3, seed=seed).run(evaluate, budget)
71 distinct = len({elite.genome
for elite
in archive})
74 _endpoint_search(evaluate, archive, budget, seed)
75 reporting = TraceArchive(_grid((10, 10)))
77 reporting.add(elite, elite.fitness.values, elite.scores[
"trace"])
78 distinct = len({tuple(elite)
for elite
in archive})
79 yield dict(study=
"trace", method=method, seed=seed, evaluations=calls, search_cells=archive.filled_bins,
80 distinct_genomes=distinct, trace_cells=reporting.filled_bins,
81 trace_qd_score=reporting.qd_score(
False), elapsed_s=perf_counter() - start)
82 if plot
is not None and method ==
"trace-elites":
83 import matplotlib.pyplot
as plt
86 ax = plot_trace_archive(reporting)
87 ax.set(title=
"Trace-Elites retained routes", xlabel=
"Horizontal position", ylabel=
"Vertical position")
88 ax.set_aspect(
"equal")
89 plot.parent.mkdir(parents=
True, exist_ok=
True)
90 ax.figure.savefig(plot, dpi=150, bbox_inches=
"tight")
94_ES_TARGET = np.linspace(.22, .78, 48)
97def _es_arrays(points):
98 displacement = points - _ES_TARGET
99 loss = displacement**2 + .5 * (1. - np.cos(6 * np.pi * displacement))
100 return 2. - loss.mean(axis=-1), points[..., :12].mean(axis=-1), points[..., 12:24].mean(axis=-1)
103def _es_objective(genome):
104 quality, x, y = _es_arrays(np.asarray(genome))
105 return float(quality), (float(x), float(y))
108def _es_batch(genomes):
109 quality, x, y = _es_arrays(genomes)
110 return list(zip(quality, zip(x, y)))
114def memes_trial(seed, budget):
115 """Use eight emitters and three mirrored pairs per ES step."""
116 initial = np.random.default_rng(seed).uniform(.25, .75, size=(8, 48))
117 for method
in (
"me-es",
"memes",
"memes-batch"):
118 start = perf_counter()
119 archive = _grid((12, 12))
120 common = dict(pairs=3, sigma=.08, learning_rate=.035, ind_domain=(0., 1.), seed=seed)
121 if method ==
"me-es":
122 search = MEES(archive, initial[0], block_steps=8, **common)
123 search.run(_es_objective, budget)
124 evaluations, centers, updates = search.evaluations, search.center_evaluations, search.updates
127 search = MEMES(archive, initial, stale_budget=4, novelty_capacity=128, **common)
128 if method ==
"memes-batch":
129 search.run(
None, budget, evaluate_batch=_es_batch)
131 search.run(_es_objective, budget)
133 evaluations, centers, updates = stats.evaluations, stats.center_evaluations, stats.rounds * len(initial)
134 resets = stats.emitter_resets
135 yield dict(study=
"memes", method=method, seed=seed, budget=budget, evaluations=evaluations,
136 es_steps=updates, center_evaluations=centers, resets=resets, cells=archive.filled_bins,
137 qd_score=archive.qd_score(
False), best=
None if archive.best
is None else archive.best.fitness.values[0],
138 elapsed_s=perf_counter() - start)
141ROLE_SIZES = {
"scout": 2,
"carrier": 3}
142TRAINING_TASKS = (
"wide",
"offset")
143_TARGETS = {
"wide": (.27, .7, .40),
"offset": (.67, .43, .67),
"held-out": (.47, .55, .51)}
147def role_evaluation(role, genome):
148 """Map an agent's parameters to local quality and a scalar descriptor."""
150 waypoint, timing = genome
151 return 1.8 - .8 * (timing - .65)**2, (waypoint,)
152 destination, pickup, speed = genome
153 return 1.8 - .6 * (pickup - .5)**2 - .6 * (speed - .55)**2, (destination,)
157def team_evaluation(task, genomes):
158 """Return total quality and the two roles' contributions in role order."""
159 waypoint, timing = genomes[0]
160 destination, pickup, speed = genomes[1]
161 route_target, drop_target, speed_target = _TARGETS[task]
162 coordination = .45 * (waypoint - pickup)**2 + .28 * (timing - speed)**2
163 scout = 1. - .9 * (waypoint - route_target)**2 - coordination
164 carrier = 1. - .7 * (destination - drop_target)**2 - .5 * (speed - speed_target)**2 - coordination
165 return scout + carrier, (scout, carrier)
169def aim_trial(seed, budget):
170 """Evaluate the best team per training task on a third, held-out task."""
171 start = perf_counter()
172 islands = {role: _grid((9,))
for role
in ROLE_SIZES}
173 search = AIM(islands, TRAINING_TASKS, role_sizes=ROLE_SIZES, population_size=8, elite_size=2,
174 island_offspring=3, migration_period=2, allocation_rate=.8, seed=seed)
175 stats = search.run(role_evaluation, team_evaluation, island_budget=budget * 2, team_budget=budget)
176 champions = [search.team_populations[task][0].genomes
for task
in TRAINING_TASKS]
177 held_out = [team_evaluation(
"held-out", team)[0]
for team
in champions]
178 yield dict(study=
"aim", method=
"aim", seed=seed, island_evaluations=stats.island_evaluations,
179 team_evaluations=stats.team_evaluations, migration_rounds=stats.migration_rounds,
180 return_evaluations=stats.returning_evaluations, exported_roles=stats.exported_roles,
181 allocation=search.allocation_probabilities, audit_calls=len(held_out),
182 held_out_mean=float(np.mean(held_out)), held_out_best=max(held_out),
183 elapsed_s=perf_counter() - start)
184 total = stats.team_evaluations + stats.island_evaluations
185 for matched_total
in (
False,
True):
186 start = perf_counter()
187 champions, calls = [], 0
188 count = (total
if matched_total
else stats.team_evaluations) // len(TRAINING_TASKS)
189 for i, task
in enumerate(TRAINING_TASKS):
190 random.seed(seed + i)
191 np.random.seed(seed + i)
193 baseline = MixME(grid, count, ROLE_SIZES, batch_size=6)
195 def evaluate(genome):
198 team = baseline.decode_team(genome)
199 score, _ = team_evaluation(task, tuple(team.values()))
200 return (score,), (team[
"scout"][0], team[
"carrier"][0])
202 baseline.optimise(evaluate)
203 champions.append(tuple(baseline.decode_team(grid.best).values()))
204 held_out = [team_evaluation(
"held-out", team)[0]
for team
in champions]
205 yield dict(study=
"aim", method=
"mix-me-total" if matched_total
else "mix-me-team", seed=seed,
206 island_evaluations=0, team_evaluations=calls, audit_calls=len(held_out),
207 held_out_mean=float(np.mean(held_out)), held_out_best=max(held_out),
208 elapsed_s=perf_counter() - start)
212 parser = argparse.ArgumentParser(description=__doc__)
213 parser.add_argument(
"method", choices=(
"trace",
"memes",
"aim"))
214 parser.add_argument(
"--budget", type=int, help=
"Evaluation limit (team calls for AIM)")
215 parser.add_argument(
"--seeds", nargs=
"+", type=int, default=[7, 13, 23])
216 parser.add_argument(
"--plot", type=Path, help=
"Save a trajectory overlay for a single Trace-Elites seed")
217 args = parser.parse_args()
218 if args.budget
is not None and args.budget < (16
if args.method ==
"aim" else 1):
219 parser.error(
"--budget must be at least 16 for AIM and positive for the other methods")
220 if args.plot
is not None and (args.method !=
"trace" or len(args.seeds) != 1):
221 parser.error(
"--plot requires trace and one seed")
222 for seed
in args.seeds:
223 if args.method ==
"trace":
224 rows = trace_trial(seed, args.budget
or 360, args.plot)
225 elif args.method ==
"memes":
226 rows = memes_trial(seed, args.budget
or 1016)
228 rows = aim_trial(seed, args.budget
or 88)
230 print(json.dumps(row, allow_nan=
False))
233if __name__ ==
"__main__":