QDpy
Loading...
Searching...
No Matches
mo_cma_mae.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Covariance search with separate search thresholds and reporting fronts."""
6
7from math import isfinite
8import random
9
10import numpy as np
11
12from qdpy.base import registry
13from qdpy.containers import ParetoGrid
14from .modern import _CMAEmitter, _bounds, _positive_int
15
16__all__ = ["MOCMAMAE"]
17
18
19def _gain(point, front):
20 """Integrate the uncovered part of a rectangle over the threshold staircase."""
21 width, height = point
22 gain = previous = 0.
23 for x, y in front:
24 edge = min(width, x)
25 gain += (edge - previous) * max(height - y, 0.)
26 previous = edge
27 if edge == width:
28 return gain
29 return gain + (width - previous) * height
30
31
32def _insert(point, front):
33 if any(x >= point[0] and y >= point[1] for x, y in front):
34 return front
35 return tuple(sorted([point, *((x, y) for x, y in front if x > point[0] or y > point[1])]))
36
37
38def _discount(point, front, gain, rate):
39 target = gain * rate
40 if target == 0.:
41 return (0., 0.)
42 low, high = 0., 1.
43 for _ in range(48):
44 middle = (low + high) / 2
45 scaled = (point[0] * middle, point[1] * middle)
46 if _gain(scaled, front) < target:
47 low = middle
48 else:
49 high = middle
50 return point[0] * high, point[1] * high
51
52
53
54@registry.register
56 """Two-objective MO-CMA-MAE with a dynamic threshold archive.
57
58 Each candidate is scored against its cell's current threshold front, in
59 proposal order. The learning rate determines how much hypervolume of
60 an improvement is inserted into the threshold front. The reporting
61 ParetoGrid stores original, nondominated measurements.
62
63 :param container: Two-objective ParetoGrid with declared objective directions.
64 :param budget: Number of attempted candidate evaluations.
65 :param x0: Initial genome centre, with at least two coordinates.
66 :param sigma0: Initial CMA step size.
67 :param batch_size: Population size, at least two.
68 :param reference: Hypervolume reference in raw objective units. Candidate
69 objectives must be at least as good as the reference in both coordinates.
70 :param learning_rate: Fraction of the hypervolume improvement applied to the
71 threshold front, in [0, 1]. Zero freezes thresholds and one applies full gain.
72 :param ind_domain: Optional shared genome bounds.
73 :param seed: Optional private random seed for CMA and restarts.
74 """
75
76 def __init__(self, container, budget, x0, sigma0, batch_size, reference, *,
77 learning_rate=.1, ind_domain=None, seed=None, **kwargs):
78 try:
79 import cma
80 except ImportError as error:
81 raise ImportError("MOCMAMAE requires the QDpy 'cma' extra.") from error
82 if not isinstance(container, ParetoGrid) or len(container.fitness_domain) != 2:
83 raise ValueError("MOCMAMAE requires a two-objective ParetoGrid.")
84 self.x0 = np.asarray(x0, dtype=float).copy()
85 if self.x0.ndim != 1 or self.x0.size < 2 or not np.isfinite(self.x0).all():
86 raise ValueError("x0 must be a finite vector with at least two coordinates.")
87 if not (0 < sigma0 < np.inf and 0 <= learning_rate <= 1):
88 raise ValueError("Use a positive finite sigma0 and learning_rate in [0, 1].")
89 batch_size = _positive_int(batch_size, "batch_size")
90 if batch_size < 2:
91 raise ValueError("MOCMAMAE needs at least two candidates per population.")
92 reference = np.asarray(reference, dtype=float)
93 if reference.shape != (2,) or not np.isfinite(reference).all():
94 raise ValueError("Use a finite two-objective reference point.")
95 self.reference = tuple(reference)
96 self.ind_domain = None if ind_domain is None else _bounds(ind_domain)
97 if self.ind_domain is not None and not np.all(np.clip(self.x0, *self.ind_domain) == self.x0):
98 raise ValueError("x0 lies outside the genome bounds.")
99 self.sigma0, self.learning_rate, self.seed = sigma0, learning_rate, seed
100 kwargs.setdefault("optimisation_task", container.fitness_weights)
101 super().__init__(container, _positive_int(budget, "budget"), batch_size=batch_size,
102 dimension=len(self.x0), **kwargs)
103 for individual in container:
104 self._point(individual)
105
106 def reinit(self):
107 """Reset the emitter and threshold fronts while retaining reported elites."""
108 super().reinit()
109 self._threshold_fronts = {}
110 self._strategy = None
111 self._vectors = ()
112 self._gains = ()
113 self._rng = random.Random(self.seed) if self.seed is not None else None
114
115
116 def threshold_front(self, cell):
117 """Return the threshold points in the original objective units."""
118 direction = tuple(np.sign(self._fitness_weights))
119 return tuple(tuple(ref + sign * value for ref, sign, value in zip(self.reference, direction, point))
120 for point in self._threshold_fronts.get(cell, ()))
121
122 def _restart_center(self):
123 if not len(self.container):
124 return self.x0
125 center = self._search_rng().choice(self.container)
126 return center if self.ind_domain is None else np.clip(center, *self.ind_domain)
127
128 def _point(self, individual):
129 values = self.container.get_ind_fitness(individual).values
130 point = tuple(float(np.sign(weight)) * (float(value) - ref)
131 for value, ref, weight in zip(values, self.reference, self._fitness_weights))
132 if len(point) != 2 or min(point) < 0 or not isfinite(point[0] * point[1]):
133 raise ValueError("Both objectives must dominate the reference and give finite hypervolume.")
134 return point
135
136 def _check_candidate(self, individual):
137 super()._check_candidate(individual)
138 self._point(individual)
139
140 def _commit_generation(self, evaluated):
141 self._gains = np.full(len(evaluated), -np.inf)
142 new = {}
143 for slot, individual in enumerate(evaluated):
144 if individual is None:
145 continue
146 cell = self.container.index_grid(individual)
147 point = self._point(individual)
148 front = self._threshold_fronts.get(cell, ())
149 gain = self._gains[slot] = _gain(point, front)
150 if gain > 0:
151 new[id(individual)] = slot
152 if self.learning_rate == 1:
153 self._threshold_fronts[cell] = _insert(point, front)
154 elif self.learning_rate > 0:
155 discounted = _discount(point, front, gain, self.learning_rate)
156 if discounted != (0., 0.):
157 self._threshold_fronts[cell] = _insert(discounted, front)
158 admitted = self.container._merge_fronts((evaluated[slot] for slot in new.values()),
159 truncation_rng=self._search_rng())
160 if len(evaluated) == self.batch_size and np.isfinite(self._gains).any():
161 self._adapt_strategy(self._vectors)
162 return {new[key] for key in admitted}
Rank CMA candidates by their improvement over annealed Pareto thresholds.
Definition mo_cma_mae.py:55
threshold_front(self, cell)
Read the annealed objective front in raw objective coordinates.