5"""Run four seeded benchmarks using the base installation."""
13from scipy.optimize
import Bounds, LinearConstraint
15from qdpy.algorithms import (CartesianGraphSpace, CuriosityMutPolyBounded, DecisionTreePolicy,
16 GraphMAPElites, MILPArchiveSearch, MatchResult, RandomSearchMutPolyBounded,
17 QDSelfPlay, YouthMAPElites, game_search)
23def assignment_trial(seed, budget):
24 """Match all niche optima against exhaustive enumeration of six two-machine assignments."""
25 rng = np.random.default_rng(seed)
26 cost = rng.integers(1, 20, size=12)
27 loads = np.asarray([1, 1, 2, 2, 3, 4])
28 descriptor = np.zeros((2, 12), dtype=int)
29 descriptor[0, ::2], descriptor[1, ::2] = 1, loads
30 rows = np.vstack((np.kron(np.eye(6), np.ones((1, 2))), descriptor[1]))
31 constraints = LinearConstraint(rows, [1] * 6 + [4], [1] * 6 + [10])
32 grid = Grid(shape=(7, 14), features_domain=((0, 6), (0, 13)), fitness_domain=((0, 120),),
33 fitness_weights=(-1.,))
35 def measure(first_machine):
36 bits = np.column_stack((first_machine, 1 - np.asarray(first_machine))).ravel()
37 features = tuple(descriptor @ bits)
38 if 4 <= features[1] <= 10:
39 return grid.index_grid(features), int(cost @ bits)
43 for assignment
in itertools.product((0, 1), repeat=6):
44 cell, fitness = measure(assignment)
46 oracle[cell] = min(fitness, oracle.get(cell, np.inf))
48 search = MILPArchiveSearch(grid, cost, Bounds(0, 1), descriptor, constraints=constraints)
49 results = search.run()
50 solved = {row.cell: row.fitness
for row
in results
if row.status ==
"optimal"}
51 assert solved == oracle
and all(row.status !=
"unresolved" for row
in results)
52 yield dict(method=
"MILP", seed=seed, cells=len(solved), solver_calls=sum(row.solver_status
is not None for row
in results),
53 infeasible_cells=len(results) - len(solved), exhaustive_assignments=2**6,
54 best_cost=min(solved.values()), mean_cell_gap=0.)
58 for _
in range(budget):
59 if elites
and rng.random() < .9:
60 parent = tuple(elites.values())[rng.integers(len(elites))][1]
61 assignment = list(parent)
62 assignment[rng.integers(6)] ^= 1
64 assignment = rng.integers(2, size=6).tolist()
65 cell, fitness = measure(assignment)
66 if cell
is not None and (cell
not in elites
or fitness < elites[cell][0]):
67 elites[cell] = fitness, tuple(assignment)
68 yield dict(method=
"assignment MAP-Elites", seed=seed, cells=len(elites), candidate_calls=budget,
69 best_cost=min((value
for value, _
in elites.values()), default=
None),
70 mean_cell_gap=float(np.mean([value - oracle[cell]
for cell, (value, _)
in elites.items()]))
74STEPS = ((1, 0), (-1, 0), (0, 1), (0, -1))
75START, GOAL = (1, 3), (5, 3)
78def _advance(position, action):
81 dx, dy = STEPS[action]
82 x, y = position[0] + dx, position[1] + dy
83 if 0 <= x < 7
and 0 <= y < 7
and (x != 3
or y
in (0, 6)):
88def navigate(choose, *, mask_direction=False, horizon=22):
89 """Reach a goal across a wall with two possible detours using a reactive policy."""
91 for step
in range(horizon):
93 observation = (x / 3. - 1., y / 3. - 1.,
94 0.
if mask_direction
else (GOAL[0] - x) / 6., (GOAL[1] - y) / 6.,
95 *[float(_advance(position, action) == position)
for action
in range(4)])
96 position = _advance(position, choose(observation))
98 return 1. + (horizon - step) / (horizon + 1), position
99 return 1. / (1 + sum(abs(a - b)
for a, b
in zip(position, GOAL))), position
102def _graph_action(graph, observation):
103 dx, dy = graph.act(observation)
106 if abs(dx) > abs(dy):
107 return 0
if dx > 0.
else 1
108 return 2
if dy > 0.
else 3
111def _tree_policy(genome):
112 thresholds = (-.5, 0., .5)
113 first, left, right = (tuple(genome[i:i + 2])
for i
in (0, 2, 4))
115 return DecisionTreePolicy(
116 (first[0], thresholds[first[1]], (left[0], thresholds[left[1]], *leaves[:2]),
117 (right[0], thresholds[right[1]], *leaves[2:])), (8,), 4,
121def graph_trial(seed, budget):
122 """Compare structural and endpoint archives with fitness-only CGP and shallow decision trees."""
123 space = CartesianGraphSpace(8, 2, 12, operation_rate=.09, connection_rate=.12)
124 for mode
in (
"graph fitness only",
"graph behavior",
"graph joint",
"decision trees"):
125 if mode ==
"graph fitness only":
126 shape, domains = (1,), ((0., 1.),)
128 shape, domains = (7, 7), ((0., 6.),) * 2
129 if mode ==
"graph joint":
130 shape, domains = (*shape, 4, 4), (*domains, (0., 1.), (0., 1.))
131 archive = Grid(shape=shape, features_domain=domains, fitness_domain=((0., 2.),), fitness_weights=(1.,))
135 if mode ==
"decision trees":
136 return _tree_policy(genome).act, ()
137 graph = space.decode(genome)
138 return lambda observation: _graph_action(graph, observation), graph.structure_descriptors
140 def evaluate(genome):
141 policy, structure = decode(genome)
142 score, endpoint = navigate(policy)
143 endpoints.add(endpoint)
144 if mode ==
"graph fitness only":
146 elif mode ==
"graph joint":
147 descriptor = (*endpoint, *structure)
149 descriptor = endpoint
150 return (score,), descriptor
152 if mode ==
"decision trees":
153 rng = np.random.default_rng(seed)
154 limits = np.array([8, 3] * 3 + [4] * 4)
155 for _
in range(budget):
157 candidate = list(archive[rng.integers(len(archive))])
158 gene = rng.integers(len(limits))
159 flip = rng.integers(limits[gene] - 1)
160 candidate[gene] = int(flip + (flip >= candidate[gene]))
162 candidate = list(map(int, rng.integers(limits)))
163 fitness, descriptor = evaluate(candidate)
164 archive.add(Individual(candidate, fitness=Fitness(fitness, weights=(1.,)), features=Features(descriptor)))
166 GraphMAPElites(archive, budget, space, seed=seed, batch_size=1).optimise(evaluate)
168 audited = [navigate(decode(item)[0], mask_direction=
True)[0]
for item
in archive]
169 structures = {decode(item)[1]
for item
in archive}
170 yield dict(method=mode, seed=seed, evaluations=budget, explored_endpoints=len(endpoints),
171 cells=archive.filled_bins, distinct_graph_structures=len(structures)
if mode !=
"decision trees" else None,
172 best_fitness=archive.best.fitness.values[0], held_out_evaluations=len(audited),
173 best_masked_fitness=max(audited))
176def cyclic_action(strategy):
177 """Decode the cycle action from a bounded scalar strategy."""
178 return min(2, int(3 * strategy[0]))
181def cyclic_match(red, blue):
182 """Score rock-paper-scissors with a small penalty away from each action center."""
183 red_action, blue_action = cyclic_action(red), cyclic_action(blue)
184 red_penalty = abs(red[0] - (red_action + .5) / 3.)
185 blue_penalty = abs(blue[0] - (blue_action + .5) / 3.)
186 reward = (0., 1., -1.)[(red_action - blue_action) % 3] + .2 * (blue_penalty - red_penalty)
187 return reward, -reward
190def propose_cyclic(context, rng):
191 """Perturb an archived strategy, with larger moves after a loss."""
192 size = .19
if context.payoffs[context.role] < 0.
else .12
193 value = context.parents[context.role][0]
194 return (float(np.clip(value + rng.normal(0., size), 0., 1.)),)
197def self_play_trial(seed, budget):
198 """Compare grid-free competition and GAME using the same maximum match budget."""
199 search = QDSelfPlay(((.17,), (.17,)), play=cyclic_match, propose=propose_cyclic,
200 embed=
lambda role, policy: policy, novelty_radius=.16, opponents=3, seed=seed)
201 stats = search.run(budget)
204 return MatchResult(cyclic_match(red, blue), (red, blue))
206 result = game_search(play, dimensions=(1, 1), rounds=8, matches_per_round=budget // 8,
207 task_count=3, cells_per_task=5, seed=seed, match_budget=budget)
209 for side
in (
"red",
"blue"):
210 latest = next((row.representatives
for row
in reversed(result.rounds)
if row.side == side), ())
211 game.append(tuple(item.genome
for item
in latest))
212 panel = tuple(((action + .5) / 3.,)
for action
in range(3))
213 for label, archives, calls
in ((
"QD Self-Play", search.archives, stats.matches),
214 (
"GAME", tuple(game), result.total_attempts)):
215 coverage = [len({cyclic_action(policy)
for policy
in archive})
for archive
in archives]
217 for side, archive
in enumerate(archives):
218 for opponent
in panel:
219 payoffs = [(cyclic_match(policy, opponent)
if side == 0
else cyclic_match(opponent, policy))[side]
220 for policy
in archive]
222 values.append(max(payoffs))
223 yield dict(method=label, seed=seed, matches=calls, role_action_coverage=coverage,
224 mean_best_panel_payoff=float(np.mean(values))
if values
else None,
225 audit_matches=sum(map(len, archives)) * len(panel))
228def youth_trial(seed, budget):
229 """Compare recent, uniform, and curiosity parent selection under the same maze and mutation."""
232 def evaluate(genome):
233 actions = iter(min(3, int(value * 4))
for value
in genome)
234 quality, endpoint = navigate(
lambda observation: next(actions), horizon=length)
235 return (quality,), endpoint
237 def mutate(parent, rng):
238 return mut_polynomial_bounded(list(parent), eta=5., low=0., up=1., mut_pb=2 / length)
240 for kind
in (
"youth",
"uniform",
"curiosity"):
241 archive = Grid(shape=(7, 7), features_domain=((0, 6),) * 2,
242 fitness_domain=((0., 2.),), fitness_weights=(1.,))
243 start = [float(value)
for value
in np.random.default_rng(seed).random(length)]
244 fitness, endpoint = evaluate(start)
245 archive.add(Individual(start, fitness=Fitness(fitness, weights=(1.,)), features=Features(endpoint)))
248 search = YouthMAPElites(archive, budget, length, parent_window=4, mutate=mutate, seed=seed, batch_size=1)
250 settings = dict(init_pb=0., eta=5., mut_pb=2 / length, optimisation_task=
"maximisation", batch_size=1)
251 search = (RandomSearchMutPolyBounded(archive, budget, length, sel_pb=1., **settings)
252 if kind ==
"uniform" else CuriosityMutPolyBounded(archive, budget, length, **settings))
253 search.optimise(evaluate)
254 yield dict(method=kind, seed=seed, evaluations=search.nb_evaluations + 1, cells=archive.filled_bins,
255 best_fitness=archive.best.fitness.values[0], reached_goal=bool(archive.solutions[GOAL]))
258if __name__ ==
"__main__":
259 trials = {
"assignment": (assignment_trial, 64),
"graphs": (graph_trial, 768),
260 "self-play": (self_play_trial, 144),
"youth": (youth_trial, 256)}
261 parser = argparse.ArgumentParser(description=__doc__)
262 parser.add_argument(
"task", choices=trials)
263 parser.add_argument(
"--budget", type=int)
264 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 22, 33])
265 args = parser.parse_args()
266 trial, default_budget = trials[args.task]
267 budget = default_budget
if args.budget
is None else args.budget
268 if budget < (16
if args.task ==
"self-play" else 1):
269 parser.error(
"Use a positive budget, or at least 16 matches for self-play.")
270 for seed
in args.seeds:
271 for row
in trial(seed, budget):
272 print(json.dumps(row, sort_keys=
True))