QDpy
Loading...
Searching...
No Matches
mboa.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5import argparse
6import json
7from time import perf_counter
8
9import numpy as np
10
11from qdpy.algorithms import MBOA
12from qdpy.containers import Grid
13from qdpy.phenotype import Features, Fitness, Individual
14
15
16def benchmark(seed, budget):
17 """Compare trial selection using the same repertoire and shifted objective."""
18 rng = np.random.default_rng(seed)
19 optimum = rng.uniform(.65, .78)
20 options = np.linspace(0, 1, 41)
21
22 def evaluate(genome):
23 return float(1 - 3 * (genome[0] - optimum) ** 2)
24
25 archive = Grid(shape=41, fitness_domain=((-3, 1),), features_domain=((0, 1),), fitness_weights=(1.,))
26 for value in options:
27 nominal = 1 - 3 * (value - .22) ** 2
28 archive.add(Individual([value], fitness=Fitness((nominal,)), features=Features((value,))))
29 search = MBOA(archive, budget, length_scale=.45, kappa=.35)
30 count = min(budget, len(search.candidates))
31 oracle = max(evaluate(candidate.genome) for candidate in search.candidates)
32
33 def report(method, values, elapsed):
34 return dict(seed=seed, method=method, trials=len(values), regret=oracle - max(values),
35 target_trials=next((i for i, score in enumerate(values, 1) if score >= .99), None),
36 seconds=elapsed)
37
38 start = perf_counter()
39 search.run(evaluate)
40 yield report("mboa", [trial.fitness for trial in search.trials], perf_counter() - start)
41 for method in ("nominal-ranking", "random"):
42 start = perf_counter()
43 if method == "nominal-ranking":
44 candidates = sorted(search.candidates, key=lambda row: row.prior_fitness, reverse=True)[:count]
45 else:
46 candidates = [search.candidates[i] for i in rng.choice(len(search.candidates), count, replace=False)]
47 values = [evaluate(row.genome) for row in candidates]
48 yield report(method, values, perf_counter() - start)
49
50
51if __name__ == "__main__":
52 parser = argparse.ArgumentParser(description=__doc__)
53 parser.add_argument("--budget", type=int, default=8)
54 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
55 args = parser.parse_args()
56 for seed in args.seeds:
57 for result in benchmark(seed, args.budget):
58 print(json.dumps(result, sort_keys=True))