# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Seeded comparisons for constrained Pareto fronts, gradients, and diverse parent pools. """Run four small quality-diversity comparisons on the CPU.""" import argparse import json import random import numpy as np from qdpy.algorithms import (CMAMAEGA, FeasibleMOME, GradientEvaluation, IsoLineMAPElites, MEPGD, MultiDescriptorNSLC, OMGMEGA) from qdpy.containers import Grid, ParetoGrid from qdpy.phenotype import Features, Fitness, Individual def evaluate_panel(genome): """Trade off mass and stiffness while satisfying a narrow clearance interval.""" length, reinforcement, thickness = genome target = .18 + .55 * (.55 * length + .45 * reinforcement) offset = thickness - target mass = .2 + .45 * reinforcement + .4 * thickness + .1 * length stiffness = .22 + .65 * reinforcement + .33 * thickness - .13 * (length - .45)**2 return (mass, stiffness), (length,), {"too_thin": -.021 - offset, "too_thick": offset - .021} def feasible_trial(seed, budget): """Compare the same Pareto selection with and without infeasible parents.""" for label, probability in (("FeasibleMOME", .45), ("feasible parents only", 0.)): grid = ParetoGrid(shape=(12,), features_domain=((0., 1.),), fitness_domain=((0., 2.), (0., 2.)), fitness_weights=(-1., 1.), max_items_per_bin=5, truncation="crowding") search = FeasibleMOME( grid, budget, 3, 4, constraint_names=("too_thin", "too_thick"), iso_sigma=.065, line_sigma=.16, infeasible_parent_probability=probability, seed=seed, ) feasible = 0 while search.nb_evaluations < budget: size = min(search.batch_size, budget - search.nb_evaluations) results = [evaluate_panel(genome) for genome in search.ask_batch(size)] feasible += sum(all(value <= 0. for value in scores.values()) for _, _, scores in results) search.tell_batch(results) yield dict(method=label, seed=seed, evaluations=search.nb_evaluations, feasible_evaluations=feasible, cells=grid.filled_bins, elites=len(grid), auxiliary_cells=len(search.infeasible_elites), qd_hypervolume=grid.qd_hypervolume((2., 0.))) def differentiable_design(genome): """Return an exact objective, descriptors, and their Jacobian.""" x, y, z = genome quality = 1. - .30 * (x - .55)**2 - .20 * (y - .5)**2 - .5 * (z - .7)**2 return GradientEvaluation(quality, (x, y), [[-.6 * (x - .55), -.4 * (y - .5), .7 - z], [1., 0., 0.], [0., 1., 0.]]) def design_measurement(genome): """Measure the same design without computing derivatives.""" x, y, z = genome quality = 1. - .30 * (x - .55)**2 - .20 * (y - .5)**2 - .5 * (z - .7)**2 return (quality,), (x, y) def gradient_trial(seed, budget, include_cma=False): """Compare analytic and derivative-free searches in the same grid.""" kinds = (OMGMEGA, IsoLineMAPElites, CMAMAEGA) if include_cma else (OMGMEGA, IsoLineMAPElites) for kind in kinds: grid = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) random.seed(seed) np.random.seed(seed) measure = design_measurement if kind is OMGMEGA: search = kind(grid, budget, 3, batch_size=8, sigma=.16, seed=seed) measure = differentiable_design elif kind is CMAMAEGA: search = kind(grid, budget, (.5, .5, .5), .16, 8, 0., gradient_evaluate=differentiable_design, ind_domain=(0., 1.), seed=seed, optimisation_task="maximisation") else: search = kind(grid, budget, 3, batch_size=8, iso_sigma=.13, optimisation_task="maximisation") search.optimise(measure) yield dict(method=kind.__name__, seed=seed, evaluations=search.nb_evaluations, gradients=getattr(search, "gradient_evaluations", 0), cells=grid.filled_bins, qd_score=float(sum(item.fitness.values[0] for item in grid))) _MOVES = ((1, 0), (-1, 0), (0, 1), (0, -1)) def measure_route(genome): """Measure route style, ending coordinates, and success in a two-door maze.""" x, y = 1, 3 previous, turns, y_sum, door = None, 0, 0, None for length, gene in enumerate(genome, start=1): action = min(3, int(4 * gene)) dx, dy = _MOVES[action] col, row = x + dx, y + dy if 0 <= col < 7 and 0 <= row < 7 and (col != 3 or row in (0, 6)): x, y = col, row if x == 3 and door is None: door = y turns += previous is not None and previous != action previous = action y_sum += y if (x, y) == (5, 3): break distance = abs(5 - x) + abs(3 - y) return (1. / (1. + distance),), (y_sum / (6 * length), turns / max(1, length - 1)), (x / 6, y / 6), door def nslc_trial(seed, budget): """Compare reporting-view local competition with and without endpoint novelty.""" for label, use_exploration in (("NS–NSLC", True), ("reporting view only", False)): search = MultiDescriptorNSLC(budget, 18, 24, 12, reference_capacity=48, k=6, sigma=.16, seed=seed, optimisation_task="maximisation") styles = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),)) endpoints, goals = set(), set() def evaluate(genome): fitness, features, endpoint, door = measure_route(genome) endpoints.add(endpoint) if fitness[0] == 1.: goals.add(door) return fitness, features, {"exploration": endpoint if use_exploration else (0., 0.)} search.optimise(evaluate) yield dict(method=label, seed=seed, evaluations=search.nb_evaluations, terminal_cells=len(endpoints), retained_styles=len({styles.index_grid(item) for item in search.container}), goal_door_count=len(goals), best_fitness=search.best().fitness.values[0]) STAIR_FITNESS = (.7, .61, .52, .43, .8, .86, .91, .95, 1.) def deceptive_path(genome): """Reach a new cell only after losing fitness several times in the first cell.""" step = int(round(genome[0] * 8)) return (STAIR_FITNESS[step],), (max(0, step - 3) / 5,) def breeder_trial(seed, budget): """Use identical start and mutation, with or without a second breeding slot.""" def mutate(parent, rng): move = rng.choice((-1, 1)) return (float(np.clip(parent[0] + move / 8., 0., 1.)),) for label, probability in (("MEPGD", .3), ("primary slot only", 0.)): grid = Grid(shape=(6,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,)) search = MEPGD(grid, budget - 1, 1, replacement_probability=probability, mutate=mutate, seed=seed) fitness, features = deceptive_path((0.,)) grid.add(Individual([0.], fitness=Fitness(fitness, weights=(1.,)), features=Features(features))) search.optimise(deceptive_path) yield dict(method=label, seed=seed, evaluations=search.nb_evaluations + 1, cells=grid.filled_bins, best_fitness=grid.best.fitness.values[0], auxiliary_admissions=search.auxiliary_admissions) if __name__ == "__main__": trials = {"mome": (feasible_trial, 320), "gradient": (gradient_trial, 352), "nslc": (nslc_trial, 576), "breeder": (breeder_trial, 192)} parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=trials) parser.add_argument("--budget", type=int) parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33]) parser.add_argument("--include-cma", action="store_true", help="add CMA-MAEGA to the gradient comparison") args = parser.parse_args() trial, default_budget = trials[args.task] budget = default_budget if args.budget is None else args.budget if budget < 2: parser.error("Use an evaluation budget of at least two.") for seed in args.seeds: extra = {"include_cma": args.include_cma} if args.task == "gradient" else {} for row in trial(seed, budget, **extra): print(json.dumps(row, sort_keys=True))