QDpy
Loading...
Searching...
No Matches
qdevo.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Keep trade-offs between semantically similar, measured heuristics."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import numpy as np
12
13from qdpy.phenotype import Fitness
14from .modern import _positive_int
15
16__all__ = ["QDEvo", "QDEvoEntry", "QDEvoStats"]
17
18
19
20@dataclass(frozen=True)
22 """Store a heuristic, its raw objective vector, and a unit embedding."""
23
24 heuristic: object
25 objectives: tuple[float, ...]
26 embedding: tuple[float, ...]
27
28
29
30@dataclass(frozen=True)
32 """Count generator calls, evaluator calls, invalids, duplicates, and admissions."""
33
34 proposals: int
35 evaluations: int
36 invalid: int
37 duplicates: int
38 admissions: int
39
40
41
42class QDEvo:
43 """Support QDEvo's semantic survival and parent selection through callbacks.
44
45 Normalize each embedding before comparing cosine similarities. In
46 insertion order, find the first cluster where the candidate matches
47 every current member. A candidate competes only in that cluster. If
48 no cluster qualifies, it starts another one. Clusters retain their
49 identity after pruning. A callback can canonicalize its heuristic
50 representation before proposing it to share the duplicate filter.
51
52 :param propose: Callable taking (tuple_of_parent_entries, rng) and returning
53 a hashable immutable heuristic or None to skip the proposal.
54 The parent tuple is empty while bootstrapping. A dominating crossover
55 parent is passed first.
56 :param embed: Callable mapping a valid heuristic to a finite nonzero vector.
57 :param evaluate: Callable returning a finite objective vector, or None for a failed heuristic.
58 :param fitness_weights: Two or more signed directions, positive for maximize and negative for minimize.
59 :param similarity: Minimum cosine similarity to every currently retained cluster member.
60 :param crossover_probability: Probability of drawing two distinct parents when available.
61 :param seed: Private proposal and parent selection seed.
62 """
63
64 def __init__(self, *, propose, embed, evaluate, fitness_weights, similarity=.95,
65 crossover_probability=.25, seed=0):
66 if not all(map(callable, (propose, embed, evaluate))):
67 raise TypeError("Provide proposal, embedding, and evaluator callbacks.")
68 weights = tuple(map(float, fitness_weights))
69 if len(weights) < 2 or any(not isfinite(weight) or weight == 0. for weight in weights):
70 raise ValueError("Supply at least two finite, nonzero objective directions.")
71 if not -1. <= similarity <= 1. or not 0. <= crossover_probability <= 1.:
72 raise ValueError("Similarity must be in [-1, 1] and crossover probability in [0, 1].")
73 self._weights = tuple(map(float, np.sign(weights)))
74 self._propose, self._embed, self._evaluate = propose, embed, evaluate
75 self.similarity, self.crossover_probability = similarity, crossover_probability
76 self._rng = np.random.default_rng(seed)
77 self._clusters, self._seen = [], set()
78 self._width = None
79 self._proposals = self._evaluations = self._invalid = self._duplicates = self._admissions = 0
80
81 @property
82 def clusters(self):
83 """Return immutable cluster snapshots, one local Pareto front per cluster."""
84 return tuple(tuple(cluster) for cluster in self._clusters)
85
86 @property
87 def stats(self):
88 """Return counters across all completed or interrupted run calls."""
89 return QDEvoStats(self._proposals, self._evaluations, self._invalid, self._duplicates, self._admissions)
90
91 def _fitness(self, objectives):
92 return Fitness(objectives, weights=self._weights)
93
94 def _parents(self):
95 entries = [entry for cluster in self._clusters for entry in cluster]
96 if not entries:
97 return ()
98 count = 1 + (len(entries) > 1 and self._rng.random() < self.crossover_probability)
99 parents = tuple(entries[i] for i in self._rng.choice(len(entries), size=count, replace=False))
100 if count == 2 and self._fitness(parents[1].objectives).dominates(self._fitness(parents[0].objectives)):
101 parents = parents[::-1]
102 return parents
103
104 def _embedding(self, heuristic):
105 raw = np.asarray(self._embed(heuristic), dtype=float)
106 if (raw.ndim != 1 or not len(raw) or (self._width is not None and raw.size != self._width)
107 or not np.isfinite(raw).all() or not np.any(raw)):
108 raise ValueError("Provide fixed-width, finite, nonzero embeddings.")
109 scaled = raw / np.max(np.abs(raw))
110 return tuple(map(float, scaled / np.linalg.norm(scaled)))
111
112 def _offer(self, entry):
113 for cluster in self._clusters:
114 similarities = np.asarray([old.embedding for old in cluster]) @ entry.embedding
115 # Allow roundoff at the endpoints of the cosine interval.
116 if not np.all(similarities >= self.similarity - 8 * np.finfo(float).eps):
117 continue
118 fitness = self._fitness(entry.objectives)
119 incumbents = [self._fitness(old.objectives) for old in cluster]
120 if any(old.dominates(fitness) for old in incumbents):
121 return
122 survivors = [old for old, previous in zip(cluster, incumbents) if not fitness.dominates(previous)]
123 cluster[:] = [*survivors, entry]
124 break
125 else:
126 self._clusters.append([entry])
127 self._admissions += 1
128
129 def _measure(self, heuristic):
130 if heuristic in self._seen:
131 self._duplicates += 1
132 return
133 self._evaluations += 1
134 objectives = self._evaluate(heuristic)
135 if objectives is None:
136 self._invalid += 1
137 else:
138 objectives = tuple(map(float, objectives))
139 if len(objectives) != len(self._weights) or not all(map(isfinite, objectives)):
140 raise ValueError("Return one finite value per objective, or None for an invalid heuristic.")
141 embedding = self._embedding(heuristic)
142 self._width = len(embedding)
143 self._offer(QDEvoEntry(heuristic, objectives, embedding))
144 self._seen.add(heuristic)
145
146
147 def run(self, budget, *, initial=(), proposal_limit=None):
148 """Evaluate optional seeds first, then spend up to budget more exact calls.
149
150 Previously evaluated candidates and declined proposals consume no
151 evaluation calls. Each generator invocation counts toward the
152 proposal cap, which defaults to ten times budget. Evaluation
153 returning None is counted as invalid, and callback errors propagate.
154 """
155 budget = _positive_int(budget, "budget")
156 limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
157 seeds = tuple(initial)
158 if any(seed is None for seed in seeds) or len(set(seeds) - self._seen) > budget:
159 raise ValueError("Supply non-None seeds that fit the evaluation budget.")
160 stop = self._evaluations + budget
161 for heuristic in seeds:
162 self._measure(heuristic)
163 for _ in range(limit):
164 if self._evaluations == stop:
165 break
166 self._proposals += 1
167 heuristic = self._propose(self._parents(), self._rng)
168 if heuristic is not None:
169 self._measure(heuristic)
170 return self.stats
One evaluated heuristic retained in a semantic niche.
Definition qdevo.py:21
Cumulative search and archive counters.
Definition qdevo.py:31
Generate heuristic alternatives and keep local Pareto fronts in embedding space.
Definition qdevo.py:42
_embedding(self, heuristic)
Definition qdevo.py:104
run(self, budget, *, initial=(), proposal_limit=None)
Continue search under separate exact evaluation and proposal caps.
Definition qdevo.py:147
_measure(self, heuristic)
Definition qdevo.py:129
_fitness(self, objectives)
Definition qdevo.py:91