QDpy
Loading...
Searching...
No Matches
cma_maega.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run a differentiable search with one gradient call per centre."""
6
7import numpy as np
8
9from qdpy.algorithms import CMAMAEGA, GradientEvaluation
10from qdpy.containers import Grid
11from qdpy.simple import run
12
13
14def evaluate(candidate):
15 """Return the raw sphere objective and the second coordinate as the descriptor."""
16 return (sum(x ** 2 for x in candidate),), (candidate[1],)
17
18
19def evaluate_gradient(candidate):
20 """Return the measurements and one derivative row per value."""
21 fitness, features = evaluate(candidate)
22 x, y = candidate
23 jacobian = np.array([[2 * x, 2 * y], [0.0, 1.0]])
24 return GradientEvaluation(fitness[0], features, jacobian)
25
26
27if __name__ == "__main__":
28 unit = (0.0, 1.0)
29 archive = Grid(shape=4, fitness_domain=((0, 2),), features_domain=(unit,))
30 search = CMAMAEGA(
31 archive, budget=24, x0=[0.5, 0.5], sigma0=0.1, batch_size=4,
32 threshold_min=-2, gradient_evaluate=evaluate_gradient, ind_domain=unit,
33 )
34 result = run(search, evaluate, seed=42)
35 print(f"Evaluations: {result.evaluations}")
36 print(f"Centre evaluations: {search.gradient_evaluations}")
37 print(f"Offspring evaluations: {result.evaluations - search.gradient_evaluations}")
38 print(f"Occupied cells: {archive.filled_bins}/{len(archive.solutions)}")
39 print(f"Best raw fitness: {result.best.fitness.values[0]:.6g}")