# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Use analytic gradients in CMA-MAEGA. """Run a differentiable search with one gradient call per centre.""" import numpy as np from qdpy.algorithms import CMAMAEGA, GradientEvaluation from qdpy.containers import Grid from qdpy.simple import run def evaluate(candidate): """Return the raw sphere objective and the second coordinate as the descriptor.""" return (sum(x ** 2 for x in candidate),), (candidate[1],) def evaluate_gradient(candidate): """Return the measurements and one derivative row per value.""" fitness, features = evaluate(candidate) x, y = candidate jacobian = np.array([[2 * x, 2 * y], [0.0, 1.0]]) return GradientEvaluation(fitness[0], features, jacobian) if __name__ == "__main__": unit = (0.0, 1.0) archive = Grid(shape=4, fitness_domain=((0, 2),), features_domain=(unit,)) search = CMAMAEGA( archive, budget=24, x0=[0.5, 0.5], sigma0=0.1, batch_size=4, threshold_min=-2, gradient_evaluate=evaluate_gradient, ind_domain=unit, ) result = run(search, evaluate, seed=42) print(f"Evaluations: {result.evaluations}") print(f"Centre evaluations: {search.gradient_evaluations}") print(f"Offspring evaluations: {result.evaluations - search.gradient_evaluations}") print(f"Occupied cells: {archive.filled_bins}/{len(archive.solutions)}") print(f"Best raw fitness: {result.best.fitness.values[0]:.6g}")