5"""Run equal-budget comparisons for four representation search workflows."""
12from qdpy.algorithms import NSMBS, PRODUQD, BehaviorCharacterization, GenomeEncoding, MultiEncodingMAPElites
16def _flip(genome, rng):
18 index = int(rng.integers(len(child)))
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
30def _change_rectangle(genome, rng):
32 index = int(rng.integers(len(child)))
33 child[index] = int(np.clip(child[index] + rng.choice((-1, 1)), 0, 7))
37def _shape_fitness(pixels):
38 ys, xs = np.nonzero(pixels)
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)
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)
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)
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),
68def _steady_mutation(parent, rng):
69 return np.clip(parent + rng.normal(0., .07, len(parent)), 0., 1.)
73def component_comparison(seed):
75 for name, sizes
in ((
"approach", (1,)), (
"components", (1, 1, 1))):
76 contact_bins, movement_bins = set(), set()
79 def evaluate(genome, rollout_seed):
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
85 contact_bins.add(min(9, int(angle * 10.)))
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)]
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}
101def _transfer_training_panel():
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
109def transfer_comparison(seed):
110 initial, success = _transfer_training_panel()
114 return (rng.uniform(0., .1), *rng.random(12))
116 def mutate(parent, rng):
117 return (np.clip(parent[0] + rng.normal(0., .064), 0., 1.), *rng.random(12))
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
126 def measure(genome, rollout_seed):
127 nonlocal checked, first_hit
129 hit = abs(genome[0] - target) <= .025
131 first_hit = min(first_hit, checked)
132 return float(hit), (transform.transform(genome),)
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)}
144def prototype_comparison(seed):
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)
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)))
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}
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")
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)
193 for mode, metrics
in runs[0].items()}
194 print(json.dumps(results, indent=2))
197if __name__ ==
"__main__":