# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare shared and separate archives on a conditional design problem. """Run HiGeME and an equal-budget per-configuration MAP-Elites baseline.""" from argparse import ArgumentParser from itertools import product import json from time import perf_counter from qdpy.algorithms import ( ConditionalConfiguration, ConstrainedMAPElites, HiGeME, IntegerVariable, RealVariable, ) from qdpy.containers import Grid from qdpy.simple import run NAMES = ("light", "reinforced", "composite") VARIABLES = {"span": IntegerVariable(0, 3), "level": IntegerVariable(0, 5), "trim": RealVariable(0, 1), **{name: IntegerVariable(0, 4) for name in NAMES}} CONFIGURATIONS = tuple(ConditionalConfiguration({"style": name}, ("span", "level", "trim", name), (f"{name}_limit",)) for name in NAMES) def make_grid(): """Build the shared reporting geometry for the three design styles.""" return Grid(shape=(4, 6), fitness_domain=((0., 10.),), features_domain=((-0.5, 3.5), (-0.5, 5.5)), fitness_weights=(1.,)) ## @brief Score the active parameters of a synthetic conditional design. def evaluate(design): """Return quality, two descriptors, and the current configuration's constraint.""" span, level, trim, style = (design[name] for name in ("span", "level", "trim", "style")) branch = NAMES.index(style) target = (span + level) % 5 quality = 10 - (trim - (0.25 + 0.5 * (span % 2))) ** 2 quality -= 0.15 * abs(design[style] - target) + 0.4 * abs(branch - (span + level) % len(NAMES)) return (quality,), (span, level), {f"{style}_limit": level - (branch + 3)} def oracle(): """Find the best feasible design in each bin at its analytic trim optimum.""" result = {} for span, level, style, tuning in product(range(4), range(6), NAMES, range(5)): design = dict(span=span, level=level, style=style, trim=0.25 + 0.5 * (span % 2)) design[style] = tuning (quality,), cell, constraints = evaluate(design) if max(constraints.values()) <= 0: result[cell] = max(quality, result.get(cell, 0.)) return result def comparison(budget, seed): """Run both methods and report their error against the per-cell oracle.""" reference = oracle() search = HiGeME(make_grid(), budget, VARIABLES, configurations=CONFIGURATIONS, seed=seed, optimisation_task="maximisation") start = perf_counter() search.optimise(lambda candidate: evaluate(search.decode(candidate)), batch_mode=True) yield _record("higeme", search.container, reference, seed, search.nb_evaluations, perf_counter() - start) start = perf_counter() merged = make_grid() attempts = 0 for i, configuration in enumerate(CONFIGURATIONS): size = budget // len(NAMES) + int(i < budget % len(NAMES)) baseline = ConstrainedMAPElites(make_grid(), size, [VARIABLES[key] for key in configuration.active], constraint_names=configuration.constraints, real_sigma=0.3, infeasible_parent_probability=0, optimisation_task="maximisation") def measure(genome): return evaluate(dict(configuration.selectors, **dict(zip(configuration.active, baseline.decode(genome))))) result = run(baseline, measure, seed=seed + i) attempts += result.evaluations for elite in result.archive: # Different branches can have the same active values. merged.add(type(elite)([i, *elite], fitness=elite.fitness, features=elite.features, scores=elite.scores)) yield _record("separate-configurations", merged, reference, seed, attempts, perf_counter() - start) def _record(method, archive, reference, seed, budget, seconds): measured = {tuple(elite.features): elite.fitness.values[0] for elite in archive} return dict(method=method, seed=seed, attempts=budget, coverage=len(measured) / len(reference), qd_score=sum(measured.values()), oracle_gap=sum(value - measured.get(cell, 0.) for cell, value in reference.items()), seconds=seconds) if __name__ == "__main__": parser = ArgumentParser(description=__doc__) parser.add_argument("--budget", type=int, default=512) parser.add_argument("--seeds", nargs="+", type=int, default=[11, 29, 47]) args = parser.parse_args() for seed in args.seeds: for row in comparison(args.budget, seed): print(json.dumps(row, sort_keys=True, allow_nan=False))