# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare targeted ES, multi-criteria archive admission, and GAME selectors. """Run targeted and adversarial QD comparisons with a fixed evaluation cap.""" import argparse import json import random import numpy as np from qdpy.algorithms import JEDi, LMMAMAE, IsoLineMAPElites, MatchResult, game_cross_play, game_search from qdpy.containers import Grid, TDominOGrid def run_jedi(method, budget, seed): """Compare targeted ES and annealed archive improvement on a twin-peak objective.""" dimension = 12 grid = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 2.),)) common = dict(container=grid, budget=budget, batch_size=8, ind_domain=(0., 1.), sigma0=.12, seed=seed, optimisation_task="max") if method == "jedi": search = JEDi(dimension=dimension, warmup=24, targets_per_cycle=2, generations_per_target=3, **common) else: search = LMMAMAE(x0=np.full(dimension, .5), threshold_min=0., **common) def evaluate(individual): genome = np.asarray(individual) position = genome[:2] peaks = [.55 * np.exp(-np.square(position - [.28, .28]).sum() / .04), .80 * np.exp(-np.square(position - [.76, .78]).sum() / .025)] fitness = .75 + max(peaks) - np.square(genome[2:] - .7).mean() return (float(fitness),), position search.optimise(evaluate) fitness = [elite.fitness.values[0] for elite in grid] return dict(suite="target", method=method, seed=seed, evaluations=search.nb_evaluations, occupied_cells=len(grid), best=max(fitness), qd_score=sum(fitness), targets=sum(map(len, getattr(search, "target_history", ())))) def run_t_domino(method, budget, seed): """Compare T-DominO with an unnormalized sum on three conflicting criteria.""" random.seed(seed) np.random.seed(seed) geometry = dict(shape=(10,), features_domain=((0., 1.),)) if method == "t-domino": archive = TDominOGrid(fitness_domain=((0., 1.), (0., 10.), (0., 100.)), neighbor_radius=2, **geometry) else: archive = Grid(fitness_domain=((0., 111.),), **geometry) search = IsoLineMAPElites(archive, budget, dimension=3, optimisation_task="max", batch_size=8, iso_sigma=.08, line_sigma=.2) def normalized(individual): _, knob, quality = individual return np.maximum(0., 1 - 1.4 * np.abs(knob - np.array([.15, .5, .85]))) * (.5 + .5 * quality) def evaluate(individual): raw = normalized(individual) * (1., 10., 100.) objectives = tuple(raw) if method == "t-domino" else (float(raw.sum()),) return objectives, (individual[0],) search.optimise(evaluate) outcomes = np.asarray([normalized(elite) for elite in archive]) return dict(suite="balance", method=method, seed=seed, evaluations=search.nb_evaluations, occupied_cells=len(archive), average_worst=float(outcomes.min(axis=1).mean()), average_mean=float(outcomes.mean())) def cycle_game(red, blue): """Play a continuous variant of a three-way nontransitive game.""" first, second = (min(int(genome[0] * 3), 2) for genome in (red, blue)) bonus = (.0, .36, -.36)[(first - second) % 3] payoff = .5 + bonus + .12 * (red[1] - blue[1]) return MatchResult((payoff, 1. - payoff), ((red[0], red[1]), (blue[0], blue[1]))) def run_game(budget, seed): """Compare GAME selectors on a shared cross-play panel.""" pool = {"red": [], "blue": []} groups = {} for method in ("behavior", "ranking", "pareto"): # The original selector only plays bootstrap tournaments. The other # selectors can consume one full unique-elite tournament per round. reserve = 27 if method == "behavior" else 108 search = game_search(cycle_game, dimensions=(2, 2), rounds=4, matches_per_round=(budget - reserve) // 4, task_count=3, cells_per_task=3, seed=seed, task_selection=method, match_budget=budget) indices = {} for side in pool: recent = next(round_ for round_ in reversed(search.rounds) if round_.side == side) start = len(pool[side]) pool[side].extend(elite.genome for elite in recent.representatives) indices[side] = range(start, len(pool[side])) groups[method] = search, indices panel = game_cross_play(cycle_game, pool["red"], pool["blue"]) outcomes = [] for method, (search, index) in groups.items(): metrics = {side: panel.metrics(side, index[side], clusters=3, seed=seed) for side in pool} outcomes.append(dict(suite="game", method=method, seed=seed, cap=budget, search_matches=search.search_attempts, selection_matches=search.tournament_attempts, tournament_matches_shared=panel.attempts, win_rate=float(np.mean([values.win_rate for values in metrics.values()])), expertise=float(np.mean([values.expertise for values in metrics.values()])), coverage=float(np.mean([values.coverage for values in metrics.values()])))) return outcomes if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("suite", choices=("jedi", "balance", "game", "all")) parser.add_argument("--budget", type=int, default=480) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33]) args = parser.parse_args() if args.suite in ("game", "all") and args.budget < 128: parser.error("the GAME comparison needs a budget of at least 128") for seed in args.seeds: results = [] if args.suite in ("jedi", "all"): results.extend(run_jedi(method, args.budget, seed) for method in ("jedi", "lm-ma-mae")) if args.suite in ("balance", "all"): results.extend(run_t_domino(method, args.budget, seed) for method in ("t-domino", "weighted-sum")) if args.suite in ("game", "all"): results.extend(run_game(args.budget, seed)) for row in results: print(json.dumps(row, sort_keys=True, allow_nan=False))