# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Matched CPU examples for editable archives, constraint forecasts, preferences, and component credit. """Run four paired comparisons on original CPU design tasks.""" import argparse from collections import deque import json import numpy as np from qdpy.algorithms import ( MORTAR, ConstrainedSurpriseSearch, DescriptorAxis, FeasibleInfeasibleNoveltySearch, InteractiveConstrainedMAPElites, UserDrivenQD, mortar_skill_score, ) from qdpy.containers import Grid def _layout_sample(rng): return rng.random((5, 5)).ravel() > .30 def _layout_mutate(genome, rng): child = list(genome) for _ in range(int(rng.integers(1, 4))): position = int(rng.integers(len(child))) child[position] = not child[position] return child def _layout_measure(genome, seed): tiles = np.asarray(genome, dtype=bool).reshape(5, 5) reachable = {(0, 0)} if tiles[0, 0] else set() queue = deque(reachable) while queue: y, x = queue.popleft() for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)): a, b = y + dy, x + dx if 0 <= a < 5 and 0 <= b < 5 and tiles[a, b] and (a, b) not in reachable: reachable.add((a, b)) queue.append((a, b)) density = float(tiles.mean()) symmetry = float((tiles == tiles[:, ::-1]).mean()) reach = len(reachable) / tiles.size links = (np.count_nonzero(tiles[:, :-1] & tiles[:, 1:]) + np.count_nonzero(tiles[:-1, :] & tiles[1:, :])) / 40. fitness = .45 * (1. - abs(density - .6)) + .35 * reach + .2 * links scores = dict(density=density, symmetry=symmetry, reach=reach, links=links) return fitness, scores, (.55 - reach, 0. if (4, 4) in reachable else 1.) def _view(names): return tuple(DescriptorAxis(name, (0., 1.), 8) for name in names) ## @brief Compare an editor intervention with an equal-budget fixed search. def interactive_comparison(seed): initial = _view(("density", "symmetry")) report = _view(("reach", "links")) edit = tuple(bool(x) for x in np.eye(5, dtype=bool).ravel()) # Connect the main diagonal with one horizontal tile between consecutive steps. edit = tuple(x or i in (1, 7, 13, 19, 5, 11, 17, 23, 2, 8) for i, x in enumerate(edit)) rows = {} for method in ("fixed", "interactive"): search = InteractiveConstrainedMAPElites( initial, fitness_domain=(0., 1.), sample=_layout_sample, mutate=_layout_mutate, cell_capacity=3, anchor_probability=.4, seed=seed, ) search.run(_layout_measure, 200) if method == "interactive": search.reproject(report) search.submit(edit, _layout_measure) search.run(_layout_measure, 200 + (method == "fixed")) search.reproject(report) stats = search.stats rows[method] = dict(evaluations=stats.evaluations, feasible=stats.feasible_evaluations, occupied=search.archive.filled_bins, qd_sum=float(np.nansum(search.archive.quality_array))) return rows ## @brief Compare forecast deviation with feasible nearest-neighbor novelty. def surprise_comparison(seed): rows = {} for method, cls in (("fins", FeasibleInfeasibleNoveltySearch), ("surprise", ConstrainedSurpriseSearch)): grid = Grid(shape=(8, 8), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2, fitness_weights=(1.,)) search = cls(grid, initializer=_layout_sample, mutate=_layout_mutate, population_size=24, initial_samples=24, seed=seed) def evaluate(genome, stream): fitness, scores, residuals = _layout_measure(genome, stream) return fitness, (scores["reach"], scores["links"]), residuals stats = search.run(evaluate, 500) rows[method] = dict(evaluations=stats.evaluations, feasible=stats.feasible_evaluations, occupied=len(grid), qd_sum=sum(row.fitness.values[0] for row in grid)) return rows ## @brief Compare reseeding alone with reseeding and a preference penalty. def preference_comparison(seed): rows = {} for method, penalty in (("reseed", 0.), ("preference", .8)): grid = Grid(shape=(16,), fitness_domain=((0., 1.),), features_domain=((0., 1.),)) search = UserDrivenQD( grid, sample=lambda rng: rng.random(2), initial_samples=32, mutate=lambda parent, rng: np.clip(parent + rng.normal(0., .10, 2), 0., 1.), seed=seed, ) def evaluate(genome, stream): style, size = genome ideal = .25 if size < .5 else .75 return .85 - .6 * (style - ideal) ** 2, (size,) search.run(evaluate, 180) search.choose([i for i, row in enumerate(search.panel) if row[0] < .5], penalty=penalty, projection="pca") stats = search.run(evaluate, 300) rows[method] = dict(evaluations=stats.evaluations, occupied=len(search.archive), preferred=float(np.mean([row[0] < .5 for row in search.archive])), drift=float(np.mean([row.scores["udqd_drift"] for row in search.archive])), raw=float(np.mean([row.scores["udqd_raw_fitness"] for row in search.archive]))) return rows def _dial_neighbors(position, components): neighbors = [position - 1, position + 1] for stride, phase in components: if position % 3 == phase: if stride == 0: neighbors.append(12 - position) else: neighbors.append(position + stride) return sorted({state for state in neighbors if 0 <= state <= 12}) def _solve_dial(start, goal, components, allowance): frontier = deque(((start, 0),)) seen = {start} for _ in range(allowance): if not frontier: break position, depth = frontier.popleft() if position == goal: return 1. / (1 + depth) for state in _dial_neighbors(position, components): if state not in seen: seen.add(state) frontier.append((state, depth + 1)) return 0. def _dial_evaluate(components, stream): # A fixed panel of starts and targets in an original modular dial puzzle. cases = ((0, 10), (3, 12), (2, 8), (11, 1)) return mortar_skill_score(tuple(sum(_solve_dial(start, goal, components, allowance) for start, goal in cases) for allowance in (2, 5, 9, 13))) ## @brief Compare composition traversal at fixed depth, branching, and evaluation budgets. def mortar_comparison(seed): rows = {} strides = (-4, -3, -2, 0, 2, 3, 4) library = tuple((stride, phase) for stride in strides for phase in range(3)) def vary(parent, rng): if rng.random() < .5: return (int(rng.choice(strides)), parent[1]) return (parent[0], int(rng.integers(3))) for method in ("random", "ucb"): archive = Grid(shape=(7, 3), fitness_domain=((-2., 2.),), features_domain=((0., 7.), (0., 3.))) search = MORTAR(archive, sample=lambda rng: library[int(rng.integers(len(library)))], mutate=vary, describe=lambda item: (strides.index(item[0]) + .5, item[1] + .5), partners=library, composition_budget=12, selection=method, seed=seed) evaluations, top = [], [] def evaluate(components, stream): value = _dial_evaluate(components, stream) evaluations.append(value) return value for _ in range(72): search.run(evaluate, 1) top.append(max(reward for _, reward in search.last_round.compositions)) rows[method] = dict(proposals=search.stats.proposals, evaluations=search.stats.composition_evaluations, occupied=len(archive), mean_skill=float(np.mean(evaluations)), mean_best_skill=float(np.mean(top))) return rows ## @brief Print paired means for seeds starting at zero. def main(): parser = argparse.ArgumentParser(description=__doc__) workflows = dict(interactive=interactive_comparison, surprise=surprise_comparison, preference=preference_comparison, mortar=mortar_comparison) parser.add_argument("workflow", choices=("all", *workflows), default="all", nargs="?") parser.add_argument("--seeds", type=int, default=5, help="Number of seeds starting at zero.") options = parser.parse_args() if options.seeds < 1: parser.error("--seeds must be positive") results = {} for label, compare in workflows.items(): if options.workflow in ("all", label): runs = [compare(seed) for seed in range(options.seeds)] results[label] = {name: {key: round(float(np.mean([run[name][key] for run in runs])), 4) for key in row} for name, row in runs[0].items()} print(json.dumps(results, indent=2)) if __name__ == "__main__": main()