# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Small CPU comparisons for coevolution, surrogate niching, Pareto curves, and heuristic design. """Run four seeded comparisons using the base QDpy installation.""" import argparse import ast import json from dataclasses import asdict import numpy as np from qdpy.algorithms import BOPElites, CoME, MEliTA, MOLE, QDHeuristicDesign, SPHEN from qdpy.containers import Grid def design_grid(shape, bounds=(0., 1.), direction=1., fitness=(0., 2.)): """Make a fixed best-only grid with a native scalar objective.""" return Grid(shape=shape, features_domain=(bounds,) * len(shape), fitness_domain=(fitness,), fitness_weights=(direction,)) def component_trial(seed, budget): """Search complementary layout and controller settings under the same pair budget.""" for name in ("CoME", "joint MAP-Elites", "MEliTA"): occupied = {} pair_grid = design_grid((7, 7)) def quality(parts): layout, controller = parts target = .9 - .8 * layout + .05 * np.sin(6. * layout) value = 1. - .85 * (target - controller) ** 2 - .1 * (layout - .55) ** 2 cell = pair_grid.index_grid(parts) occupied[cell] = max(value, occupied.get(cell, 0.)) return float(value) def mutate(value, rng): return float(np.clip(value + rng.normal(0., .12), 0., 1.)) if name == "CoME": grids = (design_grid((7,)), design_grid((7,))) search = CoME(grids, initialize=(lambda rng: float(rng.random()),) * 2, mutations=(mutate, mutate), descriptors=(lambda part: (part,),) * 2, evaluate=quality, radius=2., partners=2, initial_samples=8, seed=seed) evaluations = search.run(budget).evaluations retained = {tuple(item) for grid in grids for item in grid} else: search = MEliTA( pair_grid, initialize=lambda rng: tuple(rng.random(2)), coherence=quality, mutations=(lambda parts, rng: mutate(parts[0], rng), lambda parts, rng: mutate(parts[1], rng)), descriptors=(float, float), transverse=name == "MEliTA", seed=seed, ) evaluations = search.run(budget).assessments retained = {tuple(item) for item in pair_grid} cells = {pair_grid.index_grid(pair) for pair in retained} yield dict(method=name, seed=seed, evaluations=evaluations, evaluated_pair_cells=len(occupied), retained_pair_cells=len(cells), component_cells=[len({cell[side] for cell in cells}) for side in range(2)], best_quality=max(occupied.values()), evaluated_qd_score=sum(occupied.values())) def black_box(genome): """Measure coupled descriptors and a nonlinear synthetic fitness.""" x, y = genome first = .15 + .68 * x + .10 * np.sin(7. * y) second = .09 + .72 * y + .12 * np.sin(9. * x) ** 2 quality = 1. + .2 * np.cos(8. * (x - y)) - .4 * (x - .65) ** 2 - .25 * (y - .4) ** 2 return (float(quality),), (float(first), float(second)) def surrogate_trial(seed, budget): """Compare a posterior-mean acquisition map with probabilistic cell assignment.""" for kind in (SPHEN, BOPElites): grid = design_grid((6, 6)) if kind is SPHEN: search = kind(grid, budget, 2, seed=seed, initial_samples=8, surrogate_budget=96, batch_size=4) else: search = kind(grid, budget, 2, (0., 1.), 0., seed=seed, initial_samples=8, candidate_pool=32, restarts=1, optimisation_task="maximisation") search.optimise(black_box) row = dict(method=kind.__name__, seed=seed, evaluations=search.nb_evaluations, cells=grid.filled_bins, qd_score=float(sum(item.fitness.values[0] for item in grid)), best_quality=grid.best.fitness.values[0]) if kind is SPHEN: predicted = search.prediction_map(192, seed=seed) row.update(prediction_checks=search.prediction_checks, misclassified=search.misclassified, surrogate_evaluations=search.surrogate_evaluations, prediction_budget=192, predicted_cells=len(predicted)) yield row def two_curves(point): """Return two costs and a Jacobian with efficient line segments at y = ±0.6.""" x, y = point well = y * y - .36 return ((x + .8) ** 2 + well ** 2, (x - .8) ** 2 + well ** 2), ( (2 * (x + .8), 4 * y * well), (2 * (x - .8), 4 * y * well), ) def landscape_trial(seed, budget): """Compare the traced decision-space curves to their analytic coordinates.""" rng = np.random.default_rng(seed) starts = [(float(rng.uniform(-.2, .2)), float(sign * rng.uniform(.72, .9))) for sign in (1, -1)] result = MOLE(((-1., 1.),) * 2, step_size=.1).run(two_curves, starts, budget) curves = [np.asarray([item.genome for item in trace]) for trace in result.sets] return [dict(method="MOLE", seed=seed, evaluations=result.evaluations, curves=len(curves), points=[len(curve) for curve in curves], spans=[float(np.ptp(curve[:, 0])) for curve in curves], max_curve_error=max((float(np.max(np.abs(np.abs(curve[:, 1]) - .6))) for curve in curves), default=None), transitions=len(result.transitions))] def schedule_cost(rule, case): """Score a deterministic single-machine schedule under a weighted tardiness cost.""" times, due, preference = case a, b = rule # A weight of zero uses just the other term. Each term is scaled within the case. order = np.argsort(a * times / times.mean() + b * due / due.mean(), kind="stable") completion = np.cumsum(times[order]) tardiness = np.maximum(completion - due[order], 0.) return float(((1. - preference) * completion.mean() + preference * tardiness.mean()) / times.sum()) def schedule_structure(rule): """Extract feature counts from the syntax of a two-term scheduling rule.""" a, b = rule terms = ["duration"] * a + ["due_date"] * b tree = ast.parse(" + ".join(terms), mode="eval") names = [node.id for node in ast.walk(tree) if isinstance(node, ast.Name)] return names.count("duration"), names.count("due_date") def propose_schedule(parent, attribution, rng): """Use structural attribution to bias which term changes in a scheduling rule.""" magnitudes = np.abs(attribution) + .1 axis = int(rng.choice(2, p=magnitudes / magnitudes.sum())) rule = list(parent) rule[axis] = int(np.clip(rule[axis] + rng.choice((-2, -1, 1, 2)), 0, 9)) return tuple(rule) if any(rule) else None def _cases(rng, count): for i in range(count): durations = rng.integers(1, 16, size=12) deadlines = rng.uniform(.06, .75, size=12) * durations.sum() yield durations, deadlines, (0., .5, 1.)[i % 3] def scheduling_trial(seed, budget): """Build one repertoire and compare two selectors on a disjoint test panel.""" train_rng, test_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2)) training, held_out = tuple(_cases(train_rng, 12)), tuple(_cases(test_rng, 30)) grid = design_grid((7, 7), (-1., 1.), -1., (0., 1.)) search = QDHeuristicDesign( grid, structure=schedule_structure, propose=propose_schedule, evaluate=schedule_cost, instance_features=lambda case: (case[2],), descriptor_indices=(0, 1), neighbors=4, seed=seed, ) stats = search.run([(8, 0), (0, 8), (4, 4), (7, 1)], training, budget) for label, select in (("instance selector", search.select), ("single best", lambda case: grid.best[0])): selected = [select(case) for case in held_out] mean_cost = float(np.mean([schedule_cost(rule, case) for rule, case in zip(selected, held_out)])) yield dict(method=label, seed=seed, **asdict(stats), cells=grid.filled_bins, held_out_evaluations=len(held_out), held_out_cost=mean_cost, selected_rules=len(set(selected))) if __name__ == "__main__": trials = {"components": (component_trial, 160), "surrogate": (surrogate_trial, 64), "landscape": (landscape_trial, 512), "scheduling": (scheduling_trial, 360)} parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=trials) parser.add_argument("--budget", type=int) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33]) args = parser.parse_args() trial, default_budget = trials[args.task] budget = default_budget if args.budget is None else args.budget for seed in args.seeds: for row in trial(seed, budget): print(json.dumps(row, sort_keys=True))