QDpy
Loading...
Searching...
No Matches
squad.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Compare SQUAD, quality-only Adam, and optional CMA-MAEGA."""
6
7from argparse import ArgumentParser
8import json
9from time import perf_counter
10
11import numpy as np
12
13from qdpy.algorithms import CMAMAEGA, GradientEvaluation, soft_qd_score, squad_search
14from qdpy.containers import CVTGrid
15from qdpy.simple import run
16
17
18def comparison(budget, seed, descriptor_size, with_cma):
19 """Evaluate methods on a shared analytic task and reporting geometry."""
20 population_size, dimension = 16, 12
21 if budget < population_size or budget % population_size:
22 raise ValueError("Choose a budget that is a positive multiple of 16.")
23 rng = np.random.default_rng(seed)
24 start_population = rng.uniform(0, 1, (population_size, dimension))
25 geometry = np.random.default_rng(917)
26 centers = geometry.uniform(0.1, 0.9, (population_size, descriptor_size))
27 probes = geometry.uniform(0, 1, (512, descriptor_size))
28 target = np.linspace(0.25, 0.75, dimension)
29 domain = ((0., 1.),) * descriptor_size
30
31 def evaluate(genome):
32 return (float(1. - np.mean((genome - target) ** 2)),), tuple(genome[:descriptor_size])
33
34 def differentiated(genome):
35 genome = np.asarray(genome)
36 (quality,), features = evaluate(genome)
37 jacobian = np.vstack((-2. * (genome - target) / dimension, np.eye(dimension)[:descriptor_size]))
38 return GradientEvaluation(quality, features, jacobian)
39
40 def reporting_grid():
41 return CVTGrid(shape=population_size, centroids=centers, nb_sampled_points=0,
42 fitness_domain=((0., 1.),), features_domain=domain, fitness_weights=(1.,))
43
44 def row(method, archive, population, attempts, started):
45 seconds = perf_counter() - started
46 return dict(method=method, seed=seed, descriptors=descriptor_size, attempts=attempts,
47 seconds=seconds, coverage=len(archive) / population_size,
48 qd_score=archive.qd_score(normalized=False),
49 best=max(g.fitness.values[0] for g in population),
50 soft_score=soft_qd_score([g.fitness.values[0] for g in population],
51 [tuple(g.features) for g in population], probes, sigma=.13))
52
53 for name, neighbors in (("squad", None), ("adam-quality", 0)):
54 start = perf_counter()
55 result = squad_search(differentiated, start_population, epochs=budget // population_size - 1,
56 gamma=.37, quality_floor=0., neighbors=neighbors, archive=reporting_grid(),
57 learning_rate=.03, seed=seed)
58 yield row(name, result.archive, result.population, result.evaluations, start)
59 if with_cma:
60 search = CMAMAEGA(reporting_grid(), budget=budget, x0=start_population[0], sigma0=.35,
61 batch_size=15, threshold_min=0., ind_domain=(0., 1.), seed=seed,
62 gradient_evaluate=differentiated, optimisation_task="maximisation")
63 start = perf_counter()
64 result = run(search, lambda genome: evaluate(np.asarray(genome)), seed=seed)
65 yield row("cma-maega", result.archive, result.archive, result.evaluations, start)
66
67
68if __name__ == "__main__":
69 parser = ArgumentParser(description=__doc__)
70 parser.add_argument("--budget", type=int, default=512)
71 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 29, 47])
72 parser.add_argument("--descriptor-sizes", nargs="+", type=int, default=[2, 8], choices=range(1, 13))
73 parser.add_argument("--cma", action="store_true", help="Also run CMA-MAEGA using qdpy[cma].")
74 args = parser.parse_args()
75 for size in args.descriptor_sizes:
76 for seed in args.seeds:
77 for record in comparison(args.budget, seed, size, args.cma):
78 print(json.dumps(record, allow_nan=False, sort_keys=True))