43 """Support QDEvo's semantic survival and parent selection through callbacks.
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.
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.
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)))
76 self.
_rng = np.random.default_rng(seed)
83 """Return immutable cluster snapshots, one local Pareto front per cluster."""
84 return tuple(tuple(cluster)
for cluster
in self.
_clusters)
88 """Return counters across all completed or interrupted run calls."""
91 def _fitness(self, objectives):
95 entries = [entry
for cluster
in self.
_clusters for entry
in cluster]
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]
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)))
112 def _offer(self, entry):
114 similarities = np.asarray([old.embedding
for old
in cluster]) @ entry.embedding
116 if not np.all(similarities >= self.
similarity - 8 * np.finfo(float).eps):
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):
122 survivors = [old
for old, previous
in zip(cluster, incumbents)
if not fitness.dominates(previous)]
123 cluster[:] = [*survivors, entry]
129 def _measure(self, heuristic):
130 if heuristic
in self.
_seen:
135 if objectives
is None:
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.")
142 self.
_width = len(embedding)
144 self.
_seen.add(heuristic)
147 def run(self, budget, *, initial=(), proposal_limit=
None):
148 """Evaluate optional seeds first, then spend up to budget more exact calls.
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.
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.")
161 for heuristic
in seeds:
163 for _
in range(limit):
168 if heuristic
is not None:
One evaluated heuristic retained in a semantic niche.
run(self, budget, *, initial=(), proposal_limit=None)
Continue search under separate exact evaluation and proposal caps.