# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare conditional depth, closest-pair competition, and occupancy descriptors. """Seeded CPU comparisons for Deep QD, Voronoi-Elites and occupancy CVT-MAP-Elites.""" import argparse import json import random from time import perf_counter import numpy as np from scipy.spatial.distance import pdist, squareform from qdpy.algorithms import (ConditionalConfiguration, DeepQD, DominatedNoveltySearch, HiGeME, IntegerVariable, OccupancyHistogram, OccupancyMAPElites, RealVariable, TraceElites, VoronoiElites, autoqd_search) from qdpy.containers import Grid, TraceArchive, VoronoiArchive from qdpy.phenotype import Features, Fitness, Individual from qdpy.tools import iso_line_dd def _grid(shape, bounds=(0., 1.)): return Grid(shape=shape, features_domain=(bounds,) * len(shape), fitness_domain=((0., 2.),), fitness_weights=(1.,)) def _offer(grid, genome, value, features): grid.add(Individual(list(genome), fitness=Fitness((value,), weights=(1.,)), features=Features(features))) _LAYOUTS = ( ConditionalConfiguration({"layout": "sheet"}, ("span", "gauge"), ("buckling",)), ConditionalConfiguration({"layout": "ribbed"}, ("span", "gauge", "ribs"), ("stock",)), ConditionalConfiguration({"layout": "laminate"}, ("span", "gauge", "binder"), ("available",)), ) _VARIABLES = {"span": RealVariable(0., 1.), "gauge": RealVariable(0., 1.), "ribs": IntegerVariable(1, 5), "binder": RealVariable(0., 1.)} def _panel(design): span, gauge = design["span"], design["gauge"] if design["layout"] == "sheet": value = 1.82 - .18 * span - .4 * (gauge - .45)**2 residuals = {"buckling": span - .86} elif design["layout"] == "ribbed": value = 1.68 - .16 * (1. - span) - .3 * (gauge - .62)**2 - .009 * (design["ribs"] - 3)**2 residuals = {"stock": .12 - span} else: value = 1.57 - .2 * (span - .65)**2 - .4 * (gauge - .25)**2 - .12 * (design["binder"] - .5)**2 residuals = {"available": .21 - span} return (value,), (span,), residuals ## @brief Compare per-configuration retention with ordinary conditional MAP-Elites. def deep_trial(seed, budget): """Use the same three feasible design families and the same measured budget.""" for cls, method in ((HiGeME, "higeme"), (DeepQD, "deep-qd")): start = perf_counter() grid = _grid((12,)) search = cls(grid, budget, _VARIABLES, configurations=_LAYOUTS, batch_size=8, optimisation_task="maximisation", seed=seed) def evaluate(genome): return _panel(search.decode(genome)) search.optimise(evaluate) counts = (search.deep_archive.configuration_counts if method == "deep-qd" else tuple(sum(ind[0] == branch for ind in grid) for branch in range(len(_LAYOUTS)))) yield dict(study="deep", method=method, seed=seed, evaluations=search.nb_evaluations, cells=grid.filled_bins, configuration_counts=counts, retained=sum(counts), mean_configurations=sum(counts) / len(grid), best_cell_qd=grid.qd_score(False), elapsed_s=perf_counter() - start) def _islands(genome): x, y, alpha, beta = genome descriptor = (.48 * x + .52 * (alpha >= .5), y) peaks = [.5 + 1.4 * np.exp(-8 * ((x - u)**2 + (y - v)**2)) for u, v in ((.25, .8), (.8, .3))] return (float(max(peaks) - .27 * (beta - .4)**2),), descriptor ## @brief Compare closest-pair competition with Dominated Novelty Search. def voronoi_trial(seed, budget, capacity): """Give both methods the same Gaussian variation scale and archive capacity.""" domain = ((0., 1.),) * 2 for method in ("voronoi", "dns"): random.seed(seed) np.random.seed(seed) start = perf_counter() if method == "voronoi": archive = VoronoiArchive(capacity, features_domain=domain, fitness_domain=((0., 2.),), storage_type="orderedset") search = VoronoiElites(archive, budget, 4, batch_size=8, initial_samples=8, sigma=.08, seed=seed) else: search = DominatedNoveltySearch(budget, 4, capacity, 8, iso_sigma=.08, line_sigma=0., fitness_domain=((0., 2.),), optimisation_task="maximisation") search.optimise(_islands, batch_mode=True) archive = search.container report = _grid((8, 8)) for elite in archive: report.add(elite) near = None if len(archive) > 1: distances = squareform(pdist([ind.features.values for ind in archive])) np.fill_diagonal(distances, np.inf) near = float(distances.min(axis=1).mean()) yield dict(study="voronoi", method=method, seed=seed, evaluations=search.nb_evaluations, capacity=capacity, retained=len(archive), reporting_cells=report.filled_bins, qd_score=report.qd_score(False), mean_nearest_distance=near, elapsed_s=perf_counter() - start) ## @brief Time full-capacity offers with exact closest-pair competition. def capacity_trial(seed, offers): """Preload the archive before timing a fixed stream of new candidates.""" for capacity in (32, 128, 512): rng = np.random.default_rng(seed) archive = VoronoiArchive(capacity, features_domain=((0., 1.),) * 2, storage_type="orderedset") points = rng.random((capacity + offers, 3)) candidates = [Individual((i,), fitness=Fitness((float(z),), weights=(1.,)), features=Features((x, y))) for i, (x, y, z) in enumerate(points)] for candidate in candidates[:capacity]: archive.add(candidate) start = perf_counter() for candidate in candidates[capacity:]: archive.add(candidate) elapsed = perf_counter() - start yield dict(study="capacity", method="voronoi", seed=seed, capacity=capacity, offers=offers, admitted=archive.nb_added - capacity, elapsed_s=elapsed, microseconds_per_offer=elapsed / offers * 1e6) ## @brief Roll out one route with variable timing around a rectangular obstacle. def navigate(genome): """Return a scalar navigation score and a trajectory of 25 positions.""" end_x, end_y, turn, pace = genome t = np.linspace(0., 1., 25)[:, None]**(.65 + 1.5 * pace) path = ((1. - t)**2 * [.08, .5] + 2 * t * (1. - t) * [.52, turn] + t**2 * [end_x, end_y]) x, y = path.T hits = np.flatnonzero((.38 <= x) & (x <= .64) & (.43 <= y) & (y <= .57)) if hits.size: path[hits[0]:] = path[hits[0] - 1] error = np.square(path[-1] - [.9, .54]).sum() return float(.3 + 1.6 * np.exp(-5 * error) - .22 * bool(hits.size)), path def _endpoint_archive(evaluate, geometry, seed, budget): rng = np.random.default_rng(seed) for step in range(budget): if step < 16 or not len(geometry): point = rng.random(4) else: first, second = rng.integers(len(geometry), size=2) point = iso_line_dd(geometry[first], geometry[second], bounds=(0., 1.), rng=rng) fitness, path = evaluate(point) _offer(geometry, point, fitness, path[-1]) return geometry ## @brief Compare trajectory descriptors on a common navigation task and reporting grid. def occupancy_trial(seed, budget, with_autoqd=False): """Share real evaluation budgets and audit the retained measured paths.""" reference = np.random.default_rng(119).random((512, 2)) histogram = OccupancyHistogram.fit(reference, 12, seed=119) methods = ("occupancy", "endpoint", "trace") + (("autoqd",) if with_autoqd else ()) for method in methods: calls, observations = 0, {} def evaluate(genome): nonlocal calls calls += 1 fitness, path = navigate(genome) observations[tuple(genome)] = (fitness, path) return fitness, path start = perf_counter() if method == "occupancy": archive = histogram.make_archive(64, fitness_domain=(0., 2.), seed=seed) search = OccupancyMAPElites(archive, budget, 4, histogram=histogram, seed=seed) search.optimise(evaluate) elif method == "endpoint": archive = _endpoint_archive(evaluate, _grid((8, 8)), seed, budget) elif method == "trace": archive = TraceArchive(_grid((8, 8))) TraceElites(archive, 4, iso_sigma=.01, seed=seed).run(evaluate, budget) else: def evaluate_autoqd(genome, _seed): score, path = evaluate(genome) return score, [path] archive = autoqd_search(evaluate_autoqd, _grid((8, 8), (-1.2, 1.2)), budget=budget, x0=[.5] * 4, sigma0=.2, threshold_min=0., trajectory_width=2, batch_size=8, embedding_dim=16, update_interval=5, ind_domain=(0., 1.), seed=seed).archive endpoints = _grid((8, 8)) paths = TraceArchive(_grid((8, 8))) genomes = {elite.genome if method == "trace" else tuple(elite) for elite in archive} # Keep tie handling independent of hash ordering during rebinning. for genome in sorted(genomes): value, path = observations[genome] _offer(endpoints, genome, value, path[-1]) paths.add(genome, value, path) best = max(observations[genome][0] for genome in genomes) yield dict(study="occupancy", method=method, seed=seed, evaluations=calls, trajectory_steps=calls * 25, retained=len(genomes), search_cells=archive.filled_bins, endpoint_cells=endpoints.filled_bins, trace_cells=paths.filled_bins, endpoint_qd=endpoints.qd_score(False), best=best, elapsed_s=perf_counter() - start) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("method", choices=("deep", "voronoi", "capacity", "occupancy")) parser.add_argument("--budget", type=int, help="Evaluation budget or number of timed offers") parser.add_argument("--capacity", type=int, default=32, help="Archive capacity for the Voronoi search comparison") parser.add_argument("--seeds", nargs="+", type=int, default=[7, 13, 23]) parser.add_argument("--with-autoqd", action="store_true", help="Include AutoQD using the optional cma extra") args = parser.parse_args() minimum = 3 if args.method == "deep" else 1 if args.capacity < 1 or (args.budget is not None and args.budget < minimum): parser.error(f"Use a positive capacity and a budget of at least {minimum} for {args.method}.") if args.with_autoqd and args.method != "occupancy": parser.error("--with-autoqd is available with occupancy.") for seed in args.seeds: if args.method == "deep": trial = deep_trial(seed, args.budget or 480) elif args.method == "voronoi": trial = voronoi_trial(seed, args.budget or 400, args.capacity) elif args.method == "capacity": trial = capacity_trial(seed, args.budget or 128) else: trial = occupancy_trial(seed, args.budget or 320, args.with_autoqd) for row in trial: print(json.dumps(row, allow_nan=False)) if __name__ == "__main__": main()