QDpy
Loading...
Searching...
No Matches
novelty_swarm.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Explore binary designs with novelty-guided particle swarm optimization."""
7
8from collections import deque
9from dataclasses import dataclass
10from math import isfinite
11
12import numpy as np
13from scipy.special import expit
14
15from qdpy.containers import CVTGrid, Grid
16from qdpy.phenotype import Features, Fitness, Individual
17
18from .modern import _positive_int
19
20__all__ = ["NoveltyBinaryPSO", "BinarySwarmResult"]
21
22
23
24@dataclass(frozen=True)
26 """The archive retains measured fitness. The memory guides swarm novelty."""
27
28 archive: Grid
29 positions: tuple[tuple[int, ...], ...]
30 memory: tuple[tuple[int, ...], ...]
31 evaluations: int
32 archive_updates: int
33 out_of_domain: int
34
35
36def _hamming_novelty(points, memory, neighbors):
37 """Use the mean distance to the closest remembered binary designs."""
38 if not len(memory):
39 return np.zeros(len(points))
40 k = min(neighbors, len(memory))
41 return np.asarray([
42 np.partition(np.count_nonzero(memory != point, axis=1), k - 1)[:k].mean()
43 for point in points
44 ])
45
46
47
49 """Evaluate binary topologies and report their measured fitness and descriptors.
50
51 Recompute the novelty of current positions and personal leaders
52 against a common memory at each swarm iteration. The most novel
53 personal leader provides the social signal. A temperature schedule
54 controls the sigmoid used to sample bit values from their velocities.
55 The reporting archive receives real measurements and stays independent
56 of the novelty memory. Use deterministic measurements for a given bit vector.
57
58 :param archive: Empty parentless best-only scalar Grid or CVTGrid.
59 :param dimension: Number of bits.
60 :param population_size: Particle count, up to the available evaluation budget.
61 :param neighbors: Number of previous designs used for novelty.
62 :param memory_size: Maximum number of distinct recent designs.
63 :param inertia: Previous-velocity coefficient in the swarm update.
64 :param cognitive: Pull toward each particle's personal leader.
65 :param social: Pull toward the swarm's most novel leader.
66 :param velocity_limit: Absolute velocity cap.
67 :param temperature: Positive starting and ending sigmoid temperatures.
68 :param seed: Private seed for initial positions and velocity draws.
69 """
70
71 def __init__(self, archive, dimension, *, population_size=16, neighbors=5, memory_size=256,
72 inertia=.7, cognitive=1.4, social=1.4, velocity_limit=6.,
73 temperature=(5., 1.), seed=0):
74 if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
75 or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
76 or archive.fitness_domain is None or len(archive.fitness_domain) != 1
77 or archive.fitness_score_names or archive.features_score_names):
78 raise ValueError("Use an empty parentless scalar best-only Grid or CVTGrid.")
79 weights = archive.fitness_weights
80 if weights is not None and (len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0.):
81 raise ValueError("Use one finite, nonzero fitness weight.")
82 self._weights = (1.,) if weights is None else tuple(weights)
83 self.archive = archive
84 self.dimension = _positive_int(dimension, "dimension")
85 self.population_size = _positive_int(population_size, "population_size")
86 self.neighbors = _positive_int(neighbors, "neighbors")
87 self.memory_size = _positive_int(memory_size, "memory_size")
88 start, end = temperature
89 if (not all(0. <= value < np.inf for value in (inertia, cognitive, social))
90 or not 0. < velocity_limit < np.inf or not 0. < end <= start < np.inf):
91 raise ValueError("Use finite coefficients, a positive velocity limit and decreasing temperatures.")
92 self.inertia, self.cognitive, self.social = inertia, cognitive, social
93 self.velocity_limit, self.temperature, self.seed = velocity_limit, (start, end), seed
94
95
100 def optimise(self, evaluate, budget, *, repair=None):
101 """Measure evaluate(bits) returning (scalar fitness, descriptors).
102
103 An optional repair(bits) supplies a feasible bit vector for
104 evaluation. Charge any additional work inside that callback
105 separately. Run with an empty reporting archive.
106 """
107 if len(self.archive):
108 raise ValueError("Use an empty reporting archive for each swarm run.")
109 if not callable(evaluate) or (repair is not None and not callable(repair)):
110 raise TypeError("Supply a callable evaluator and optional repair.")
111 budget = _positive_int(budget, "budget")
112 rng = np.random.default_rng(self.seed)
113 width = min(self.population_size, budget)
114 moves = (budget - 1) // width
115 shape = (width, self.dimension)
116 positions = rng.integers(0, 2, size=shape, dtype=np.int8)
117 personal = positions.copy()
118 velocity = rng.uniform(-self.velocity_limit, self.velocity_limit, size=shape)
119 memory, seen = deque(), set()
120 calls = updates = outside = 0
121 while calls < budget:
122 count = min(budget - calls, width)
123 measured = []
124 for row in range(count):
125 genome = tuple(map(int, positions[row]))
126 if repair is not None:
127 fixed = np.asarray(repair(genome))
128 if fixed.shape != (self.dimension,) or not np.isin(fixed, (0, 1)).all():
129 raise ValueError("repair must return a binary vector of the configured length.")
130 positions[row] = fixed
131 genome = tuple(map(int, positions[row]))
132 fitness, features = evaluate(genome)
133 fitness = float(fitness)
134 features = tuple(map(float, features))
135 calls += 1
136 if (not isfinite(fitness) or len(features) != len(self.archive.features_domain)
137 or not all(map(isfinite, features))):
138 raise ValueError("Return one finite objective and finite archive descriptors.")
139 if (self.archive.in_bounds((fitness,), self.archive.fitness_domain)
140 and self.archive.in_bounds(features, self.archive.features_domain)):
141 if self.archive.free >= 1 or self.archive.solutions[self.archive.index_grid(features)]:
142 previous = self.archive.nb_added
143 self.archive.add(Individual(genome, fitness=Fitness((fitness,), weights=self._weights),
144 features=Features(features)))
145 updates += self.archive.nb_added - previous
146 else:
147 outside += 1
148 measured.append(genome)
149
150 snapshot = np.asarray(memory, dtype=np.int8)
151 candidates = _hamming_novelty(positions[:count], snapshot, self.neighbors)
152 leaders = _hamming_novelty(personal, snapshot, self.neighbors)
153 better = np.ones(count, dtype=bool) if not memory else candidates > leaders[:count]
154 np.copyto(personal[:count], positions[:count], where=better[:, None])
155 leaders[:count] = np.where(better, candidates, leaders[:count])
156 for genome in measured:
157 if genome not in seen:
158 if len(memory) == self.memory_size:
159 seen.remove(memory.popleft())
160 memory.append(genome)
161 seen.add(genome)
162 if calls < budget:
163 leader = personal[int(np.argmax(leaders))]
164 velocity = np.clip(self.inertia * velocity
165 + self.cognitive * rng.random(shape) * (personal - positions)
166 + self.social * rng.random(shape) * (leader - positions),
167 -self.velocity_limit, self.velocity_limit)
168 start, end = self.temperature
169 progress = (calls // width - 1) / max(1, moves - 1)
170 temperature = start + progress * (end - start)
171 # Update only the final batch's measured slots when the budget is short.
172 active = min(width, budget - calls)
173 positions[:active] = rng.random((active, self.dimension)) < expit(velocity[:active] / temperature)
174 return BinarySwarmResult(self.archive, tuple(tuple(map(int, row)) for row in positions),
175 tuple(memory), calls, updates, outside)
Final particle positions, novelty memory, and measured search costs.
Move binary particles using personal and social Hamming-novelty leaders.
optimise(self, evaluate, budget, *, repair=None)
Run the swarm for at most budget objective calls.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405