QDpy
Loading...
Searching...
No Matches
representation_search.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run equal-budget comparisons for four representation search workflows."""
6
7import argparse
8import json
9
10import numpy as np
11
12from qdpy.algorithms import NSMBS, PRODUQD, BehaviorCharacterization, GenomeEncoding, MultiEncodingMAPElites
13from qdpy.containers import Grid
14
15
16def _flip(genome, rng):
17 child = list(genome)
18 index = int(rng.integers(len(child)))
19 child[index] ^= 1
20 return child
21
22
23def _rectangle(genome):
24 x, y, width, height = genome
25 pixels = np.zeros((8, 8), dtype=bool)
26 pixels[y:y + height + 1, x:x + width + 1] = True
27 return pixels
28
29
30def _change_rectangle(genome, rng):
31 child = list(genome)
32 index = int(rng.integers(len(child)))
33 child[index] = int(np.clip(child[index] + rng.choice((-1, 1)), 0, 7))
34 return child
35
36
37def _shape_fitness(pixels):
38 ys, xs = np.nonzero(pixels)
39 if not len(xs):
40 return None
41 adjacent = (np.count_nonzero(pixels[:, 1:] & pixels[:, :-1])
42 + np.count_nonzero(pixels[1:, :] & pixels[:-1, :]))
43 fill = len(xs) / pixels.size
44 compactness = adjacent / (2. * len(xs))
45 return float(.6 * compactness + .4 * (1. - fill)), (float(xs.mean() / 7.), fill)
46
47
48
49def encoding_comparison(seed):
50 direct = GenomeEncoding("pixels", lambda rng: rng.integers(0, 2, size=64), _flip,
51 lambda genome: np.asarray(genome, dtype=bool).reshape(8, 8))
52 rectangle = GenomeEncoding("rectangles", lambda rng: rng.integers(0, 8, size=4),
53 _change_rectangle, _rectangle)
54 rows = {}
55 for name, encodings in (("pixels", (direct,)), ("rectangles", (rectangle,)), ("mixed", (direct, rectangle))):
56 grid = Grid(shape=(10, 10), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2)
57 search = MultiEncodingMAPElites(grid, encodings, initial_samples=32 // len(encodings), seed=seed)
58 stats = search.run(_shape_fitness, 1500)
59 rows[name] = {
60 "measured": sum(stats.objective_calls),
61 "occupied": len(grid),
62 "qd_sum": sum(row.fitness.values[0] for row in grid),
63 "pixel_elites": sum(encodings[row[0]].name == "pixels" for row in grid),
64 }
65 return rows
66
67
68def _steady_mutation(parent, rng):
69 return np.clip(parent + rng.normal(0., .07, len(parent)), 0., 1.)
70
71
72
73def component_comparison(seed):
74 rows = {}
75 for name, sizes in (("approach", (1,)), ("components", (1, 1, 1))):
76 contact_bins, movement_bins = set(), set()
77 move_count = 0
78
79 def evaluate(genome, rollout_seed):
80 nonlocal move_count
81 x, y, angle, push = genome
82 reached = abs(x - .76) < .075 and abs(y - .43) < .075
83 moved = reached and abs(angle - .75) < .15 and push > .42
84 if reached:
85 contact_bins.add(min(9, int(angle * 10.)))
86 if moved:
87 move_count += 1
88 movement_bins.add(min(9, int(push * 10.)))
89 approach = (1. - np.hypot(x - .76, y - .43) / np.sqrt(2.),)
90 views = (approach, (angle,) if reached else None, (push,) if moved else None)
91 return float(moved), views[:len(sizes)]
92
93 search = NSMBS(sizes, sample=lambda rng: rng.random(4), mutate=_steady_mutation,
94 population_size=24, offspring=24, seed=seed)
95 stats = search.run(evaluate, 1200)
96 rows[name] = {"measured": stats.evaluations, "contact_bins": len(contact_bins),
97 "movement_bins": len(movement_bins), "moved": move_count}
98 return rows
99
100
101def _transfer_training_panel():
102 # Analytical measurements from source tasks with different target distances.
103 initial = [(x, *([.5] * 12)) for x in np.linspace(.01, .09, 8)]
104 success = [(target, *([.5] * 12)) for target in np.linspace(.55, .75, 8)]
105 return initial, success
106
107
108
109def transfer_comparison(seed):
110 initial, success = _transfer_training_panel()
111 rows = {}
112
113 def sample(rng):
114 return (rng.uniform(0., .1), *rng.random(12))
115
116 def mutate(parent, rng):
117 return (np.clip(parent[0] + rng.normal(0., .064), 0., 1.), *rng.random(12))
118
119 for name in ("uniform", "i2s", "xs"):
120 transform = BehaviorCharacterization.fit(initial, success, method="xs" if name == "xs" else "i2s",
121 exponent=0. if name == "uniform" else 2.)
122 solved, first = 0, []
123 for task_id, target in enumerate((.79, .86, .94)):
124 checked, first_hit = 0, 721
125
126 def measure(genome, rollout_seed):
127 nonlocal checked, first_hit
128 checked += 1
129 hit = abs(genome[0] - target) <= .025
130 if hit:
131 first_hit = min(first_hit, checked)
132 return float(hit), (transform.transform(genome),)
133
134 search = NSMBS((13,), sample=sample, mutate=mutate, population_size=24, offspring=24,
135 seed=seed * 3 + task_id)
136 search.run(measure, 720)
137 solved += int(first_hit <= 720)
138 first.append(min(first_hit, 720))
139 rows[name] = {"measured": 2160, "tasks_solved": solved, "capped_first_hit": np.mean(first)}
140 return rows
141
142
143
144def prototype_comparison(seed):
145 rows = {}
146 for mode in ("unfocused", "focused"):
147 grid = Grid(shape=(10, 6), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2)
148 search = PRODUQD(grid, 3, lambda x: (x[0], x[2]), initial_samples=16, acquisition_steps=72,
149 prediction_steps=144, evaluations_per_fit=4, mutation_sigma=.055,
150 cluster_eps=.19, min_samples=3, seed=seed)
151 measured = []
152
153 def evaluate(genome):
154 x, material, length = genome
155 pocket = min((x - .22) ** 2, (x - .78) ** 2)
156 fitness = .2 + .8 * np.exp(-38. * pocket - 4. * (material - .45) ** 2
157 - 2. * (length - .65) ** 2)
158 measured.append((x, float(fitness)))
159 return fitness
160
161 search.run(evaluate, 24)
162 target = min(range(len(search.prototypes)),
163 key=lambda position: abs(search.prototypes[position].representative.genome[0] - .22))
164 if mode == "focused":
165 search.select_prototypes((target,))
166 start = len(measured)
167 stats = search.run(evaluate, 24)
168 final = measured[start:]
169 rows[mode] = {"measured": stats.evaluations,
170 "selected_side": np.mean([x < .5 for x, _ in final]),
171 "mean_quality": np.mean([quality for _, quality in final]),
172 "occupied": len(grid),
173 "surrogate_predictions": stats.acquisition_predictions + stats.mean_predictions}
174 return rows
175
176
177
178def main():
179 parser = argparse.ArgumentParser(description=__doc__)
180 workflows = dict(encodings=encoding_comparison, components=component_comparison,
181 transfer=transfer_comparison, prototypes=prototype_comparison)
182 parser.add_argument("workflow", choices=("all", *workflows), default="all", nargs="?")
183 parser.add_argument("--seeds", type=int, default=5, help="Run seeds starting at 0.")
184 options = parser.parse_args()
185 if options.seeds < 1:
186 parser.error("--seeds must be positive")
187 results = {}
188 for name, comparison in workflows.items():
189 if options.workflow in ("all", name):
190 runs = [comparison(seed) for seed in range(options.seeds)]
191 results[name] = {mode: {key: round(float(np.mean([run[mode][key] for run in runs])), 4)
192 for key in metrics}
193 for mode, metrics in runs[0].items()}
194 print(json.dumps(results, indent=2))
195
196
197if __name__ == "__main__":
198 main()