# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Run matched-budget pilots for Differential MAP-Elites, mixed Bayesian QD, and preference emitters. """Reproducible CPU studies for bounded search and interactive illumination.""" import argparse import json import math from time import perf_counter import numpy as np from qdpy.algorithms import (CategoricalVariable, ConstrainedMAPElites, DifferentialMAPElites, IntegerVariable, IsoLineMAPElites, MixedBayesianQD, PreferenceLearningMAPElites, RealVariable) from qdpy.containers import CVTGrid, Grid from qdpy.phenotype import Features, Fitness, Individual from qdpy.simple import _coordinator_seed ## @brief Compare DE and Iso+LineDD with shared initial elites and CVT cells. def differential_trial(seed, budget): """Use a rotated ill-conditioned ellipsoid and a rotated Rastrigin function.""" dimension = 10 bounds = (-5.12, 5.12) domain = (bounds, bounds) axes = np.linspace(-4.48, 4.48, 8) centers = [(a, b) for a in axes for b in axes] rng = np.random.default_rng(seed) rotation, _ = np.linalg.qr(rng.normal(size=(dimension, dimension))) warmup = min(24, budget - 1) warm = rng.uniform(*bounds, size=(warmup, dimension)) weights = np.geomspace(1., 1e4, dimension) for landscape in ("ellipsoid", "rastrigin"): for method in ("differential", "iso_line"): archive = CVTGrid(shape=(len(centers),), centroids=centers, features_domain=domain, fitness_domain=((0., 1.),), fitness_weights=(1.,)) def evaluate(genome): rotated = rotation @ genome error = (np.sum(weights * rotated ** 2) if landscape == "ellipsoid" else np.sum(rotated ** 2 + 10 * (1 - np.cos(2 * np.pi * rotated)))) return (1. / (1. + float(error)),), tuple(genome[:2]) start = perf_counter() for genome in warm: quality, behavior = evaluate(genome) archive.add(Individual(genome.tolist(), fitness=Fitness(quality, weights=(1.,)), features=Features(behavior))) options = dict(container=archive, budget=budget - warmup, dimension=dimension, ind_domain=bounds, batch_size=1, optimisation_task="maximisation") search = (DifferentialMAPElites(**options, initial_samples=0, seed=seed) if method == "differential" else IsoLineMAPElites(**options, iso_sigma=.15)) with _coordinator_seed(seed): search.optimise(evaluate) yield dict(method=method, seed=seed, landscape=landscape, evaluations=search.nb_evaluations + warmup, coverage=archive.filled_bins / len(centers), qd_score=archive.qd_score(), best=archive.best.fitness.values[0], differential_proposals=getattr(search, "differential_proposals", 0), elapsed_s=perf_counter() - start) ## @brief Allocate the same number of measurements to two constrained mixed-variable methods. def mixed_trial(seed, budget): """Design a synthetic beam with width, a rib count, and unordered material.""" variables = (RealVariable(0., 1.), IntegerVariable(1, 4), CategoricalVariable(("light", "dense", "hybrid"))) properties = {"light": (.55, .75, .16), "dense": (.92, .25, .25), "hybrid": (.75, .57, .21)} for method in ("gower", "constrained_me"): start = perf_counter() archive = Grid(shape=(8, 4), features_domain=((0., 1.),) * 2, fitness_domain=((0., 3.),), fitness_weights=(1.,)) options = dict(container=archive, budget=budget, variables=variables, batch_size=4, optimisation_task="maximisation", constraint_names=("load", "mass")) search = (MixedBayesianQD(**options, initial_samples=12, surrogate_budget=96, seed=seed) if method == "gower" else ConstrainedMAPElites(**options)) feasible_attempts = 0 def evaluate(genome): nonlocal feasible_attempts width, ribs, material = search.decode(genome) strength, target, density = properties[material] load = .40 + .48 * width - strength - .04 * (ribs - 1) mass = density * (ribs + width) - .89 feasible_attempts += load <= 0. and mass <= 0. quality = 1. + math.exp(-10 * (width - target) ** 2) + .06 * ribs return (quality,), (width, (ribs - 1) / 3.), {"load": load, "mass": mass} # An empty feasible archive is a legitimate outcome with short budgets. with _coordinator_seed(seed): while search.nb_evaluations < budget: batch = search.ask_batch(min(search.batch_size, budget - search.nb_evaluations)) search.tell_batch([evaluate(candidate) for candidate in batch]) yield dict(method=method, seed=seed, exact=search.nb_evaluations, surrogate=getattr(search, "surrogate_evaluations", 0), feasible_attempts=feasible_attempts, coverage=archive.filled_bins / 32, score=archive.qd_score(), best=None if archive.best is None else archive.best.fitness.values[0], elapsed_s=perf_counter() - start) ## @brief Compare automated parent choices under an equal number of simulated user selections. def preference_trial(seed, budget): """Use one shared warm start and a scripted user who favors larger second descriptors.""" warmup = min(20, budget - 1) start_points = np.random.default_rng(seed).uniform(0., 1., size=(warmup, 2)) def measure(genome): x, y = genome return (1. - ((x - .5) ** 2 + (y - .5) ** 2),), (x, y) def preference(genome): return float(genome[1] + .2 * genome[0]) for mode in ("ridge", "tabular", "uniform"): start = perf_counter() grid = Grid(shape=(10, 10), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) for genome in start_points: quality, descriptors = measure(genome) grid.add(Individual(genome.tolist(), fitness=Fitness(quality, weights=(1.,)), features=Features(descriptors))) search = PreferenceLearningMAPElites(grid, budget, 2, mode=mode, seed=seed, batch_size=12, iso_sigma=.09, line_sigma=.12) preferred = total = 0 while search.nb_evaluations < budget - warmup: occupied = {cell: entries[0] for cell, entries in grid.solutions.items() if entries} selected = max(occupied, key=lambda cell: preference(occupied[cell])) search.record_feedback([selected]) candidates = search.ask_batch(min(12, budget - warmup - search.nb_evaluations)) preferred += sum(preference(genome) >= .85 for genome in candidates) total += len(candidates) search.tell_batch([measure(genome) for genome in candidates]) yield dict(method=mode, seed=seed, evaluations=search.nb_evaluations + warmup, feedback=search.feedback_rounds, favored_fraction=preferred / total, coverage=len(grid) / 100, qd_score=grid.qd_score(), elapsed_s=perf_counter() - start) def main(): """Emit per-method and seed JSON records.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("study", choices=("differential", "mixed", "preference")) parser.add_argument("--seeds", type=int, nargs="+", default=[7]) parser.add_argument("--budget", type=int) args = parser.parse_args() trial, default = {"differential": (differential_trial, 480), "mixed": (mixed_trial, 96), "preference": (preference_trial, 164)}[args.study] budget = default if args.budget is None else args.budget if budget < 2: parser.error("--budget must be at least two") for seed in args.seeds: for record in trial(seed, budget): print(json.dumps(record)) if __name__ == "__main__": main()