# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Small solver, graph policy, competitive strategy, and parent-selection comparisons. """Run four seeded benchmarks using the base installation.""" import argparse import itertools import json import random import numpy as np from scipy.optimize import Bounds, LinearConstraint from qdpy.algorithms import (CartesianGraphSpace, CuriosityMutPolyBounded, DecisionTreePolicy, GraphMAPElites, MILPArchiveSearch, MatchResult, RandomSearchMutPolyBounded, QDSelfPlay, YouthMAPElites, game_search) from qdpy.containers import Grid from qdpy.phenotype import Features, Fitness, Individual from qdpy.tools import mut_polynomial_bounded def assignment_trial(seed, budget): """Match all niche optima against exhaustive enumeration of six two-machine assignments.""" rng = np.random.default_rng(seed) cost = rng.integers(1, 20, size=12) loads = np.asarray([1, 1, 2, 2, 3, 4]) descriptor = np.zeros((2, 12), dtype=int) descriptor[0, ::2], descriptor[1, ::2] = 1, loads rows = np.vstack((np.kron(np.eye(6), np.ones((1, 2))), descriptor[1])) constraints = LinearConstraint(rows, [1] * 6 + [4], [1] * 6 + [10]) grid = Grid(shape=(7, 14), features_domain=((0, 6), (0, 13)), fitness_domain=((0, 120),), fitness_weights=(-1.,)) def measure(first_machine): bits = np.column_stack((first_machine, 1 - np.asarray(first_machine))).ravel() features = tuple(descriptor @ bits) if 4 <= features[1] <= 10: return grid.index_grid(features), int(cost @ bits) return None, None oracle = {} for assignment in itertools.product((0, 1), repeat=6): cell, fitness = measure(assignment) if cell is not None: oracle[cell] = min(fitness, oracle.get(cell, np.inf)) search = MILPArchiveSearch(grid, cost, Bounds(0, 1), descriptor, constraints=constraints) results = search.run() solved = {row.cell: row.fitness for row in results if row.status == "optimal"} assert solved == oracle and all(row.status != "unresolved" for row in results) yield dict(method="MILP", seed=seed, cells=len(solved), solver_calls=sum(row.solver_status is not None for row in results), infeasible_cells=len(results) - len(solved), exhaustive_assignments=2**6, best_cost=min(solved.values()), mean_cell_gap=0.) # Preserve assignment equalities by flipping one job's machine. elites = {} for _ in range(budget): if elites and rng.random() < .9: parent = tuple(elites.values())[rng.integers(len(elites))][1] assignment = list(parent) assignment[rng.integers(6)] ^= 1 else: assignment = rng.integers(2, size=6).tolist() cell, fitness = measure(assignment) if cell is not None and (cell not in elites or fitness < elites[cell][0]): elites[cell] = fitness, tuple(assignment) yield dict(method="assignment MAP-Elites", seed=seed, cells=len(elites), candidate_calls=budget, best_cost=min((value for value, _ in elites.values()), default=None), mean_cell_gap=float(np.mean([value - oracle[cell] for cell, (value, _) in elites.items()])) if elites else None) STEPS = ((1, 0), (-1, 0), (0, 1), (0, -1)) START, GOAL = (1, 3), (5, 3) def _advance(position, action): if action is None: return position dx, dy = STEPS[action] x, y = position[0] + dx, position[1] + dy if 0 <= x < 7 and 0 <= y < 7 and (x != 3 or y in (0, 6)): return x, y return position def navigate(choose, *, mask_direction=False, horizon=22): """Reach a goal across a wall with two possible detours using a reactive policy.""" position = START for step in range(horizon): x, y = position observation = (x / 3. - 1., y / 3. - 1., 0. if mask_direction else (GOAL[0] - x) / 6., (GOAL[1] - y) / 6., *[float(_advance(position, action) == position) for action in range(4)]) position = _advance(position, choose(observation)) if position == GOAL: return 1. + (horizon - step) / (horizon + 1), position return 1. / (1 + sum(abs(a - b) for a, b in zip(position, GOAL))), position def _graph_action(graph, observation): dx, dy = graph.act(observation) if dx == dy == 0.: return None if abs(dx) > abs(dy): return 0 if dx > 0. else 1 return 2 if dy > 0. else 3 def _tree_policy(genome): thresholds = (-.5, 0., .5) first, left, right = (tuple(genome[i:i + 2]) for i in (0, 2, 4)) leaves = genome[6:] return DecisionTreePolicy( (first[0], thresholds[first[1]], (left[0], thresholds[left[1]], *leaves[:2]), (right[0], thresholds[right[1]], *leaves[2:])), (8,), 4, ) def graph_trial(seed, budget): """Compare structural and endpoint archives with fitness-only CGP and shallow decision trees.""" space = CartesianGraphSpace(8, 2, 12, operation_rate=.09, connection_rate=.12) for mode in ("graph fitness only", "graph behavior", "graph joint", "decision trees"): if mode == "graph fitness only": shape, domains = (1,), ((0., 1.),) else: shape, domains = (7, 7), ((0., 6.),) * 2 if mode == "graph joint": shape, domains = (*shape, 4, 4), (*domains, (0., 1.), (0., 1.)) archive = Grid(shape=shape, features_domain=domains, fitness_domain=((0., 2.),), fitness_weights=(1.,)) endpoints = set() def decode(genome): if mode == "decision trees": return _tree_policy(genome).act, () graph = space.decode(genome) return lambda observation: _graph_action(graph, observation), graph.structure_descriptors def evaluate(genome): policy, structure = decode(genome) score, endpoint = navigate(policy) endpoints.add(endpoint) if mode == "graph fitness only": descriptor = (0.,) elif mode == "graph joint": descriptor = (*endpoint, *structure) else: descriptor = endpoint return (score,), descriptor if mode == "decision trees": rng = np.random.default_rng(seed) limits = np.array([8, 3] * 3 + [4] * 4) for _ in range(budget): if archive: candidate = list(archive[rng.integers(len(archive))]) gene = rng.integers(len(limits)) flip = rng.integers(limits[gene] - 1) candidate[gene] = int(flip + (flip >= candidate[gene])) else: candidate = list(map(int, rng.integers(limits))) fitness, descriptor = evaluate(candidate) archive.add(Individual(candidate, fitness=Fitness(fitness, weights=(1.,)), features=Features(descriptor))) else: GraphMAPElites(archive, budget, space, seed=seed, batch_size=1).optimise(evaluate) audited = [navigate(decode(item)[0], mask_direction=True)[0] for item in archive] structures = {decode(item)[1] for item in archive} yield dict(method=mode, seed=seed, evaluations=budget, explored_endpoints=len(endpoints), cells=archive.filled_bins, distinct_graph_structures=len(structures) if mode != "decision trees" else None, best_fitness=archive.best.fitness.values[0], held_out_evaluations=len(audited), best_masked_fitness=max(audited)) def cyclic_action(strategy): """Decode the cycle action from a bounded scalar strategy.""" return min(2, int(3 * strategy[0])) def cyclic_match(red, blue): """Score rock-paper-scissors with a small penalty away from each action center.""" red_action, blue_action = cyclic_action(red), cyclic_action(blue) red_penalty = abs(red[0] - (red_action + .5) / 3.) blue_penalty = abs(blue[0] - (blue_action + .5) / 3.) reward = (0., 1., -1.)[(red_action - blue_action) % 3] + .2 * (blue_penalty - red_penalty) return reward, -reward def propose_cyclic(context, rng): """Perturb an archived strategy, with larger moves after a loss.""" size = .19 if context.payoffs[context.role] < 0. else .12 value = context.parents[context.role][0] return (float(np.clip(value + rng.normal(0., size), 0., 1.)),) def self_play_trial(seed, budget): """Compare grid-free competition and GAME using the same maximum match budget.""" search = QDSelfPlay(((.17,), (.17,)), play=cyclic_match, propose=propose_cyclic, embed=lambda role, policy: policy, novelty_radius=.16, opponents=3, seed=seed) stats = search.run(budget) def play(red, blue): return MatchResult(cyclic_match(red, blue), (red, blue)) result = game_search(play, dimensions=(1, 1), rounds=8, matches_per_round=budget // 8, task_count=3, cells_per_task=5, seed=seed, match_budget=budget) game = [] for side in ("red", "blue"): latest = next((row.representatives for row in reversed(result.rounds) if row.side == side), ()) game.append(tuple(item.genome for item in latest)) panel = tuple(((action + .5) / 3.,) for action in range(3)) for label, archives, calls in (("QD Self-Play", search.archives, stats.matches), ("GAME", tuple(game), result.total_attempts)): coverage = [len({cyclic_action(policy) for policy in archive}) for archive in archives] values = [] for side, archive in enumerate(archives): for opponent in panel: payoffs = [(cyclic_match(policy, opponent) if side == 0 else cyclic_match(opponent, policy))[side] for policy in archive] if payoffs: values.append(max(payoffs)) yield dict(method=label, seed=seed, matches=calls, role_action_coverage=coverage, mean_best_panel_payoff=float(np.mean(values)) if values else None, audit_matches=sum(map(len, archives)) * len(panel)) def youth_trial(seed, budget): """Compare recent, uniform, and curiosity parent selection under the same maze and mutation.""" length = 16 def evaluate(genome): actions = iter(min(3, int(value * 4)) for value in genome) quality, endpoint = navigate(lambda observation: next(actions), horizon=length) return (quality,), endpoint def mutate(parent, rng): return mut_polynomial_bounded(list(parent), eta=5., low=0., up=1., mut_pb=2 / length) for kind in ("youth", "uniform", "curiosity"): archive = Grid(shape=(7, 7), features_domain=((0, 6),) * 2, fitness_domain=((0., 2.),), fitness_weights=(1.,)) start = [float(value) for value in np.random.default_rng(seed).random(length)] fitness, endpoint = evaluate(start) archive.add(Individual(start, fitness=Fitness(fitness, weights=(1.,)), features=Features(endpoint))) random.seed(seed) if kind == "youth": search = YouthMAPElites(archive, budget, length, parent_window=4, mutate=mutate, seed=seed, batch_size=1) else: settings = dict(init_pb=0., eta=5., mut_pb=2 / length, optimisation_task="maximisation", batch_size=1) search = (RandomSearchMutPolyBounded(archive, budget, length, sel_pb=1., **settings) if kind == "uniform" else CuriosityMutPolyBounded(archive, budget, length, **settings)) search.optimise(evaluate) yield dict(method=kind, seed=seed, evaluations=search.nb_evaluations + 1, cells=archive.filled_bins, best_fitness=archive.best.fitness.values[0], reached_goal=bool(archive.solutions[GOAL])) if __name__ == "__main__": trials = {"assignment": (assignment_trial, 64), "graphs": (graph_trial, 768), "self-play": (self_play_trial, 144), "youth": (youth_trial, 256)} parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=trials) parser.add_argument("--budget", type=int) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33]) args = parser.parse_args() trial, default_budget = trials[args.task] budget = default_budget if args.budget is None else args.budget if budget < (16 if args.task == "self-play" else 1): parser.error("Use a positive budget, or at least 16 matches for self-play.") for seed in args.seeds: for row in trial(seed, budget): print(json.dumps(row, sort_keys=True))