QDpy
Loading...
Searching...
No Matches
constrained_novelty.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Steady-state FINS and FI2NS with a passive feasible reporting archive."""
7
8from collections import Counter, deque
9from dataclasses import dataclass
10from math import fsum
11
12import numpy as np
13from scipy.spatial.distance import cdist
14
15from .modern import _positive_int
16from .sampling import _rollout_seed
17from .task_search import _measurement, _offer, _validate_grid
18
19__all__ = ["FeasibleInfeasibleNoveltySearch", "FeasibleNoveltyStats"]
20
21
22def _novelty_scores(population, history, embedding, neighbors):
23 """Mean distance to the nearest other records, excluding identical live references."""
24 present = {row.genome for row in population}
25 extra = [row for row in history if row.genome not in present]
26 count = min(neighbors, len(population) + len(extra) - 1)
27 if count < 1:
28 return np.zeros(len(population))
29 points = [embedding(row) for row in population]
30 distances = cdist(points, points + [embedding(row) for row in extra])
31 np.fill_diagonal(distances, np.inf)
32 scores = np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
33 if not np.isfinite(scores).all():
34 raise ValueError("Novelty distances must stay finite. Scale the descriptor coordinates.")
35 return scores
36
37
38def _remember(history, row):
39 if not any(old.genome == row.genome for old in history):
40 history.append(row)
41
42
43def _tournament(population, scores, rng):
44 choices = rng.integers(len(population), size=2)
45 return population[int(choices[np.argmax(scores[choices])])]
46
47
48@dataclass(frozen=True)
50 genome: tuple
51 descriptor: tuple[float, ...]
52 violation: float
53
54
55
56@dataclass(frozen=True)
58 """Evaluations count attempted calls, with one-based first-feasible indexing."""
59
60 evaluations: int = 0
61 feasible_evaluations: int = 0
62 feasible_from_infeasible: int = 0
63 infeasible_from_feasible: int = 0
64 archive_updates: int = 0
65 first_feasible: int | None = None
66
67
68
70 """Keep independent bounded populations and novelty histories.
71
72 FINS chooses feasible parents by novelty and infeasible parents by
73 low total positive violation. FI2NS uses novelty in both populations.
74 An offspring enters the pool appropriate to its measured constraints.
75 Only feasible measurements are offered to the independent native grid.
76
77 :param archive: Empty parentless best-only Grid or CVTGrid.
78 :param initializer: Callable (rng) returning an immutable genome sequence.
79 :param mutate: Callable (genome, rng) returning a new genome sequence.
80 :param mode: FINS or FI2NS, specified as "fins" or "fi2ns".
81 :param population_size: Capacity of each breeding population.
82 :param history_size: Number of distinct recent genomes per novelty history.
83 :param neighbors: Nearest-neighbor count for novelty.
84 :param feasible_parent_probability: Fraction of births allocated to feasible
85 breeders when both populations are available.
86 :param initial_samples: Number of initial proposals from initializer.
87 :param seed: Seed for variation, selection, and evaluation calls.
88 """
89
90 def __init__(self, archive, *, initializer, mutate, mode="fins", population_size=32,
91 history_size=128, neighbors=5, feasible_parent_probability=.5, initial_samples=16, seed=0):
92 _validate_grid(archive)
93 if not callable(initializer) or not callable(mutate):
94 raise TypeError("Supply initializer and mutate callbacks.")
95 if mode not in ("fins", "fi2ns") or not 0 <= feasible_parent_probability <= 1.:
96 raise ValueError("Use fins or fi2ns and a parent probability between zero and one.")
97 self.archive = archive
98 self._initializer, self._mutate = initializer, mutate
99 self._mode, self._probability = mode, feasible_parent_probability
100 self._capacity = _positive_int(population_size, "population_size")
101 self._neighbors = _positive_int(neighbors, "neighbors")
102 self._initial = _positive_int(initial_samples, "initial_samples")
103 memory = _positive_int(history_size, "history_size")
104 self._groups = ([], [])
105 self._history = (deque(maxlen=memory), deque(maxlen=memory))
106 rng, evaluations = np.random.SeedSequence(seed).spawn(2)
107 self._rng = np.random.default_rng(rng)
108 self._evaluation_seed = int(evaluations.generate_state(1, dtype=np.uint64)[0])
109 self._counts = Counter()
110 self._residual_count = self._first = None
111
112 @property
113 def stats(self):
114 """Return cumulative measured search costs and outcomes."""
115 return FeasibleNoveltyStats(**self._counts, first_feasible=self._first)
116
117 @property
119 """Return immutable active feasible genomes."""
120 return tuple(row.genome for row in self._groups[1])
121
122 @property
124 """Return immutable active infeasible genomes."""
125 return tuple(row.genome for row in self._groups[0])
126
127 def _scores(self, group):
128 population = self._groups[group]
129 if group == 0 and self._mode == "fins":
130 return -np.asarray([row.violation for row in population])
131 return _novelty_scores(population, self._history[group], lambda row: row.descriptor, self._neighbors)
132
133 def _parent(self):
134 infeasible, feasible = self._groups
135 if self._counts["evaluations"] < self._initial:
136 return None, None
137 group = int(bool(feasible) and (not infeasible or self._rng.random() < self._probability))
138 pool = self._groups[group]
139 return (group, _tournament(pool, self._scores(group), self._rng)) if pool else (None, None)
140
141 def _candidate(self, genome, descriptor, violation, residuals):
142 return _Candidate(genome, descriptor, violation)
143
144
148 def run(self, evaluate, budget) -> FeasibleNoveltyStats:
149 """Use residuals at or below zero for feasible admission and propagate invalid evaluations."""
150 if not callable(evaluate):
151 raise TypeError("Supply a callable evaluator.")
152 for _ in range(_positive_int(budget, "budget")):
153 origin, parent = self._parent()
154 genome = tuple(self._initializer(self._rng) if parent is None else self._mutate(parent.genome, self._rng))
155 hash(genome)
156 attempt = self._counts["evaluations"]
157 self._counts["evaluations"] += 1
158 fitness, descriptors, residuals = evaluate(genome, _rollout_seed(self._evaluation_seed, 0, attempt))
159 residuals = tuple(map(float, residuals))
160 if (not residuals or not np.isfinite(residuals).all()
161 or self._residual_count is not None and len(residuals) != self._residual_count):
162 raise ValueError("Return a fixed nonempty vector of finite residuals.")
163 self._residual_count = len(residuals)
164 violation = fsum(max(0., value) for value in residuals)
165 measurement = _measurement(self.archive, ((fitness,), descriptors), genome)
166 measured, _ = measurement
167 group = int(violation == 0.)
168 if group:
169 self._counts["feasible_evaluations"] += 1
170 if self._first is None:
171 self._first = attempt + 1
172 if origin == 0:
173 self._counts["feasible_from_infeasible"] += 1
174 before = self.archive.nb_added
175 _offer(self.archive, measurement)
176 self._counts["archive_updates"] += self.archive.nb_added - before
177 elif origin == 1:
178 self._counts["infeasible_from_feasible"] += 1
179
180 pool = self._groups[group]
181 if any(row.genome == genome for row in pool):
182 continue
183 row = self._candidate(genome, tuple(self.archive.get_ind_features(measured)), violation, residuals)
184 pool.append(row)
185 if len(pool) > self._capacity:
186 scores = self._scores(group)
187 pool.pop(len(pool) - 1 - int(scores[::-1].argmin()))
188 if group or self._mode == "fi2ns":
189 _remember(self._history[group], row)
190 return self.stats
Search with feasible novelty and either violation or infeasible novelty.
FeasibleNoveltyStats run(self, evaluate, budget)
Spend an additional hard evaluator budget.
Account for feasible measurements, migrations, and reporting-archive changes.