# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare multi-cell traces, parallel evolution strategies and asymmetric teams. """Seeded CPU examples for Trace-Elites, MEMES, and the Asymmetric Island Model.""" import argparse import json from pathlib import Path import random from time import perf_counter import numpy as np from qdpy.algorithms import AIM, MEES, MEMES, MixME, TraceElites from qdpy.containers import Grid, TraceArchive from qdpy.phenotype import Features, Fitness, Individual from qdpy.tools import iso_line_dd def _grid(shape): return Grid(shape=shape, features_domain=((0., 1.),) * len(shape), fitness_domain=((0., 2.),), fitness_weights=(1.,)) ## @brief Evaluate a curved route in a square with a landing quality objective. def route(genome): """Return scalar quality and the sampled path of a quadratic Bézier curve.""" x_end, y_end, turn = genome start = np.array([.12, .13]) bend = np.array([.14 + .76 * turn, .87 - .7 * turn]) end = np.array([x_end, y_end]) time = np.linspace(0., 1., 17)[:, None] trace = (1. - time)**2 * start + 2 * (1. - time) * time * bend + time**2 * end length = np.linalg.norm(np.diff(trace, axis=0), axis=1).sum() score = 1.85 - .64 * np.linalg.norm(end - [.82, .76])**2 - .25 * length return float(score), tuple(map(tuple, trace)) def _endpoint_search(evaluate, grid, budget, seed): rng = np.random.default_rng(seed) for step in range(budget): if step < 16 or not len(grid): genome = rng.random(3) else: first, second = rng.integers(len(grid), size=2) genome = iso_line_dd(grid[first], grid[second], bounds=(0., 1.), iso_sigma=.05, line_sigma=.2, rng=rng) value, trace = evaluate(genome) grid.add(Individual(list(genome), fitness=Fitness((value,), weights=(1.,)), features=Features(trace[-1]), scores={"trace": trace})) ## @brief Compare retained trajectory coverage on the same reporting geometry. def trace_trial(seed, budget, plot=None): """Make one rollout per proposal and draw retained routes if requested.""" for method in ("trace-elites", "endpoint"): start = perf_counter() calls = 0 def evaluate(genome): nonlocal calls calls += 1 return route(genome) geometry = _grid((10, 10)) if method == "trace-elites": archive = TraceArchive(geometry) TraceElites(archive, 3, seed=seed).run(evaluate, budget) reporting = archive distinct = len({elite.genome for elite in archive}) else: archive = geometry _endpoint_search(evaluate, archive, budget, seed) reporting = TraceArchive(_grid((10, 10))) for elite in archive: reporting.add(elite, elite.fitness.values, elite.scores["trace"]) distinct = len({tuple(elite) for elite in archive}) yield dict(study="trace", method=method, seed=seed, evaluations=calls, search_cells=archive.filled_bins, distinct_genomes=distinct, trace_cells=reporting.filled_bins, trace_qd_score=reporting.qd_score(False), elapsed_s=perf_counter() - start) if plot is not None and method == "trace-elites": import matplotlib.pyplot as plt from qdpy.plots import plot_trace_archive ax = plot_trace_archive(reporting) ax.set(title="Trace-Elites retained routes", xlabel="Horizontal position", ylabel="Vertical position") ax.set_aspect("equal") plot.parent.mkdir(parents=True, exist_ok=True) ax.figure.savefig(plot, dpi=150, bbox_inches="tight") plt.close(ax.figure) _ES_TARGET = np.linspace(.22, .78, 48) def _es_arrays(points): displacement = points - _ES_TARGET loss = displacement**2 + .5 * (1. - np.cos(6 * np.pi * displacement)) return 2. - loss.mean(axis=-1), points[..., :12].mean(axis=-1), points[..., 12:24].mean(axis=-1) def _es_objective(genome): quality, x, y = _es_arrays(np.asarray(genome)) return float(quality), (float(x), float(y)) def _es_batch(genomes): quality, x, y = _es_arrays(genomes) return list(zip(quality, zip(x, y))) ## @brief Compare a single ES, scalar MEMES, and NumPy-batched MEMES. def memes_trial(seed, budget): """Use eight emitters and three mirrored pairs per ES step.""" initial = np.random.default_rng(seed).uniform(.25, .75, size=(8, 48)) for method in ("me-es", "memes", "memes-batch"): start = perf_counter() archive = _grid((12, 12)) common = dict(pairs=3, sigma=.08, learning_rate=.035, ind_domain=(0., 1.), seed=seed) if method == "me-es": search = MEES(archive, initial[0], block_steps=8, **common) search.run(_es_objective, budget) evaluations, centers, updates = search.evaluations, search.center_evaluations, search.updates resets = None else: search = MEMES(archive, initial, stale_budget=4, novelty_capacity=128, **common) if method == "memes-batch": search.run(None, budget, evaluate_batch=_es_batch) else: search.run(_es_objective, budget) stats = search.stats evaluations, centers, updates = stats.evaluations, stats.center_evaluations, stats.rounds * len(initial) resets = stats.emitter_resets yield dict(study="memes", method=method, seed=seed, budget=budget, evaluations=evaluations, es_steps=updates, center_evaluations=centers, resets=resets, cells=archive.filled_bins, qd_score=archive.qd_score(False), best=None if archive.best is None else archive.best.fitness.values[0], elapsed_s=perf_counter() - start) ROLE_SIZES = {"scout": 2, "carrier": 3} TRAINING_TASKS = ("wide", "offset") _TARGETS = {"wide": (.27, .7, .40), "offset": (.67, .43, .67), "held-out": (.47, .55, .51)} ## @brief Measure a controller on its own class-specific scouting or carrying task. def role_evaluation(role, genome): """Map an agent's parameters to local quality and a scalar descriptor.""" if role == "scout": waypoint, timing = genome return 1.8 - .8 * (timing - .65)**2, (waypoint,) destination, pickup, speed = genome return 1.8 - .6 * (pickup - .5)**2 - .6 * (speed - .55)**2, (destination,) ## @brief Measure a scout and carrier on a joint routing task. def team_evaluation(task, genomes): """Return total quality and the two roles' contributions in role order.""" waypoint, timing = genomes[0] destination, pickup, speed = genomes[1] route_target, drop_target, speed_target = _TARGETS[task] coordination = .45 * (waypoint - pickup)**2 + .28 * (timing - speed)**2 scout = 1. - .9 * (waypoint - route_target)**2 - coordination carrier = 1. - .7 * (destination - drop_target)**2 - .5 * (speed - speed_target)**2 - coordination return scout + carrier, (scout, carrier) ## @brief Compare asymmetric migration with Mix-ME at matched team and total call budgets. def aim_trial(seed, budget): """Evaluate the best team per training task on a third, held-out task.""" start = perf_counter() islands = {role: _grid((9,)) for role in ROLE_SIZES} search = AIM(islands, TRAINING_TASKS, role_sizes=ROLE_SIZES, population_size=8, elite_size=2, island_offspring=3, migration_period=2, allocation_rate=.8, seed=seed) stats = search.run(role_evaluation, team_evaluation, island_budget=budget * 2, team_budget=budget) champions = [search.team_populations[task][0].genomes for task in TRAINING_TASKS] held_out = [team_evaluation("held-out", team)[0] for team in champions] yield dict(study="aim", method="aim", seed=seed, island_evaluations=stats.island_evaluations, team_evaluations=stats.team_evaluations, migration_rounds=stats.migration_rounds, return_evaluations=stats.returning_evaluations, exported_roles=stats.exported_roles, allocation=search.allocation_probabilities, audit_calls=len(held_out), held_out_mean=float(np.mean(held_out)), held_out_best=max(held_out), elapsed_s=perf_counter() - start) total = stats.team_evaluations + stats.island_evaluations for matched_total in (False, True): start = perf_counter() champions, calls = [], 0 count = (total if matched_total else stats.team_evaluations) // len(TRAINING_TASKS) for i, task in enumerate(TRAINING_TASKS): random.seed(seed + i) np.random.seed(seed + i) grid = _grid((9, 9)) baseline = MixME(grid, count, ROLE_SIZES, batch_size=6) def evaluate(genome): nonlocal calls calls += 1 team = baseline.decode_team(genome) score, _ = team_evaluation(task, tuple(team.values())) return (score,), (team["scout"][0], team["carrier"][0]) baseline.optimise(evaluate) champions.append(tuple(baseline.decode_team(grid.best).values())) held_out = [team_evaluation("held-out", team)[0] for team in champions] yield dict(study="aim", method="mix-me-total" if matched_total else "mix-me-team", seed=seed, island_evaluations=0, team_evaluations=calls, audit_calls=len(held_out), held_out_mean=float(np.mean(held_out)), held_out_best=max(held_out), elapsed_s=perf_counter() - start) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("method", choices=("trace", "memes", "aim")) parser.add_argument("--budget", type=int, help="Evaluation limit (team calls for AIM)") parser.add_argument("--seeds", nargs="+", type=int, default=[7, 13, 23]) parser.add_argument("--plot", type=Path, help="Save a trajectory overlay for a single Trace-Elites seed") args = parser.parse_args() if args.budget is not None and args.budget < (16 if args.method == "aim" else 1): parser.error("--budget must be at least 16 for AIM and positive for the other methods") if args.plot is not None and (args.method != "trace" or len(args.seeds) != 1): parser.error("--plot requires trace and one seed") for seed in args.seeds: if args.method == "trace": rows = trace_trial(seed, args.budget or 360, args.plot) elif args.method == "memes": rows = memes_trial(seed, args.budget or 1016) else: rows = aim_trial(seed, args.budget or 88) for row in rows: print(json.dumps(row, allow_nan=False)) if __name__ == "__main__": main()