43 unique, inverse = np.unique(points, axis=0, return_inverse=
True)
69 """Run mirrored ES with centered Pareto ranks and an Adam ascent step.
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.
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.
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)
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)
96 raise ValueError(
"x0 must be inside ind_domain.")
97 self.
_pairs = _positive_int(pairs,
"pairs")
101 self.
_noise, self.
_seeds = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
110 """Return a copy of the center, which can be used with a new evaluator."""
116 """Return cumulative search statistics."""
119 def _bounded(self, points):
120 return points
if self.
_domain is None else np.clip(points, *self.
_domain)
122 def _measure(self, evaluate, points, rng, *, training):
123 fitness, descriptors = [], []
126 if not np.isfinite(point).all():
127 raise ValueError(
"ES generated nonfinite parameters. Reduce sigma or learning_rate.")
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.")
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))
149 def run(self, evaluate, budget):
150 """Use up to budget calls. Any remainder smaller than 2*pairs stays unspent."""
151 budget = index(budget)
153 raise ValueError(
"budget must be nonnegative.")
154 for _
in range(budget // (2 * self.
_pairs)):
157 sample = self.
_measure(evaluate, points, self.
_seeds, training=
True)
158 quality = self.
_direction * np.asarray(sample.fitness)
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
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)
171 if not (np.isfinite(center).all()
and np.isfinite(variance).all()):
172 raise ValueError(
"ES update overflowed. Reduce the gradient scale.")
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))
187 return self.
_measure(evaluate, points, seeds, training=
False)