QDpy
Loading...
Searching...
No Matches
adaptive_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5import argparse
6import json
7import random
8
9import numpy as np
10
11from qdpy.algorithms import (
12 BOPElitesHyperband, CuriosityMutPolyBounded, EnhancedPOET, IsoLineMAPElites,
13 MEES, MonteCarloElites, QDHyperband, RandomSearchMutPolyBounded,
14)
15from qdpy.containers import Grid, SlidingBoundariesGrid
16from qdpy.phenotype import Features, Fitness, Individual
17from qdpy.tools import mut_polynomial_bounded
18
19
20def grid(shape=(8, 8), *, grid_type=Grid, **kwargs):
21 """Return a normalized, best-only descriptor grid."""
22 return grid_type(shape=shape, features_domain=((0., 1.),) * len(shape),
23 fitness_domain=((0., 1.),), fitness_weights=(1.,), **kwargs)
24
25
26def metrics(archive):
27 """Measure coverage and the sum of the retained objectives."""
28 return dict(coverage=archive.filled_bins / np.prod(archive.shape),
29 qd_score=sum(ind.fitness.values[0] for ind in archive))
30
31
32def multifidelity(seed, budget):
33 """Compare niche promotion on informative and misleading cheap approximations."""
34 for proxy in ("informative", "misleading"):
35 def evaluate(x, fidelity):
36 optimum = .15 + .7 * x[0]
37 if fidelity != 16:
38 blend = min(1., (16 - fidelity) / 12)
39 shift = .1 * np.sin(8 * x[0]) if proxy == "informative" else (.93 - optimum)
40 optimum = np.clip(optimum + blend * shift, 0., 1.)
41 return float(1 - (x[1] - optimum) ** 2), (x[0],)
42
43 for label, algorithm, levels in (("full-fidelity-random", QDHyperband, (16,)),
44 ("qdhb", QDHyperband, (1, 4, 16)),
45 ("bop-elites-hb", BOPElitesHyperband, (1, 4, 16))):
46 archive = grid((12,))
47 options = dict(quality_floor=0, model_after=8, trees=16) if algorithm is BOPElitesHyperband else {}
48 search = algorithm(archive, 2, levels, eta=4, seed=seed, **options)
49 search.run(evaluate, budget)
50 yield dict(method=label, proxy=proxy, cost=search.spent,
51 full_trials=sum(row.fidelity == 16 for row in search.trials),
52 **metrics(archive))
53
54
55def parent_selection(seed, budget):
56 """Compare parent selectors with the same one-parent mutation operator."""
57 def evaluate(candidate):
58 vector = np.asarray(candidate)
59 fitness = 1 / (1 + sum(10 + (vector[2:] - .7)**2 - 10 * np.cos(9 * vector[2:])))
60 return (float(fitness),), tuple(vector[:2])
61
62 def mutate(parent, _):
63 return mut_polynomial_bounded(list(parent), eta=15, low=0., up=1., mut_pb=.5)
64
65 for label in ("uniform", "curiosity", "monte-carlo"):
66 random.seed(seed)
67 np.random.seed(seed)
68 archive = grid()
69 if label == "monte-carlo":
70 method = MonteCarloElites(archive, budget, 5, batch_size=1, mutate=mutate, seed=seed)
71 else:
72 algorithm = CuriosityMutPolyBounded if label == "curiosity" else RandomSearchMutPolyBounded
73 selection = {} if label == "curiosity" else {"sel_pb": 1.}
74 method = algorithm(archive, budget, 5, batch_size=1, init_pb=0., eta=15, mut_pb=.5,
75 optimisation_task="maximisation", **selection)
76 method.optimise(evaluate)
77 yield dict(method=label, evaluations=method.nb_evaluations, **metrics(archive))
78
79
80def sliding(seed, budget):
81 """Replay a skewed descriptor stream under fixed and rolling boundaries."""
82 points = np.random.default_rng(seed).uniform(size=(budget, 3))
83 for name, archive in (("uniform", grid()), ("sliding", grid(grid_type=SlidingBoundariesGrid,
84 remap_frequency=max(4, budget // 8), buffer_capacity=128))):
85 for i, (x, y, quality) in enumerate(points):
86 archive.add(Individual([i], fitness=Fitness((quality,)), features=Features((x**8, y**6))))
87 shared = grid()
88 shared.update(archive, ignore_exceptions=False)
89 yield dict(method=name, evaluations=budget, native_bins=archive.filled_bins,
90 remaps=getattr(archive, "remaps", 0), **metrics(shared))
91
92
93def evolution_strategies(seed, budget):
94 """Compare ME-ES with native Iso+LineDD on a separable design problem."""
95 target = np.random.default_rng(seed).uniform(.55, .85, size=22)
96
97 def evaluate(candidate):
98 w = np.asarray(candidate)
99 return (float(1 - np.mean((w[2:] - target)**2)),), tuple(w[:2])
100
101 for mode in ("isoline", "exploit", "explore-exploit"):
102 random.seed(seed)
103 np.random.seed(seed)
104 archive = grid()
105 if mode == "isoline":
106 search = IsoLineMAPElites(archive, budget, 24, batch_size=8, optimisation_task="maximisation",
107 iso_sigma=.12, line_sigma=.3)
108 search.optimise(evaluate)
109 used = search.nb_evaluations
110 centers = used
111 else:
112 search = MEES(archive, [.5] * 24, pairs=8, block_steps=4, mode=mode, sigma=.1,
113 ind_domain=(0., 1.), seed=seed)
114 search.run(evaluate, budget)
115 used, centers = search.evaluations, search.center_evaluations
116 yield dict(method=mode, evaluations=used, centers=centers,
117 best=archive.best.fitness.values[0], **metrics(archive))
118
119
120def poet(seed, budget):
121 """Compare task generation with and without cross-task transfer."""
122 def score(task, policy, _):
123 return float(1 - np.linalg.norm(np.asarray(task) / 4 - policy))
124
125 def mutate(task, rng):
126 change = rng.integers(2), rng.choice((-1, 1))
127 new = list(task)
128 new[change[0]] += int(change[1])
129 return tuple(new)
130
131 def improve(task, policy, evaluate, rng):
132 proposals = [policy] + [tuple(policy + noise) for noise in rng.normal(0, .09, (3, 2))]
133 return max(proposals, key=evaluate)
134
135 for label, transfer in (("enhanced-poet", 2), ("no-transfer", None)):
136 search = EnhancedPOET((0, 0), (0., 0.), mutate_task=mutate, improve=improve,
137 minimal_criterion=(.5, .92), reproduction_threshold=.91,
138 active_limit=4, proposals=5, new_tasks=1, mutate_every=2,
139 transfer_every=transfer, seed=seed)
140 stats = search.run(score, budget, rounds=budget)
141 pairs = (*search.active, *search.archived)
142 yield dict(method=label, evaluations=stats.evaluations, tasks=len(pairs),
143 solved=sum(row.score >= .91 for row in pairs), transfers=stats.transfers,
144 max_task_distance=max(float(np.linalg.norm(row.task)) for row in pairs))
145
146
147if __name__ == "__main__":
148 tasks = dict(multifidelity=(multifidelity, 816), parents=(parent_selection, 1024),
149 sliding=(sliding, 512), mees=(evolution_strategies, 1021), poet=(poet, 1800))
150 parser = argparse.ArgumentParser(description=__doc__)
151 parser.add_argument("task", choices=tasks)
152 parser.add_argument("--budget", type=int)
153 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
154 args = parser.parse_args()
155 execute, default = tasks[args.task]
156 for seed in args.seeds:
157 for result in execute(seed, default if args.budget is None else args.budget):
158 print(json.dumps(dict(task=args.task, seed=seed, **result), sort_keys=True))