5"""Run four paired comparisons on original CPU design tasks."""
8from collections
import deque
15 ConstrainedSurpriseSearch,
17 FeasibleInfeasibleNoveltySearch,
18 InteractiveConstrainedMAPElites,
25def _layout_sample(rng):
26 return rng.random((5, 5)).ravel() > .30
29def _layout_mutate(genome, rng):
31 for _
in range(int(rng.integers(1, 4))):
32 position = int(rng.integers(len(child)))
33 child[position] =
not child[position]
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)
42 y, x = queue.popleft()
43 for dy, dx
in ((1, 0), (-1, 0), (0, 1), (0, -1)):
45 if 0 <= a < 5
and 0 <= b < 5
and tiles[a, b]
and (a, b)
not in reachable:
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.)
59 return tuple(DescriptorAxis(name, (0., 1.), 8)
for name
in names)
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())
68 edit = tuple(x
or i
in (1, 7, 13, 19, 5, 11, 17, 23, 2, 8)
for i, x
in enumerate(edit))
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,
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)
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)))
89def surprise_comparison(seed):
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)
96 def evaluate(genome, stream):
97 fitness, scores, residuals = _layout_measure(genome, stream)
98 return fitness, (scores[
"reach"], scores[
"links"]), residuals
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))
107def preference_comparison(seed):
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,
116 def evaluate(genome, stream):
118 ideal = .25
if size < .5
else .75
119 return .85 - .6 * (style - ideal) ** 2, (size,)
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])))
131def _dial_neighbors(position, components):
132 neighbors = [position - 1, position + 1]
133 for stride, phase
in components:
134 if position % 3 == phase:
136 neighbors.append(12 - position)
138 neighbors.append(position + stride)
139 return sorted({state
for state
in neighbors
if 0 <= state <= 12})
142def _solve_dial(start, goal, components, allowance):
143 frontier = deque(((start, 0),))
145 for _
in range(allowance):
148 position, depth = frontier.popleft()
150 return 1. / (1 + depth)
151 for state
in _dial_neighbors(position, components):
152 if state
not in seen:
154 frontier.append((state, depth + 1))
158def _dial_evaluate(components, stream):
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)))
166def mortar_comparison(seed):
168 strides = (-4, -3, -2, 0, 2, 3, 4)
169 library = tuple((stride, phase)
for stride
in strides
for phase
in range(3))
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)))
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 = [], []
184 def evaluate(components, stream):
185 value = _dial_evaluate(components, stream)
186 evaluations.append(value)
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)))
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")
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)
214 for name, row
in runs[0].items()}
215 print(json.dumps(results, indent=2))
218if __name__ ==
"__main__":