QDpy
Loading...
Searching...
No Matches
repertoire_workflows.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run seeded workflows for BOIL, Reset-free Trial-and-Error, and QD-Meta."""
6
7import argparse
8import json
9import random
10
11import numpy as np
12
13from qdpy.algorithms import BOIL, BOPElites, IsoLineMAPElites, QDMeta, RTESkill, ResetFreeTrialAndError
14from qdpy.containers import Grid
15
16
17def landscape(individual):
18 """Score a real design with two genes and a nonlinear descriptor."""
19 x, y = individual
20 return 1. - .6 * (y - .68) ** 2 - .28 * x, .84 * x + .16 * y ** 2
21
22
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.
26 measured = []
27
28 def evaluate(individual):
29 quality, descriptor = landscape(individual)
30 measured.append((quality, descriptor))
31 return (quality,), (descriptor,)
32
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")
36 if method == "boil":
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)
44 else:
45 search = BOPElites(**options)
46 search.optimise(evaluate)
47 preview = ()
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)
52
53
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)
58 goal = (5., 2.)
59 planner = ResetFreeTrialAndError(repertoire, horizon=4, simulations=96, goal_tolerance=.2,
60 prior_std=.12, observation_noise=.025, model_capacity=7, seed=seed)
61 trials = 0
62
63 def execute(state, action):
64 nonlocal trials
65 changed = trials >= 2
66 trials += 1
67 east, north = action
68 if changed:
69 if scenario == "reversal":
70 east = -east
71 else:
72 east *= .5
73 north += east
74 return state[0] + east, state[1] + north
75
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))))
81
82
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)
88
89 def evaluate(genome):
90 nonlocal calls
91 calls += 1
92 return float(2. - np.sum((np.asarray(genome) - [.47, .52, .54]) ** 2)), tuple(genome)
93
94 def adapt(grid, goals, training):
95 nonlocal selection_calls, audits
96 points = np.asarray([tuple(elite) for elite in grid])
97 if training:
98 selection_calls += len(points) * len(goals)
99 else:
100 audits += len(points) * len(goals)
101 # Each shifted task wants a different value of the third coordinate.
102 losses = [np.sum((points - [.47, .52, goal]) ** 2, axis=1).min() for goal in goals]
103 return float(2. - np.mean(losses))
104
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
111 else:
112 np.random.seed(seed)
113 random.seed(seed)
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")
116
117 def fixed_evaluate(genome):
118 value, base = evaluate(genome)
119 return (value,), (base[0],)
120
121 run.optimise(fixed_evaluate)
122 meta_calls = 0
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))
126
127
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:
135 rows = []
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"))
143 for row in rows:
144 print(json.dumps(row, sort_keys=True, allow_nan=False))