QDpy
Loading...
Searching...
No Matches
descriptor_cma.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run small, matched-budget comparisons for four QDpy methods."""
6
7import argparse
8from importlib.metadata import PackageNotFoundError, version
9import json
10from pathlib import Path
11import platform
12
13import numpy as np
14
15from examples.dynamic_map_elites import audit_at, evaluate as shifted_sphere
16from qdpy import __version__
17from qdpy.algorithms import (CMAMAE, MEES, RandomSearchMutPolyBounded, cma_mega_es, dds_kde,
18 dynamic_cma_me, dynamic_map_elites, multi_bd_mes)
19from qdpy.benchmarks import illumination_rastrigin_normalised
20from qdpy.containers import Container, Grid, NoveltyArchive
21from qdpy.simple import run
22
23
24def grid(shape=(8, 8), weights=(-1.,)):
25 """Use the same reporting cells for competing methods."""
26 return Grid(shape=shape, features_domain=((0., 1.),) * len(shape), fitness_domain=((0., 1.),),
27 fitness_weights=weights, storage_type="orderedset")
28
29
30def navigate(genome):
31 """Follow four moves around a wall and report endpoint and path centroid."""
32 point = np.array([.15, .3])
33 path = [point]
34 for move in np.asarray(genome).reshape(-1, 2):
35 candidate = np.clip(point + .9 * (move - .5), 0., 1.)
36 if (point[0] < .5 <= candidate[0] or candidate[0] < .5 <= point[0]):
37 fraction = (.5 - point[0]) / (candidate[0] - point[0])
38 if point[1] + fraction * (candidate[1] - point[1]) < .58:
39 candidate[0] = point[0]
40 point = candidate
41 path.append(point)
42 distance = np.linalg.norm(point - [.88, .32])
43 return distance < .14, (float(1 - min(distance, 1.)),), {
44 "endpoint": tuple(point), "path": tuple(np.mean(path, axis=0)),
45 }
46
47
48def success_study(budget, seed):
49 """Compare success-prioritised search with one and two descriptor views."""
50 results = []
51 for names in (("endpoint",), ("endpoint", "path")):
52 archives = {name: grid(weights=(1.,)) for name in names}
53
54 def evaluate(genome):
55 success, fitness, descriptors = navigate(genome)
56 return success, fitness, {name: descriptors[name] for name in names}
57
58 result = multi_bd_mes(archives, evaluate, dimension=8, budget=budget, seed=seed)
59 results.append(dict(method="multi-bd-mes" if len(names) > 1 else "single-grid-mes",
60 attempts=result.attempts, successful_evaluations=result.successful_evaluations,
61 success_cells={name: sum(elite.scores["success"] for elite in archive)
62 for name, archive in archives.items()}))
63 archive = grid(weights=(1.,))
64 successful = 0
65
66 def evaluate_endpoint(genome):
67 nonlocal successful
68 success, fitness, descriptors = navigate(genome)
69 successful += int(success)
70 return fitness, descriptors["endpoint"], {"success": bool(success)}
71
72 search = RandomSearchMutPolyBounded(archive, budget=budget, dimension=8,
73 optimisation_task="maximisation")
74 run(search, evaluate_endpoint, seed=seed)
75 results.append(dict(method="map-elites", attempts=search.nb_evaluations,
76 successful_evaluations=successful,
77 success_cells={"endpoint": sum(elite.scores["success"] for elite in archive)}))
78 return results
79
80
81def dynamic_study(budget, seed):
82 """Measure archive freshness after objective and descriptor shifts."""
83 results = []
84 for name in ("dynamic-cma-me", "static-cma-me", "dynamic-map-elites"):
85 archive = grid()
86 if name == "dynamic-map-elites":
87 result = dynamic_map_elites(archive, shifted_sphere, dimension=4, budget=budget, seed=seed)
88 probes = 0
89 else:
90 result = dynamic_cma_me(archive, shifted_sphere, x0=[.5] * 4, budget=budget,
91 batch_size=12, seed=seed, refresh=name == "dynamic-cma-me")
92 probes = result.detection_attempts
93 freshness, audited = audit_at(archive, budget - 1)
94 results.append(dict(method=name, attempts=result.offspring_attempts + result.refresh_attempts + probes,
95 probes=probes, refreshes=result.refresh_attempts, audit_calls=audited.rollouts,
96 freshness=freshness, coverage=audited.corrected_coverage,
97 qd_score=audited.corrected_qd_score))
98 return results
99
100
101def diversity_measurement(genome):
102 """Use constant quality and two nonlinear descriptors to isolate coverage."""
103 first, second = .5 + .5 * np.sin(5 * np.asarray(genome[:2]) + np.asarray(genome[2:4]))
104 return (1.,), (first, second)
105
106
107def density_study(budget, seed):
108 """Compare DDS-KDE, novelty search and constant-quality CMA-MAE."""
109 results = []
110 for name in ("dds-kde", "novelty-search", "cma-mae"):
111 archive = grid(weights=(1.,))
112 if name == "dds-kde":
113 result = dds_kde(archive, diversity_measurement, x0=[.5] * 4, budget=budget,
114 bandwidth=.12, reservoir_size=96, batch_size=12, seed=seed)
115 attempts = result.attempts
116 elif name == "novelty-search":
117 history = Container(storage_type="orderedset")
118 novelty = NoveltyArchive(parents=[history], features_domain=archive.features_domain,
119 fitness_domain=archive.fitness_domain, threshold_novelty=.04)
120 search = RandomSearchMutPolyBounded(novelty, budget=budget, batch_size=12, dimension=4,
121 optimisation_task="maximisation")
122 run(search, diversity_measurement, seed=seed)
123 archive.update(history)
124 attempts = search.nb_evaluations
125 else:
126 search = CMAMAE(archive, budget, [.5] * 4, .15, 12, 0., ind_domain=(0., 1.),
127 optimisation_task="maximisation", seed=seed)
128 search.optimise(diversity_measurement)
129 attempts = search.nb_evaluations
130 results.append(dict(method=name, attempts=attempts, coverage=archive.filled_bins / 64))
131 return results
132
133
134def rastrigin(genome):
135 """Return an objective and descriptor pair for the black-box gradient study."""
136 fitness, descriptors, _ = illumination_rastrigin_normalised(genome, nb_features=2)
137 return fitness, tuple(descriptors)
138
139
140def gradient_study(budget, seed):
141 """Compare an ES arborescence against ME-ES and CMA-MAE."""
142 results = []
143 for name in ("cma-mega-es", "me-es", "cma-mae"):
144 archive = grid()
145 if name == "cma-mega-es":
146 result = cma_mega_es(archive, rastrigin, x0=[.5] * 4, budget=budget, batch_size=12,
147 es_sigma=.06, es_samples=8, seed=seed)
148 attempts = result.attempts
149 elif name == "me-es":
150 search = MEES(archive, [.5] * 4, pairs=4, sigma=.06, ind_domain=(0, 1), seed=seed)
151
152 def evaluate(genome):
153 fitness, descriptors = rastrigin(genome)
154 return fitness[0], descriptors
155
156 search.run(evaluate, budget)
157 attempts = search.evaluations
158 else:
159 search = CMAMAE(archive, budget, [.5] * 4, .15, 12, -1., ind_domain=(0., 1.), seed=seed)
160 search.optimise(rastrigin)
161 attempts = search.nb_evaluations
162 results.append(dict(method=name, attempts=attempts, coverage=archive.filled_bins / 64,
163 qd_score=archive.qd_score()))
164 return results
165
166
167def main():
168 """Run the selected studies at the same budget and save per-seed results."""
169 studies = dict(success=success_study, dynamic=dynamic_study, density=density_study, gradient=gradient_study)
170 parser = argparse.ArgumentParser(description=__doc__)
171 parser.add_argument("--studies", nargs="+", choices=tuple(studies), default=list(studies))
172 parser.add_argument("--budget", type=int, default=388)
173 parser.add_argument("--seeds", type=int, nargs="+", default=[7, 13, 23])
174 parser.add_argument("--output", type=Path)
175 args = parser.parse_args()
176 records = [dict(study=name, seed=seed, **row) for name in args.studies for seed in args.seeds
177 for row in studies[name](args.budget, seed)]
178 try:
179 cma = version("cma")
180 except PackageNotFoundError:
181 cma = None
182 data = json.dumps(dict(schema_version=1, qdpy=__version__, python=platform.python_version(),
183 numpy=np.__version__, cma=cma, budget=args.budget, trials=records),
184 indent=2, allow_nan=False)
185 if args.output is None:
186 print(data)
187 else:
188 args.output.parent.mkdir(parents=True, exist_ok=True)
189 args.output.write_text(data + "\n", encoding="utf-8")
190
191
192if __name__ == "__main__":
193 main()