QDpy
Loading...
Searching...
No Matches
evolvability_es.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Search for centers with high-quality, behaviourally diverse offspring."""
7
8from bisect import bisect_right
9from dataclasses import dataclass
10from itertools import groupby
11from operator import index
12
13import numpy as np
14from scipy.stats import rankdata
15
16from qdpy.containers.pareto import _crowding_distance
17from .me_es import _rank_gradient
18from .modern import _bounds, _positive_int
19
20__all__ = ["QualityEvolvabilityES", "EvolvabilityESStats", "OffspringSample"]
21
22
23def _pareto_utilities(fitness, spread):
24 # Descending lexicographic order is a dominance order. A longest
25 # nonincreasing chain in the second objective gives each front depth.
26 order = np.lexsort((-spread, -fitness))
27 tails = []
28 fronts = []
29 for (_, second), group in groupby(order, key=lambda i: (fitness[i], spread[i])):
30 slots = list(group)
31 depth = bisect_right(tails, -second)
32 if depth == len(tails):
33 tails.append(-second)
34 fronts.append([])
35 else:
36 tails[depth] = -second
37 fronts[depth].extend(slots)
38
39 utilities = np.empty(len(fitness))
40 remaining = len(fitness)
41 for front in fronts:
42 points = np.column_stack((fitness[front], spread[front]))
43 unique, inverse = np.unique(points, axis=0, return_inverse=True)
44 remaining -= len(front)
45 utilities[front] = rankdata(_crowding_distance(unique)[inverse], method="average") + remaining
46 return utilities
47
48
49
50@dataclass(frozen=True)
52 """Count training evaluator calls, including attempts that raise."""
53
54 evaluations: int
55 updates: int
56
57
58
59@dataclass(frozen=True)
61 """Keep quality scores and corresponding descriptors in sampling order."""
62
63 fitness: tuple[float, ...]
64 descriptors: tuple[tuple[float, ...], ...]
65
66
67
69 """Run mirrored ES with centered Pareto ranks and an Adam ascent step.
70
71 Evolvability is squared descriptor distance from the current offspring
72 mean. Normalize descriptor axes in the evaluator if their units differ.
73 Search optimizes the mutation distribution with one fixed sigma. It
74 maintains a single center and evaluates offspring around it.
75
76 :param x0: Finite initial parameter vector.
77 :param pairs: Number of mirrored perturbation pairs per ES update.
78 :param sigma: Gaussian standard deviation for mutation.
79 :param learning_rate: Adam ascent step size.
80 :param l2: Nonnegative L2 coefficient applied to the gradient.
81 :param maximize: Maximize fitness if true, minimize otherwise.
82 :param quality_only: Run the matched fitness-only ES control if true.
83 :param ind_domain: Optional common inclusive parameter bounds.
84 :param seed: Private seed for mirrored noise and evaluator seeds.
85 """
86
87 def __init__(self, x0, *, pairs=16, sigma=.1, learning_rate=.03, l2=.005,
88 maximize=True, quality_only=False, ind_domain=None, seed=0):
89 self._center = np.array(x0, dtype=float, copy=True)
90 if self._center.ndim != 1 or not len(self._center) or not np.isfinite(self._center).all():
91 raise ValueError("x0 must be a nonempty finite parameter vector.")
92 if not (0 < sigma < np.inf and 0 < learning_rate < np.inf and 0 <= l2 < np.inf):
93 raise ValueError("Use a finite positive sigma and learning rate, and finite nonnegative l2.")
94 self._domain = None if ind_domain is None else _bounds(ind_domain)
95 if self._domain is not None and np.any(self._center != self._bounded(self._center)):
96 raise ValueError("x0 must be inside ind_domain.")
97 self._pairs = _positive_int(pairs, "pairs")
98 self._sigma, self._rate, self._l2 = sigma, learning_rate, l2
99 self._direction = 1. if maximize else -1.
100 self._quality_only = quality_only
101 self._noise, self._seeds = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
102 self._moment = np.zeros_like(self._center)
103 self._variance = np.zeros_like(self._center)
104 self._calls = self._updates = 0
105 self._descriptor_size = None
106
107
108 @property
109 def center(self):
110 """Return a copy of the center, which can be used with a new evaluator."""
111 return self._center.copy()
112
113
114 @property
115 def stats(self):
116 """Return cumulative search statistics."""
117 return EvolvabilityESStats(self._calls, self._updates)
118
119 def _bounded(self, points):
120 return points if self._domain is None else np.clip(points, *self._domain)
121
122 def _measure(self, evaluate, points, rng, *, training):
123 fitness, descriptors = [], []
124 width = self._descriptor_size
125 for point in points:
126 if not np.isfinite(point).all():
127 raise ValueError("ES generated nonfinite parameters. Reduce sigma or learning_rate.")
128 if training:
129 self._calls += 1
130 reward, descriptor = evaluate(tuple(point), int(rng.integers(2**32)))
131 reward, descriptor = float(reward), np.asarray(descriptor, dtype=float)
132 if (not np.isfinite(reward) or descriptor.ndim != 1 or not len(descriptor)
133 or not np.isfinite(descriptor).all()):
134 raise ValueError("Return finite fitness and a nonempty finite descriptor vector.")
135 if width is None:
136 width = len(descriptor)
137 elif len(descriptor) != width:
138 raise ValueError("Descriptor dimensions must remain fixed.")
139 fitness.append(reward)
140 descriptors.append(tuple(descriptor))
141 if training:
142 self._descriptor_size = width
143 return OffspringSample(tuple(fitness), tuple(descriptors))
144
145
149 def run(self, evaluate, budget):
150 """Use up to budget calls. Any remainder smaller than 2*pairs stays unspent."""
151 budget = index(budget)
152 if budget < 0:
153 raise ValueError("budget must be nonnegative.")
154 for _ in range(budget // (2 * self._pairs)):
155 noise = self._noise.normal(size=(self._pairs, len(self._center)))
156 points = self._bounded(self._center + self._sigma * np.concatenate((noise, -noise)))
157 sample = self._measure(evaluate, points, self._seeds, training=True)
158 quality = self._direction * np.asarray(sample.fitness)
159 scores = quality
160 if not self._quality_only:
161 features = np.asarray(sample.descriptors)
162 features /= np.abs(features).max() or 1.
163 spread = np.square(features - features.mean(axis=0)).sum(axis=1)
164 scores = _pareto_utilities(quality, spread)
165 gradient = _rank_gradient(noise, scores, self._sigma) - self._l2 * self._center
166 step = self._updates + 1
167 moment = .9 * self._moment + .1 * gradient
168 variance = .999 * self._variance + .001 * np.square(gradient)
169 move = self._rate * (moment / (1. - .9**step)) / (np.sqrt(variance / (1. - .999**step)) + 1e-8)
170 center = self._bounded(self._center + move)
171 if not (np.isfinite(center).all() and np.isfinite(variance).all()):
172 raise ValueError("ES update overflowed. Reduce the gradient scale.")
173 self._center, self._moment, self._variance = center, moment, variance
174 self._updates = step
175 return self.stats
176
177
182 def sample_offspring(self, evaluate, count, *, seed):
183 """Measure an independent sample around the current center using the training sigma."""
184 count = _positive_int(count, "count")
185 noise, seeds = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
186 points = self._bounded(self._center + self._sigma * noise.normal(size=(count, len(self._center))))
187 return self._measure(evaluate, points, seeds, training=False)
Cumulative search attempts and committed ES updates.
Independent offspring measurements around a fixed center.
Optimize one center by Pareto-ranking quality and descriptor displacement.
sample_offspring(self, evaluate, count, *, seed)
Measure fresh, independently drawn offspring without changing the search streams.
_measure(self, evaluate, points, rng, *, training)
stats(self)
Return the training evaluator and ES update counts.
center(self)
Return a copy of the current parameters.
run(self, evaluate, budget)
Use an additional budget of offspring evaluations, in complete mirrored batches.