5"""Run seeded workflows for BOIL, Reset-free Trial-and-Error, and QD-Meta."""
13from qdpy.algorithms import BOIL, BOPElites, IsoLineMAPElites, QDMeta, RTESkill, ResetFreeTrialAndError
17def landscape(individual):
18 """Score a real design with two genes and a nonlinear descriptor."""
20 return 1. - .6 * (y - .68) ** 2 - .28 * x, .84 * x + .16 * y ** 2
23def run_boil(method, seed, budget=36):
24 """Spend the same real budget on global search and on interactive refinement."""
25 target, weight = .83, 3.
28 def evaluate(individual):
29 quality, descriptor = landscape(individual)
30 measured.append((quality, descriptor))
31 return (quality,), (descriptor,)
33 grid = Grid(shape=(5,), features_domain=((0., 1.),), fitness_domain=((0., 1.),))
34 options = dict(container=grid, budget=budget, dimension=2, ind_domain=(0., 1.), quality_floor=0.,
35 initial_samples=6, candidate_pool=24, restarts=2, seed=seed, optimisation_task=
"max")
37 search = BOIL(**options)
38 search.optimise(evaluate, budget=budget // 3)
39 preview = search.prediction_map(samples=128)
40 search.focus([(3,), (4,)])
41 search.optimise(evaluate, budget=budget // 6)
42 search.set_target((target,), distance_weight=weight)
43 search.optimise(evaluate)
45 search = BOPElites(**options)
46 search.optimise(evaluate)
48 fitness, descriptor = max(measured, key=
lambda entry: entry[0] - weight * abs(entry[1] - target))
49 error = abs(descriptor - target)
50 return dict(method=method, seed=seed, attempts=search.nb_evaluations, occupied=len(grid),
51 preview_cells=len(preview), target_error=error, target_utility=fitness - weight * error)
54def run_rte(adapt, seed, max_trials=16, scenario="reversal"):
55 """Navigate a point system whose horizontal control changes mid-run."""
56 moves = ((1., 0.), (-1., 0.), (0., 1.), (0., -1.))
57 repertoire = tuple(RTESkill(move, move)
for move
in moves)
59 planner = ResetFreeTrialAndError(repertoire, horizon=4, simulations=96, goal_tolerance=.2,
60 prior_std=.12, observation_noise=.025, model_capacity=7, seed=seed)
63 def execute(state, action):
69 if scenario ==
"reversal":
74 return state[0] + east, state[1] + north
76 path = planner.run((0., 0.), goal, execute, max_trials=max_trials, adapt=adapt)
77 return dict(method=
"rte" if adapt
else "fixed-planner", scenario=scenario, seed=seed, cap=max_trials,
78 trials=trials, model_observations=planner.stats.observations,
79 simulations=planner.stats.planning_rollouts, goal_reached=path.goal_reached,
80 final_distance=float(np.linalg.norm(np.subtract(path.states[-1], goal))))
83def run_meta(method, seed, generations=5):
84 """Choose a feature projection for recovery after a change in the fitness function."""
85 calls, selection_calls, audits = 0, 0, 0
86 training_goals = (.22, .5, .78)
87 held_out_goals = (.12, .37, .65, .91)
92 return float(2. - np.sum((np.asarray(genome) - [.47, .52, .54]) ** 2)), tuple(genome)
94 def adapt(grid, goals, training):
95 nonlocal selection_calls, audits
96 points = np.asarray([tuple(elite)
for elite
in grid])
98 selection_calls += len(points) * len(goals)
100 audits += len(points) * len(goals)
102 losses = [np.sum((points - [.47, .52, goal]) ** 2, axis=1).min()
for goal
in goals]
103 return float(2. - np.mean(losses))
105 budget = 24 + generations * 4 * 12
106 if method ==
"qd-meta":
107 run = QDMeta(3, ((0., 1.),) * 3, (7,), initial_samples=24, inner_evaluations=12,
108 population_size=4, seed=seed, iso_sigma=.09)
109 result = run.run(evaluate,
lambda grid: adapt(grid, training_goals,
True), generations=generations)
110 grid, meta_calls = result.archive, result.meta_evaluations
114 grid = Grid(shape=(7,), features_domain=((0., 1.),), fitness_domain=((0., 2.),))
115 run = IsoLineMAPElites(grid, budget, dimension=3, iso_sigma=.09, optimisation_task=
"max")
117 def fixed_evaluate(genome):
118 value, base = evaluate(genome)
119 return (value,), (base[0],)
121 run.optimise(fixed_evaluate)
123 return dict(method=method, seed=seed, attempts=calls, meta_calls=meta_calls,
124 meta_trials=selection_calls, held_out_score=adapt(grid, held_out_goals,
False),
125 audit_trials=audits, cells=len(grid))
128if __name__ ==
"__main__":
129 parser = argparse.ArgumentParser(description=__doc__)
130 parser.add_argument(
"suite", choices=(
"boil",
"rte",
"meta",
"all"))
131 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 22, 33])
132 parser.add_argument(
"--quick", action=
"store_true")
133 args = parser.parse_args()
134 for seed
in args.seeds:
136 if args.suite
in (
"boil",
"all"):
137 rows.extend(run_boil(method, seed, 24
if args.quick
else 36)
for method
in (
"boil",
"bop-elites"))
138 if args.suite
in (
"rte",
"all"):
139 rows.extend(run_rte(adapt, seed, 12
if args.quick
else 16, scenario)
140 for scenario
in (
"reversal",
"drift")
for adapt
in (
True,
False))
141 if args.suite
in (
"meta",
"all"):
142 rows.extend(run_meta(method, seed, 2
if args.quick
else 5)
for method
in (
"qd-meta",
"fixed-projection"))
144 print(json.dumps(row, sort_keys=
True, allow_nan=
False))