QDpy
Loading...
Searching...
No Matches
interactive_design.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run four paired comparisons on original CPU design tasks."""
6
7import argparse
8from collections import deque
9import json
10
11import numpy as np
12
13from qdpy.algorithms import (
14 MORTAR,
15 ConstrainedSurpriseSearch,
16 DescriptorAxis,
17 FeasibleInfeasibleNoveltySearch,
18 InteractiveConstrainedMAPElites,
19 UserDrivenQD,
20 mortar_skill_score,
21)
22from qdpy.containers import Grid
23
24
25def _layout_sample(rng):
26 return rng.random((5, 5)).ravel() > .30
27
28
29def _layout_mutate(genome, rng):
30 child = list(genome)
31 for _ in range(int(rng.integers(1, 4))):
32 position = int(rng.integers(len(child)))
33 child[position] = not child[position]
34 return child
35
36
37def _layout_measure(genome, seed):
38 tiles = np.asarray(genome, dtype=bool).reshape(5, 5)
39 reachable = {(0, 0)} if tiles[0, 0] else set()
40 queue = deque(reachable)
41 while queue:
42 y, x = queue.popleft()
43 for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
44 a, b = y + dy, x + dx
45 if 0 <= a < 5 and 0 <= b < 5 and tiles[a, b] and (a, b) not in reachable:
46 reachable.add((a, b))
47 queue.append((a, b))
48 density = float(tiles.mean())
49 symmetry = float((tiles == tiles[:, ::-1]).mean())
50 reach = len(reachable) / tiles.size
51 links = (np.count_nonzero(tiles[:, :-1] & tiles[:, 1:])
52 + np.count_nonzero(tiles[:-1, :] & tiles[1:, :])) / 40.
53 fitness = .45 * (1. - abs(density - .6)) + .35 * reach + .2 * links
54 scores = dict(density=density, symmetry=symmetry, reach=reach, links=links)
55 return fitness, scores, (.55 - reach, 0. if (4, 4) in reachable else 1.)
56
57
58def _view(names):
59 return tuple(DescriptorAxis(name, (0., 1.), 8) for name in names)
60
61
62
63def interactive_comparison(seed):
64 initial = _view(("density", "symmetry"))
65 report = _view(("reach", "links"))
66 edit = tuple(bool(x) for x in np.eye(5, dtype=bool).ravel())
67 # Connect the main diagonal with one horizontal tile between consecutive steps.
68 edit = tuple(x or i in (1, 7, 13, 19, 5, 11, 17, 23, 2, 8) for i, x in enumerate(edit))
69 rows = {}
70 for method in ("fixed", "interactive"):
71 search = InteractiveConstrainedMAPElites(
72 initial, fitness_domain=(0., 1.), sample=_layout_sample, mutate=_layout_mutate, cell_capacity=3,
73 anchor_probability=.4, seed=seed,
74 )
75 search.run(_layout_measure, 200)
76 if method == "interactive":
77 search.reproject(report)
78 search.submit(edit, _layout_measure)
79 search.run(_layout_measure, 200 + (method == "fixed"))
80 search.reproject(report)
81 stats = search.stats
82 rows[method] = dict(evaluations=stats.evaluations, feasible=stats.feasible_evaluations,
83 occupied=search.archive.filled_bins,
84 qd_sum=float(np.nansum(search.archive.quality_array)))
85 return rows
86
87
88
89def surprise_comparison(seed):
90 rows = {}
91 for method, cls in (("fins", FeasibleInfeasibleNoveltySearch), ("surprise", ConstrainedSurpriseSearch)):
92 grid = Grid(shape=(8, 8), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2, fitness_weights=(1.,))
93 search = cls(grid, initializer=_layout_sample, mutate=_layout_mutate, population_size=24,
94 initial_samples=24, seed=seed)
95
96 def evaluate(genome, stream):
97 fitness, scores, residuals = _layout_measure(genome, stream)
98 return fitness, (scores["reach"], scores["links"]), residuals
99
100 stats = search.run(evaluate, 500)
101 rows[method] = dict(evaluations=stats.evaluations, feasible=stats.feasible_evaluations, occupied=len(grid),
102 qd_sum=sum(row.fitness.values[0] for row in grid))
103 return rows
104
105
106
107def preference_comparison(seed):
108 rows = {}
109 for method, penalty in (("reseed", 0.), ("preference", .8)):
110 grid = Grid(shape=(16,), fitness_domain=((0., 1.),), features_domain=((0., 1.),))
111 search = UserDrivenQD(
112 grid, sample=lambda rng: rng.random(2), initial_samples=32,
113 mutate=lambda parent, rng: np.clip(parent + rng.normal(0., .10, 2), 0., 1.), seed=seed,
114 )
115
116 def evaluate(genome, stream):
117 style, size = genome
118 ideal = .25 if size < .5 else .75
119 return .85 - .6 * (style - ideal) ** 2, (size,)
120
121 search.run(evaluate, 180)
122 search.choose([i for i, row in enumerate(search.panel) if row[0] < .5], penalty=penalty, projection="pca")
123 stats = search.run(evaluate, 300)
124 rows[method] = dict(evaluations=stats.evaluations, occupied=len(search.archive),
125 preferred=float(np.mean([row[0] < .5 for row in search.archive])),
126 drift=float(np.mean([row.scores["udqd_drift"] for row in search.archive])),
127 raw=float(np.mean([row.scores["udqd_raw_fitness"] for row in search.archive])))
128 return rows
129
130
131def _dial_neighbors(position, components):
132 neighbors = [position - 1, position + 1]
133 for stride, phase in components:
134 if position % 3 == phase:
135 if stride == 0:
136 neighbors.append(12 - position)
137 else:
138 neighbors.append(position + stride)
139 return sorted({state for state in neighbors if 0 <= state <= 12})
140
141
142def _solve_dial(start, goal, components, allowance):
143 frontier = deque(((start, 0),))
144 seen = {start}
145 for _ in range(allowance):
146 if not frontier:
147 break
148 position, depth = frontier.popleft()
149 if position == goal:
150 return 1. / (1 + depth)
151 for state in _dial_neighbors(position, components):
152 if state not in seen:
153 seen.add(state)
154 frontier.append((state, depth + 1))
155 return 0.
156
157
158def _dial_evaluate(components, stream):
159 # A fixed panel of starts and targets in an original modular dial puzzle.
160 cases = ((0, 10), (3, 12), (2, 8), (11, 1))
161 return mortar_skill_score(tuple(sum(_solve_dial(start, goal, components, allowance) for start, goal in cases)
162 for allowance in (2, 5, 9, 13)))
163
164
165
166def mortar_comparison(seed):
167 rows = {}
168 strides = (-4, -3, -2, 0, 2, 3, 4)
169 library = tuple((stride, phase) for stride in strides for phase in range(3))
170
171 def vary(parent, rng):
172 if rng.random() < .5:
173 return (int(rng.choice(strides)), parent[1])
174 return (parent[0], int(rng.integers(3)))
175
176 for method in ("random", "ucb"):
177 archive = Grid(shape=(7, 3), fitness_domain=((-2., 2.),),
178 features_domain=((0., 7.), (0., 3.)))
179 search = MORTAR(archive, sample=lambda rng: library[int(rng.integers(len(library)))], mutate=vary,
180 describe=lambda item: (strides.index(item[0]) + .5, item[1] + .5),
181 partners=library, composition_budget=12, selection=method, seed=seed)
182 evaluations, top = [], []
183
184 def evaluate(components, stream):
185 value = _dial_evaluate(components, stream)
186 evaluations.append(value)
187 return value
188
189 for _ in range(72):
190 search.run(evaluate, 1)
191 top.append(max(reward for _, reward in search.last_round.compositions))
192 rows[method] = dict(proposals=search.stats.proposals, evaluations=search.stats.composition_evaluations,
193 occupied=len(archive), mean_skill=float(np.mean(evaluations)),
194 mean_best_skill=float(np.mean(top)))
195 return rows
196
197
198
199def main():
200 parser = argparse.ArgumentParser(description=__doc__)
201 workflows = dict(interactive=interactive_comparison, surprise=surprise_comparison,
202 preference=preference_comparison, mortar=mortar_comparison)
203 parser.add_argument("workflow", choices=("all", *workflows), default="all", nargs="?")
204 parser.add_argument("--seeds", type=int, default=5, help="Number of seeds starting at zero.")
205 options = parser.parse_args()
206 if options.seeds < 1:
207 parser.error("--seeds must be positive")
208 results = {}
209 for label, compare in workflows.items():
210 if options.workflow in ("all", label):
211 runs = [compare(seed) for seed in range(options.seeds)]
212 results[label] = {name: {key: round(float(np.mean([run[name][key] for run in runs])), 4)
213 for key in row}
214 for name, row in runs[0].items()}
215 print(json.dumps(results, indent=2))
216
217
218if __name__ == "__main__":
219 main()