QDpy
Loading...
Searching...
No Matches
cpdea.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""CPDEA for finding distinct decision-space realizations of a Pareto front."""
7
8from dataclasses import dataclass
9from math import isfinite, pi, sqrt
10
11import numpy as np
12from scipy.spatial.distance import cdist
13
14from qdpy.tools import mut_polynomial_bounded
15
16from .modern import _positive_int
17from .parametric import _Coordinates, _sbx
18
19__all__ = ["CPDEA", "CPDEAPoint", "CPDEAResult"]
20
21
22
23@dataclass(frozen=True)
25 """Store a decision vector and its raw objective vector."""
26
27 genome: tuple[float, ...]
28 fitness: tuple[float, ...]
29
30
31
32@dataclass(frozen=True)
34 """The final nondominated archive and final population are independent views."""
35
36 archive: tuple[CPDEAPoint, ...]
37 population: tuple[CPDEAPoint, ...]
38 evaluations: int
39
40
41def _dominates(values):
42 """Return a matrix entry (i, j) if i dominates j in maximization units."""
43 return (np.all(values[:, None] >= values[None, :], axis=-1)
44 & np.any(values[:, None] > values[None, :], axis=-1))
45
46
47def _distance(points):
48 matrix = cdist(points, points)
49 if not np.isfinite(matrix).all():
50 raise ValueError("CPDEA requires finite pairwise distances. Rescale the problem coordinates.")
51 return matrix
52
53
54def _nearest(distances, neighbors):
55 """Take the closest other entries for each point, even with duplicate coordinates."""
56 matrix = distances.copy()
57 np.fill_diagonal(matrix, np.inf)
58 k = min(neighbors, len(matrix) - 1)
59 return np.partition(matrix, k, axis=1)[:, :k]
60
61
62
63def _cpd(distances, dominates, sigma, neighbors):
64 with np.errstate(over="ignore", under="ignore"):
65 weights = np.exp(-.5 * (distances / sigma) ** 2) / (sigma * sqrt(2 * pi))
66 convergence = np.sum(np.where(dominates.T, weights, 0.), axis=1)
67 adjusted = distances / (1. + .5 * convergence[:, None] + .5 * convergence[None, :])
68 return 1. / (1. + _nearest(adjusted, neighbors).sum(axis=1))
69
70
71
72def _dkn(genomes, objectives, neighbors):
73 total = np.zeros(len(genomes))
74 for coordinates in (genomes, objectives):
75 closest = _nearest(_distance(coordinates), neighbors)
76 if closest.size and (scale := closest.max()) > 0.:
77 normalized = closest / scale
78 total += normalized.sum(axis=1) / normalized.mean()
79 return 1. / (1. + total)
80
81
82
83class CPDEA:
84 """Run the steady-state algorithm of Liu et al. on bounded real decisions.
85
86 Penalize decision distances by the local presence of objective-space
87 dominators. Update a separate nondominated archive using both decision
88 and objective distances. Use population tournaments in the first half
89 of the budget, then also mate sparse archive elites with nearby designs.
90
91 :param genome_bounds: Finite increasing (lower, upper) intervals, one per variable.
92 :param fitness_weights: At least two signs. Positive maximizes and negative minimizes.
93 :param population_size: Size of the breeding population and cap of the archive.
94 :param neighbors: Number of nearest other solutions used in either density.
95 :param eta: Scale of the local-convergence bandwidth in Eq. 17.
96 :param seed: Private seed for initialization, mating, and variation.
97 """
98
99 def __init__(self, genome_bounds, fitness_weights, *, population_size=60, neighbors=3, eta=2., seed=0):
100 self._coordinates = _Coordinates(genome_bounds)
101 self._direction = np.sign(np.asarray(fitness_weights, dtype=float))
102 if (self._direction.ndim != 1 or len(self._direction) < 2
103 or not np.isfinite(fitness_weights).all() or np.any(self._direction == 0)):
104 raise ValueError("Provide at least two finite, nonzero fitness weights.")
105 self.population_size = _positive_int(population_size, "population_size")
106 self.neighbors = _positive_int(neighbors, "neighbors")
107 if self.population_size < 2 or not 0 < eta < np.inf:
108 raise ValueError("Use a population of at least two and finite positive eta.")
109 self.seed = seed
110 dimension = len(self._coordinates.span)
111 self._sigma = np.exp(np.log(eta) + np.log(self._coordinates.span).mean()
112 - np.log(self.population_size + 1) / dimension)
113 if not isfinite(self._sigma * sqrt(2 * pi)) or not 0 < self._sigma or not isfinite(1. / self._sigma):
114 raise ValueError("Use bounds and eta that give a finite nonzero convergence bandwidth.")
115
116 def _measure(self, evaluate, normalized):
117 genome = self._coordinates.physical(normalized)
118 objectives = np.asarray(evaluate(genome), dtype=float)
119 if objectives.shape != self._direction.shape or not np.isfinite(objectives).all():
120 raise ValueError("Return one finite value per configured objective.")
121 return CPDEAPoint(genome, tuple(map(float, objectives)))
122
123 def _objectives(self, points):
124 return np.asarray([point.fitness for point in points]) * self._direction
125
126 def _archive_update(self, archive, candidate):
127 if candidate in archive:
128 return
129 pool = [*archive, candidate]
130 front = [point for point, dominated in zip(pool, _dominates(self._objectives(pool)).any(axis=0))
131 if not dominated]
132 if len(front) > self.population_size:
133 density = _dkn([point.genome for point in front], self._objectives(front), self.neighbors)
134 # Preserve older measurements on exact density ties.
135 front.pop(len(front) - 1 - np.argmax(density[::-1]))
136 archive[:] = front
137
138 def _mating(self, population, archive, rng, explore):
139 if explore:
140 distance = _distance([point.genome for point in population])
141 costs = _cpd(distance, _dominates(self._objectives(population)), self._sigma, self.neighbors)
142 tournaments = rng.integers(len(population), size=(2, 2))
143 return tuple(population[contest[np.argmin(costs[contest])]] for contest in tournaments)
144 density = _dkn([point.genome for point in archive], self._objectives(archive), self.neighbors)
145 first = archive[np.argmin(density)]
146 pool = tuple(point for point in dict.fromkeys([*population, *archive]) if point.genome != first.genome)
147 if not pool:
148 return first, first
149 distances = cdist([first.genome], [point.genome for point in pool])[0]
150 closest = np.argsort(distances, kind="stable")[:len(first.genome)]
151 return first, pool[rng.choice(closest)]
152
153
154 def optimise(self, evaluate, budget):
155 """Call evaluate(genome) for raw objectives and return a :class:`CPDEAResult`."""
156 if not callable(evaluate):
157 raise TypeError("evaluate must be callable.")
158 budget = _positive_int(budget, "budget")
159 if budget < self.population_size:
160 raise ValueError("The budget must cover the entire initial population.")
161 rng = np.random.default_rng(self.seed)
162 dimension = len(self._coordinates.span)
163 population = [self._measure(evaluate, point)
164 for point in rng.random((self.population_size, dimension))]
165 archive = []
166 for point in population:
167 self._archive_update(archive, point)
168 for used in range(self.population_size, budget):
169 first, second = self._mating(population, archive, rng, used < budget / 2 or rng.random() < .5)
170 parents = self._coordinates.normalize([first.genome, second.genome])
171 child = _sbx(*parents, rng, eta=20)
172 mut_polynomial_bounded(child, 20, 0., 1., 1. / dimension, rng=rng)
173 candidate = self._measure(evaluate, child)
174 population.append(candidate)
175 distance = _distance([point.genome for point in population])
176 costs = _cpd(distance, _dominates(self._objectives(population)), self._sigma, self.neighbors)
177 population.pop(len(population) - 1 - np.argmax(costs[::-1]))
178 self._archive_update(archive, candidate)
179 return CPDEAResult(tuple(archive), tuple(population), budget)
Measured decision vector and objective values in original units.
Definition cpdea.py:24
Bounded nondominated archive, final breeding population, and exact work.
Definition cpdea.py:33
Search without descriptors using a CPD population and a nondominated archive.
Definition cpdea.py:83
_measure(self, evaluate, normalized)
Definition cpdea.py:116
_archive_update(self, archive, candidate)
Definition cpdea.py:126
_mating(self, population, archive, rng, explore)
Definition cpdea.py:138
_objectives(self, points)
Definition cpdea.py:123
optimise(self, evaluate, budget)
Run CPDEA with exactly the specified number of evaluator calls.
Definition cpdea.py:154