# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief CPU comparisons for competing encodings, staged novelty, transfer, and prototypes. """Run equal-budget comparisons for four representation search workflows.""" import argparse import json import numpy as np from qdpy.algorithms import NSMBS, PRODUQD, BehaviorCharacterization, GenomeEncoding, MultiEncodingMAPElites from qdpy.containers import Grid def _flip(genome, rng): child = list(genome) index = int(rng.integers(len(child))) child[index] ^= 1 return child def _rectangle(genome): x, y, width, height = genome pixels = np.zeros((8, 8), dtype=bool) pixels[y:y + height + 1, x:x + width + 1] = True return pixels def _change_rectangle(genome, rng): child = list(genome) index = int(rng.integers(len(child))) child[index] = int(np.clip(child[index] + rng.choice((-1, 1)), 0, 7)) return child def _shape_fitness(pixels): ys, xs = np.nonzero(pixels) if not len(xs): return None adjacent = (np.count_nonzero(pixels[:, 1:] & pixels[:, :-1]) + np.count_nonzero(pixels[1:, :] & pixels[:-1, :])) fill = len(xs) / pixels.size compactness = adjacent / (2. * len(xs)) return float(.6 * compactness + .4 * (1. - fill)), (float(xs.mean() / 7.), fill) ## @brief Compare direct pixels, rectangles, and competition between the two encodings. def encoding_comparison(seed): direct = GenomeEncoding("pixels", lambda rng: rng.integers(0, 2, size=64), _flip, lambda genome: np.asarray(genome, dtype=bool).reshape(8, 8)) rectangle = GenomeEncoding("rectangles", lambda rng: rng.integers(0, 8, size=4), _change_rectangle, _rectangle) rows = {} for name, encodings in (("pixels", (direct,)), ("rectangles", (rectangle,)), ("mixed", (direct, rectangle))): grid = Grid(shape=(10, 10), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2) search = MultiEncodingMAPElites(grid, encodings, initial_samples=32 // len(encodings), seed=seed) stats = search.run(_shape_fitness, 1500) rows[name] = { "measured": sum(stats.objective_calls), "occupied": len(grid), "qd_sum": sum(row.fitness.values[0] for row in grid), "pixel_elites": sum(encodings[row[0]].name == "pixels" for row in grid), } return rows def _steady_mutation(parent, rng): return np.clip(parent + rng.normal(0., .07, len(parent)), 0., 1.) ## @brief Compare approach-only novelty with approach, contact, and movement views. def component_comparison(seed): rows = {} for name, sizes in (("approach", (1,)), ("components", (1, 1, 1))): contact_bins, movement_bins = set(), set() move_count = 0 def evaluate(genome, rollout_seed): nonlocal move_count x, y, angle, push = genome reached = abs(x - .76) < .075 and abs(y - .43) < .075 moved = reached and abs(angle - .75) < .15 and push > .42 if reached: contact_bins.add(min(9, int(angle * 10.))) if moved: move_count += 1 movement_bins.add(min(9, int(push * 10.))) approach = (1. - np.hypot(x - .76, y - .43) / np.sqrt(2.),) views = (approach, (angle,) if reached else None, (push,) if moved else None) return float(moved), views[:len(sizes)] search = NSMBS(sizes, sample=lambda rng: rng.random(4), mutate=_steady_mutation, population_size=24, offspring=24, seed=seed) stats = search.run(evaluate, 1200) rows[name] = {"measured": stats.evaluations, "contact_bins": len(contact_bins), "movement_bins": len(movement_bins), "moved": move_count} return rows def _transfer_training_panel(): # Analytical measurements from source tasks with different target distances. initial = [(x, *([.5] * 12)) for x in np.linspace(.01, .09, 8)] success = [(target, *([.5] * 12)) for target in np.linspace(.55, .75, 8)] return initial, success ## @brief Freeze transferred descriptor weights before search on held-out tasks. def transfer_comparison(seed): initial, success = _transfer_training_panel() rows = {} def sample(rng): return (rng.uniform(0., .1), *rng.random(12)) def mutate(parent, rng): return (np.clip(parent[0] + rng.normal(0., .064), 0., 1.), *rng.random(12)) for name in ("uniform", "i2s", "xs"): transform = BehaviorCharacterization.fit(initial, success, method="xs" if name == "xs" else "i2s", exponent=0. if name == "uniform" else 2.) solved, first = 0, [] for task_id, target in enumerate((.79, .86, .94)): checked, first_hit = 0, 721 def measure(genome, rollout_seed): nonlocal checked, first_hit checked += 1 hit = abs(genome[0] - target) <= .025 if hit: first_hit = min(first_hit, checked) return float(hit), (transform.transform(genome),) search = NSMBS((13,), sample=sample, mutate=mutate, population_size=24, offspring=24, seed=seed * 3 + task_id) search.run(measure, 720) solved += int(first_hit <= 720) first.append(min(first_hit, 720)) rows[name] = {"measured": 2160, "tasks_solved": solved, "capped_first_hit": np.mean(first)} return rows ## @brief Compare unfocused SAIL-style sampling with reseeding a design family. def prototype_comparison(seed): rows = {} for mode in ("unfocused", "focused"): grid = Grid(shape=(10, 6), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2) search = PRODUQD(grid, 3, lambda x: (x[0], x[2]), initial_samples=16, acquisition_steps=72, prediction_steps=144, evaluations_per_fit=4, mutation_sigma=.055, cluster_eps=.19, min_samples=3, seed=seed) measured = [] def evaluate(genome): x, material, length = genome pocket = min((x - .22) ** 2, (x - .78) ** 2) fitness = .2 + .8 * np.exp(-38. * pocket - 4. * (material - .45) ** 2 - 2. * (length - .65) ** 2) measured.append((x, float(fitness))) return fitness search.run(evaluate, 24) target = min(range(len(search.prototypes)), key=lambda position: abs(search.prototypes[position].representative.genome[0] - .22)) if mode == "focused": search.select_prototypes((target,)) start = len(measured) stats = search.run(evaluate, 24) final = measured[start:] rows[mode] = {"measured": stats.evaluations, "selected_side": np.mean([x < .5 for x, _ in final]), "mean_quality": np.mean([quality for _, quality in final]), "occupied": len(grid), "surrogate_predictions": stats.acquisition_predictions + stats.mean_predictions} return rows ## @brief Print JSON means across paired seeds. Every search runs on CPU. def main(): parser = argparse.ArgumentParser(description=__doc__) workflows = dict(encodings=encoding_comparison, components=component_comparison, transfer=transfer_comparison, prototypes=prototype_comparison) parser.add_argument("workflow", choices=("all", *workflows), default="all", nargs="?") parser.add_argument("--seeds", type=int, default=5, help="Run seeds starting at 0.") options = parser.parse_args() if options.seeds < 1: parser.error("--seeds must be positive") results = {} for name, comparison in workflows.items(): if options.workflow in ("all", name): runs = [comparison(seed) for seed in range(options.seeds)] results[name] = {mode: {key: round(float(np.mean([run[mode][key] for run in runs])), 4) for key in metrics} for mode, metrics in runs[0].items()} print(json.dumps(results, indent=2)) if __name__ == "__main__": main()