# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare multi-descriptor success, dynamic CMA, density descent and ES gradient search. """Run small, matched-budget comparisons for four QDpy methods.""" import argparse from importlib.metadata import PackageNotFoundError, version import json from pathlib import Path import platform import numpy as np from examples.dynamic_map_elites import audit_at, evaluate as shifted_sphere from qdpy import __version__ from qdpy.algorithms import (CMAMAE, MEES, RandomSearchMutPolyBounded, cma_mega_es, dds_kde, dynamic_cma_me, dynamic_map_elites, multi_bd_mes) from qdpy.benchmarks import illumination_rastrigin_normalised from qdpy.containers import Container, Grid, NoveltyArchive from qdpy.simple import run def grid(shape=(8, 8), weights=(-1.,)): """Use the same reporting cells for competing methods.""" return Grid(shape=shape, features_domain=((0., 1.),) * len(shape), fitness_domain=((0., 1.),), fitness_weights=weights, storage_type="orderedset") def navigate(genome): """Follow four moves around a wall and report endpoint and path centroid.""" point = np.array([.15, .3]) path = [point] for move in np.asarray(genome).reshape(-1, 2): candidate = np.clip(point + .9 * (move - .5), 0., 1.) if (point[0] < .5 <= candidate[0] or candidate[0] < .5 <= point[0]): fraction = (.5 - point[0]) / (candidate[0] - point[0]) if point[1] + fraction * (candidate[1] - point[1]) < .58: candidate[0] = point[0] point = candidate path.append(point) distance = np.linalg.norm(point - [.88, .32]) return distance < .14, (float(1 - min(distance, 1.)),), { "endpoint": tuple(point), "path": tuple(np.mean(path, axis=0)), } def success_study(budget, seed): """Compare success-prioritised search with one and two descriptor views.""" results = [] for names in (("endpoint",), ("endpoint", "path")): archives = {name: grid(weights=(1.,)) for name in names} def evaluate(genome): success, fitness, descriptors = navigate(genome) return success, fitness, {name: descriptors[name] for name in names} result = multi_bd_mes(archives, evaluate, dimension=8, budget=budget, seed=seed) results.append(dict(method="multi-bd-mes" if len(names) > 1 else "single-grid-mes", attempts=result.attempts, successful_evaluations=result.successful_evaluations, success_cells={name: sum(elite.scores["success"] for elite in archive) for name, archive in archives.items()})) archive = grid(weights=(1.,)) successful = 0 def evaluate_endpoint(genome): nonlocal successful success, fitness, descriptors = navigate(genome) successful += int(success) return fitness, descriptors["endpoint"], {"success": bool(success)} search = RandomSearchMutPolyBounded(archive, budget=budget, dimension=8, optimisation_task="maximisation") run(search, evaluate_endpoint, seed=seed) results.append(dict(method="map-elites", attempts=search.nb_evaluations, successful_evaluations=successful, success_cells={"endpoint": sum(elite.scores["success"] for elite in archive)})) return results def dynamic_study(budget, seed): """Measure archive freshness after objective and descriptor shifts.""" results = [] for name in ("dynamic-cma-me", "static-cma-me", "dynamic-map-elites"): archive = grid() if name == "dynamic-map-elites": result = dynamic_map_elites(archive, shifted_sphere, dimension=4, budget=budget, seed=seed) probes = 0 else: result = dynamic_cma_me(archive, shifted_sphere, x0=[.5] * 4, budget=budget, batch_size=12, seed=seed, refresh=name == "dynamic-cma-me") probes = result.detection_attempts freshness, audited = audit_at(archive, budget - 1) results.append(dict(method=name, attempts=result.offspring_attempts + result.refresh_attempts + probes, probes=probes, refreshes=result.refresh_attempts, audit_calls=audited.rollouts, freshness=freshness, coverage=audited.corrected_coverage, qd_score=audited.corrected_qd_score)) return results def diversity_measurement(genome): """Use constant quality and two nonlinear descriptors to isolate coverage.""" first, second = .5 + .5 * np.sin(5 * np.asarray(genome[:2]) + np.asarray(genome[2:4])) return (1.,), (first, second) def density_study(budget, seed): """Compare DDS-KDE, novelty search and constant-quality CMA-MAE.""" results = [] for name in ("dds-kde", "novelty-search", "cma-mae"): archive = grid(weights=(1.,)) if name == "dds-kde": result = dds_kde(archive, diversity_measurement, x0=[.5] * 4, budget=budget, bandwidth=.12, reservoir_size=96, batch_size=12, seed=seed) attempts = result.attempts elif name == "novelty-search": history = Container(storage_type="orderedset") novelty = NoveltyArchive(parents=[history], features_domain=archive.features_domain, fitness_domain=archive.fitness_domain, threshold_novelty=.04) search = RandomSearchMutPolyBounded(novelty, budget=budget, batch_size=12, dimension=4, optimisation_task="maximisation") run(search, diversity_measurement, seed=seed) archive.update(history) attempts = search.nb_evaluations else: search = CMAMAE(archive, budget, [.5] * 4, .15, 12, 0., ind_domain=(0., 1.), optimisation_task="maximisation", seed=seed) search.optimise(diversity_measurement) attempts = search.nb_evaluations results.append(dict(method=name, attempts=attempts, coverage=archive.filled_bins / 64)) return results def rastrigin(genome): """Return an objective and descriptor pair for the black-box gradient study.""" fitness, descriptors, _ = illumination_rastrigin_normalised(genome, nb_features=2) return fitness, tuple(descriptors) def gradient_study(budget, seed): """Compare an ES arborescence against ME-ES and CMA-MAE.""" results = [] for name in ("cma-mega-es", "me-es", "cma-mae"): archive = grid() if name == "cma-mega-es": result = cma_mega_es(archive, rastrigin, x0=[.5] * 4, budget=budget, batch_size=12, es_sigma=.06, es_samples=8, seed=seed) attempts = result.attempts elif name == "me-es": search = MEES(archive, [.5] * 4, pairs=4, sigma=.06, ind_domain=(0, 1), seed=seed) def evaluate(genome): fitness, descriptors = rastrigin(genome) return fitness[0], descriptors search.run(evaluate, budget) attempts = search.evaluations else: search = CMAMAE(archive, budget, [.5] * 4, .15, 12, -1., ind_domain=(0., 1.), seed=seed) search.optimise(rastrigin) attempts = search.nb_evaluations results.append(dict(method=name, attempts=attempts, coverage=archive.filled_bins / 64, qd_score=archive.qd_score())) return results def main(): """Run the selected studies at the same budget and save per-seed results.""" studies = dict(success=success_study, dynamic=dynamic_study, density=density_study, gradient=gradient_study) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--studies", nargs="+", choices=tuple(studies), default=list(studies)) parser.add_argument("--budget", type=int, default=388) parser.add_argument("--seeds", type=int, nargs="+", default=[7, 13, 23]) parser.add_argument("--output", type=Path) args = parser.parse_args() records = [dict(study=name, seed=seed, **row) for name in args.studies for seed in args.seeds for row in studies[name](args.budget, seed)] try: cma = version("cma") except PackageNotFoundError: cma = None data = json.dumps(dict(schema_version=1, qdpy=__version__, python=platform.python_version(), numpy=np.__version__, cma=cma, budget=args.budget, trials=records), indent=2, allow_nan=False) if args.output is None: print(data) else: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(data + "\n", encoding="utf-8") if __name__ == "__main__": main()