5"""Small seeded comparisons with separate search work and reference measurements."""
8from itertools
import permutations, product
10from pathlib
import Path
11from statistics
import median
12from time
import perf_counter, perf_counter_ns
17 LUCIEMAPElites, NoveltyBinaryPSO, TravelingThiefItem, TravelingThiefMAPElites, TravelingThiefProblem,
24def _offer(archive, genome, fitness, features):
25 archive.add(Individual(genome, fitness=Fitness((fitness,), weights=(1.,)), features=Features(features)))
29 for cell, front
in archive.solutions.items():
34def _regret_metrics(archive, exact):
35 gaps = [max(0., exact[cell] - elite.fitness.values[0])
for cell, elite
in _elites(archive)]
36 return dict(occupied=len(archive), reachable_cells=len(exact),
37 exact_cells=sum(gap < 1e-10
for gap
in gaps),
38 mean_occupied_regret=sum(gaps) / len(gaps)
if gaps
else None)
41def swarm_trials(budget, seed):
42 """Find sensor subsets that cover a target panel at different deployment counts."""
43 sensors = np.array([[-.85, -.72], [-.75, -.16], [-.55, .68], [-.26, .17], [-.15, -.91],
44 [.15, .73], [.35, -.56], [.38, .14], [.69, .65], [.72, -.16]])
45 side = np.linspace(-.95, .95, 13)
46 targets = np.array(list(product(side, repeat=2)))
47 visible = np.linalg.norm(sensors[:,
None] - targets[
None], axis=-1) <= .58
50 return Grid(shape=(6, 6), fitness_domain=((0., len(targets)),), features_domain=((0., 5.), (0., 5.)))
53 coverage = np.any(visible[np.asarray(bits, dtype=bool)], axis=0)
54 return float(coverage.sum()), (sum(bits[:5]), sum(bits[5:]))
58 for bits
in product((0, 1), repeat=len(sensors)):
59 quality, descriptor = evaluate(bits)
60 cell = archive.index_grid(descriptor)
61 exact[cell] = max(exact.get(cell, 0.), quality)
62 pso = NoveltyBinaryPSO(archive, len(sensors), population_size=12, memory_size=48, seed=seed)
63 stats = pso.optimise(evaluate, budget)
64 yield dict(method=
"binary-novelty-pso", evaluations=stats.evaluations, **_regret_metrics(archive, exact))
67 rng = np.random.default_rng(seed)
68 width = min(12, budget)
69 initial = rng.integers(0, 2, size=(width, len(sensors)), dtype=np.int8)
70 for step
in range(budget):
74 bits = np.asarray(archive[int(rng.integers(len(archive)))], dtype=np.int8).copy()
75 mutation = rng.random(len(bits)) < 1. / len(bits)
76 if not mutation.any():
77 mutation[int(rng.integers(len(bits)))] =
True
79 genome = tuple(map(int, bits))
80 quality, descriptor = evaluate(genome)
81 _offer(archive, genome, quality, descriptor)
82 yield dict(method=
"bit-flip-map-elites", evaluations=budget, **_regret_metrics(archive, exact))
85def lucie_trials(budget, seed):
86 """Compare archive quality using the known mean of a bounded noisy task."""
88 return Grid(shape=8, fitness_domain=((0., 1.),), features_domain=((0., 1.),))
90 def descriptor(genome):
95 return .15 + .78 * (1. - abs(y - (.2 + .65 * x)))
97 def evaluate(genome, rollout_seed):
98 rng = np.random.default_rng(rollout_seed)
99 return float(rng.random() < mean(genome))
102 return dict(occupied=len(archive), estimated_qd_score=sum(elite.fitness.values[0]
for elite
in archive),
103 true_qd_score=sum(mean(elite)
for elite
in archive))
106 adaptive = LUCIEMAPElites(archive, 2, epsilon=.35, initial_samples=3, max_pairs=7,
107 iso_sigma=.10, line_sigma=.25, seed=seed)
108 stats = adaptive.run(evaluate, descriptor, budget)
109 yield dict(method=
"lucie-style", **vars(stats), **report(archive))
112 rng = np.random.default_rng(seed)
113 calls = proposals = 0
114 while calls < budget:
117 genome = tuple(rng.random(2))
119 first, second = rng.integers(len(archive), size=2)
120 genome = tuple(iso_line_dd(archive[int(first)], archive[int(second)],
121 iso_sigma=.10, line_sigma=.25, bounds=(0., 1.), rng=rng))
122 samples = min(4, budget - calls)
123 values = [evaluate(genome, np.random.SeedSequence([seed, 1, index]))
124 for index
in range(calls, calls + samples)]
126 _offer(archive, genome, sum(values) / samples, descriptor(genome))
127 yield dict(method=
"fixed-four-repeats", evaluations=calls, proposals=proposals, **report(archive))
130def thief_trials(budget, seed):
131 """Compare 2-opt with random anchored tours on the same exact packing oracle."""
132 points = np.array([[0., 0.], [1., 2.], [3., .5], [4., 3.], [5., -1.], [2., -2.]])
133 distances = np.linalg.norm(points[:,
None] - points[
None], axis=-1)
134 items = [TravelingThiefItem(*item)
for item
in
135 [(0, 1, 3.), (1, 2, 12.), (1, 1, 6.), (2, 3, 18.), (3, 1, 6.), (4, 3, 17.), (5, 2, 13.)]]
136 problem = TravelingThiefProblem(distances, items, capacity=6, min_speed=.25, rent=1.2)
139 return Grid(shape=(7, 7), features_domain=((12., 28.), (0., 49.)), fitness_domain=((-100., 75.),))
143 for tail
in permutations(range(1, len(points))):
144 solution, _ = problem.solve_packing((0, *tail))
145 cell = reference.index_grid((solution.tour_length, solution.profit))
146 exact[cell] = max(exact.get(cell, -np.inf), solution.fitness)
147 for name, initial
in [(
"thief-2opt", min(6, budget)), (
"thief-random-tours", budget)]:
149 search = TravelingThiefMAPElites(problem, archive, initial_tours=initial, seed=seed)
150 stats = search.run(budget)
151 yield dict(method=name, tour_evaluations=stats.tour_evaluations,
152 packing_transitions=stats.packing_transitions, best=float(archive.best.fitness.values[0]),
153 **_regret_metrics(archive, exact))
156def gene_trials(budget, seed, *, timing=False):
157 """Compare the geometric and dense genomes at equal environment steps."""
158 import gymnasium
as gym
161 from qdpy.rl import GENEMAPElites, NeuralMAPElites, PolicyConfig
163 torch.set_num_threads(1)
165 class Tracking(gym.Env):
166 observation_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
167 action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32)
169 def _observation(self):
170 return np.array([self.position, self.target], dtype=np.float32)
172 def reset(self, *, seed=None, options=None):
173 super().reset(seed=seed)
174 self.position, self.target, self.steps = 0., self.np_random.uniform(-.8, .8), 0
175 return self._observation(), {}
177 def step(self, action):
178 self.position = float(np.clip(self.position + .17 * float(action[0]), -1., 1.))
180 reward = 1. - abs(self.position - self.target) / 2.
181 return self._observation(), reward, self.steps == 12,
False, {}
183 for name, cls, options
in [(
"gene-map-elites", GENEMAPElites, dict(coordinate_size=2)),
184 (
"dense-neural-map-elites", NeuralMAPElites, {})]:
185 archive = Grid(shape=(7, 7), features_domain=((-1., 1.), (-1., 1.)), fitness_domain=((0., 12.),))
186 search = cls(Tracking, archive, descriptor=
lambda ep: (np.mean(ep.actions), ep.observations[-1, 0]),
187 policy=PolicyConfig((32, 32)), iso_sigma=.03, line_sigma=.20, seed=seed, **options)
188 before = perf_counter()
189 stats = search.train(budget)
190 duration = perf_counter() - before
192 row = dict(method=name, env_steps=stats.env_steps, complete_policies=stats.evaluated_policies,
193 occupied=len(archive), genome_values=len(elite)
if elite
is not None else None,
194 train_qd_score=sum(float(ind.fitness.values[0])
for ind
in archive),
195 best=float(elite.fitness.values[0])
if elite
is not None else None)
196 if timing
and elite
is not None:
197 values = np.asarray(elite, dtype=float)
198 transform = search.encoding.decode
if isinstance(search, GENEMAPElites)
else np.copy
201 start = perf_counter_ns()
203 times.append(perf_counter_ns() - start)
204 row.update(train_seconds=duration, prepare_parameters_us=median(times) / 1000)
210 """Use tiny, matched workloads with no simulator download."""
211 parser = argparse.ArgumentParser(description=__doc__)
212 parser.add_argument(
"tasks", nargs=
"*", metavar=
"TASK", help=
"Choose swarm, lucie, thief, or gene.")
213 parser.add_argument(
"--budget", type=int, help=
"Override the task-specific search budget.")
214 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 23, 47])
215 parser.add_argument(
"--timing", action=
"store_true", help=
"Include elapsed times for the GENE comparison.")
216 parser.add_argument(
"--output", type=Path)
217 args = parser.parse_args()
218 trials = dict(swarm=swarm_trials, lucie=lucie_trials, thief=thief_trials, gene=gene_trials)
219 budgets = dict(swarm=360, lucie=512, thief=40, gene=720)
220 if args.budget
is not None and args.budget < 1:
221 parser.error(
"--budget must be positive")
223 for task
in args.tasks
or (
"swarm",
"lucie",
"thief"):
224 if task
not in trials:
225 parser.error(f
"unknown task {task}")
226 for seed
in args.seeds:
227 kwargs = dict(timing=args.timing)
if task ==
"gene" else {}
228 for row
in trials[task](args.budget
or budgets[task], seed, **kwargs):
229 line = json.dumps(dict(task=task, seed=seed, **row), sort_keys=
True, allow_nan=
False)
232 if args.output
is not None:
233 args.output.parent.mkdir(parents=
True, exist_ok=
True)
234 args.output.write_text(
"\n".join(lines) +
"\n", encoding=
"utf-8")
237if __name__ ==
"__main__":