QDpy
Loading...
Searching...
No Matches
objective_voting_transfer.py
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3"""Run five small CPU searches and their comparison workflows."""
4
5import argparse
6from itertools import combinations
7import json
8
9import numpy as np
10
11from qdpy.algorithms import (
12 CMOEA,
13 CosineMAPElites,
14 DiversityEnhancingNSGAII,
15 DvDES,
16 EDOCS,
17 MOVE,
18 TBREvolution,
19)
20
21
22def real_sample(rng):
23 return tuple(rng.uniform(-1., 1., 2))
24
25
26def real_mutation(genome, rng):
27 return tuple(np.clip(np.asarray(genome) + rng.normal(0., .2, 2), -1., 1.))
28
29
30def voting(seed):
31 rng = np.random.default_rng(534)
32 targets = rng.uniform(-1., 1., (10, 2))
33 triples = list(combinations(range(len(targets)), 3))
34 subsets = tuple(triples[i] for i in rng.choice(len(triples), 11, replace=False)) + (tuple(range(10)),)
35
36 def objectives(genome, rollout_seed):
37 return np.exp(-2. * np.square(targets - genome).sum(axis=1))
38
39 move = MOVE(len(targets), sample=real_sample, mutate=real_mutation, subsets=subsets, seed=seed)
40 cmoea = CMOEA(len(targets), sample=real_sample, mutate=real_mutation, subsets=subsets,
41 bin_capacity=1, batch_size=len(subsets), seed=seed)
42 move.run(objectives, 360)
43 cmoea.run(lambda genome, rollout_seed: (objectives(genome, rollout_seed), genome), 360)
44 return {
45 "move_evaluations": move.stats.evaluations,
46 "cmoea_evaluations": cmoea.stats.evaluations,
47 "move_mean_best_objective": float(np.max([row.objectives for row in move.champions], axis=0).mean()),
48 "cmoea_mean_best_objective": float(np.max([rows[0].task_scores for rows in cmoea.bins.values()], axis=0).mean()),
49 "cross_slot_replacements": move.stats.goal_switches,
50 }
51
52
53def structural(seed):
54 def sample(rng):
55 return tuple(map(int, rng.integers(0, 2, size=12)))
56
57 def mutate(genome, rng):
58 child = list(genome)
59 flip = int(rng.integers(len(child)))
60 child[flip] = 1 - child[flip]
61 return child
62
63 def evaluate(genome, rollout_seed):
64 selected = frozenset(i for i, enabled in enumerate(genome) if enabled)
65 quality = sum((i % 4) + 1 for i in selected)
66 return (float(quality), -float(len(selected))), selected
67
68 def distance(a, b):
69 return len(a ^ b)
70
71 result = {}
72 for name, standard in (("dissimilarity", False), ("objective_crowding", True)):
73 search = DiversityEnhancingNSGAII(2, sample=sample, mutate=mutate, distance=distance,
74 standard_crowding=standard, population_size=16, seed=seed)
75 search.run(evaluate, 240)
76 result[name] = {
77 "evaluations": search.stats.evaluations,
78 "mean_dissimilarity": float(np.mean([distance(a.behavior, b.behavior)
79 for a, b in combinations(search.population, 2)])),
80 "best_quality": max(row.objectives[0] for row in search.population),
81 }
82 return result
83
84
85def clusters(seed):
86 def evaluate(genome, rollout_seed):
87 x, y = genome
88 reward = max(.84 - 2. * (x + .72) ** 2, 1. - 2. * (x - .72) ** 2) - .25 * y ** 2
89 return reward, genome
90
91 rng = np.random.default_rng(seed)
92 initial = [real_sample(rng), real_sample(rng)]
93 method = EDOCS(2, archive_size=8, clusters=2, probes=6, es_steps=2, ind_domain=(-1., 1.), seed=seed)
94 baseline = DvDES(initial, pairs=3, ind_domain=(-1., 1.), seed=seed)
95 method.run(evaluate, 268)
96 baseline.run(evaluate, 268)
97 return {
98 "edo_evaluations": method.stats.evaluations,
99 "dvd_evaluations": baseline.stats.evaluations,
100 "edo_best_reward": max(row.reward for row in method.archive),
101 "dvd_best_reward": max(row.reward for row in baseline.population),
102 "edo_arm_observations": method.stats.arm_counts,
103 }
104
105
106def ensemble(seed):
107 x_train = np.linspace(-2., 2., 28)
108 x_test = np.linspace(-1.98, 1.98, 45)
109
110 def target(x):
111 return np.cos(1.7 * x) + .3 * np.sin(3. * x)
112
113 def predictions(genome, x):
114 amplitude, phase, offset = genome
115 return amplitude * np.cos(1.7 * x + phase) + offset
116
117 def sample(rng):
118 return tuple(rng.uniform(-1., 1., 3))
119
120 def mutate(genome, rng):
121 return tuple(np.clip(np.asarray(genome) + rng.normal(0., .2, 3), -1.5, 1.5))
122
123 labels = target(x_train)
124 measured = []
125
126 def evaluate(genome, rollout_seed):
127 prediction = predictions(genome, x_train)
128 loss = float(np.square(labels - prediction).mean())
129 measured.append((loss, genome))
130 return loss, prediction
131
132 def crossover(parent, donor, rng):
133 return tuple(np.where(rng.random(3) < .5, parent, donor))
134
135 search = CosineMAPElites(labels, sample=sample, mutate=mutate, crossover=crossover,
136 population_size=24, shape=(8, 8), seed=seed)
137 search.run(evaluate, 288)
138 size = min(5, len(search.archive))
139 evolved = search.predict(lambda genome: predictions(genome, x_test), size=size)
140 # Draw an equally sized quality-only ensemble from distinct measured genomes.
141 unique = {genome: loss for loss, genome in measured}
142 best = sorted(unique, key=unique.get)[:size]
143 quality_only = np.mean([predictions(genome, x_test) for genome in best], axis=0)
144 return {
145 "evaluations": search.stats.evaluations,
146 "archive_size": len(search.archive),
147 "ensemble_size": size,
148 "cosine_test_mse": float(np.square(target(x_test) - evolved).mean()),
149 "quality_only_test_mse": float(np.square(target(x_test) - quality_only).mean()),
150 }
151
152
153def transfer(seed):
154 def simulate(genome, rollout_seed):
155 x, y = genome
156 quality = .8 + .2 * x - .25 * y ** 2
157 return quality, (x, y)
158
159 def target(genome, rollout_seed):
160 x, y = genome
161 return (x, y - .44 * (x + 1.) / 2.)
162
163 result = {}
164 for name, training_calls in (("calibrated", 6), ("simulation_only", 0)):
165 search = TBREvolution(sample=real_sample, mutate=real_mutation, population_size=12, neighbors=4,
166 novelty_threshold=.24, transfer_threshold=.26, transfer_period=2, seed=seed)
167 search.run(simulate, 192, evaluate_target=target, target_budget=training_calls)
168 # Apply the same seeded selection rule and count audit calls separately.
169 audit_rng = np.random.default_rng(731)
170 indices = audit_rng.choice(len(search.archive), min(8, len(search.archive)), replace=False)
171 entries = [search.archive[i] for i in indices]
172 measurements = [target(row.genome, 0) for row in entries]
173 errors = [np.linalg.norm(np.asarray(row.descriptor) - actual)
174 for row, actual in zip(entries, measurements)]
175 coordinates = (np.asarray(measurements) - (-1., -1.44)) / (2., 2.44)
176 occupied = {tuple(cell) for cell in np.clip((5 * coordinates).astype(int), 0, 4)}
177 result[name] = {
178 "simulator_calls": search.stats.simulation_evaluations,
179 "target_training_calls": search.stats.target_evaluations,
180 "target_audit_calls": len(errors),
181 "transferable_fraction": float(np.mean(np.asarray(errors) <= .26)),
182 "mean_target_error": float(np.mean(errors)),
183 "target_cells": len(occupied),
184 }
185 return result
186
187
188CASES = {
189 "voting": voting,
190 "structural": structural,
191 "clusters": clusters,
192 "ensemble": ensemble,
193 "transfer": transfer,
194}
195
196
197def main():
198 parser = argparse.ArgumentParser(description=__doc__)
199 parser.add_argument("--case", choices=("all", *CASES), default="all")
200 parser.add_argument("--seed", type=int, default=42)
201 args = parser.parse_args()
202 selected = CASES if args.case == "all" else {args.case: CASES[args.case]}
203 report = {name: run(args.seed) for name, run in selected.items()}
204 print(json.dumps({"seed": args.seed, **report}, indent=2, allow_nan=False))
205
206
207if __name__ == "__main__":
208 main()
Preserve solutions to task combinations via local nondominated survival.
Definition cmoea.py:57
Fit cosine-kernel PCA over symmetric prediction references and retain one elite per cell.
Rank by quality and average diversity, then crowd by dissimilarity.
Optimize multiple centers with local rewards and shared population volumes.
Definition dvd_es.py:80
Cluster live descriptors and independently update each representative with ES.
Definition edo_cs.py:48
Breed one child per slot and compare it against all slots by strict majority.
Definition move.py:44
Breed by novelty, local quality, and local predicted transferability.