# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Callback-based semantic clustering and local Pareto search for heuristics.
# @see https://arxiv.org/abs/2607.11916
"""Keep trade-offs between semantically similar, measured heuristics."""
from dataclasses import dataclass
from math import isfinite
import numpy as np
from qdpy.phenotype import Fitness
from .modern import _positive_int
__all__ = ["QDEvo", "QDEvoEntry", "QDEvoStats"]
## @brief One evaluated heuristic retained in a semantic niche.
[docs]
@dataclass(frozen=True)
class QDEvoEntry:
"""Store a heuristic, its raw objective vector, and a unit embedding."""
heuristic: object
objectives: tuple[float, ...]
embedding: tuple[float, ...]
## @brief Cumulative search and archive counters.
[docs]
@dataclass(frozen=True)
class QDEvoStats:
"""Count generator calls, evaluator calls, invalids, duplicates, and admissions."""
proposals: int
evaluations: int
invalid: int
duplicates: int
admissions: int
## @brief Generate heuristic alternatives and keep local Pareto fronts in embedding space.
[docs]
class QDEvo:
"""Support QDEvo's semantic survival and parent selection through callbacks.
Normalize each embedding before comparing cosine similarities. In
insertion order, find the first cluster where the candidate matches
every current member. A candidate competes only in that cluster. If
no cluster qualifies, it starts another one. Clusters retain their
identity after pruning. A callback can canonicalize its heuristic
representation before proposing it to share the duplicate filter.
:param propose: Callable taking (tuple_of_parent_entries, rng) and returning
a hashable immutable heuristic or None to skip the proposal.
The parent tuple is empty while bootstrapping. A dominating crossover
parent is passed first.
:param embed: Callable mapping a valid heuristic to a finite nonzero vector.
:param evaluate: Callable returning a finite objective vector, or None for a failed heuristic.
:param fitness_weights: Two or more signed directions, positive for maximize and negative for minimize.
:param similarity: Minimum cosine similarity to every currently retained cluster member.
:param crossover_probability: Probability of drawing two distinct parents when available.
:param seed: Private proposal and parent selection seed.
"""
def __init__(self, *, propose, embed, evaluate, fitness_weights, similarity=.95,
crossover_probability=.25, seed=0):
if not all(map(callable, (propose, embed, evaluate))):
raise TypeError("Provide proposal, embedding, and evaluator callbacks.")
weights = tuple(map(float, fitness_weights))
if len(weights) < 2 or any(not isfinite(weight) or weight == 0. for weight in weights):
raise ValueError("Supply at least two finite, nonzero objective directions.")
if not -1. <= similarity <= 1. or not 0. <= crossover_probability <= 1.:
raise ValueError("Similarity must be in [-1, 1] and crossover probability in [0, 1].")
self._weights = tuple(map(float, np.sign(weights)))
self._propose, self._embed, self._evaluate = propose, embed, evaluate
self.similarity, self.crossover_probability = similarity, crossover_probability
self._rng = np.random.default_rng(seed)
self._clusters, self._seen = [], set()
self._width = None
self._proposals = self._evaluations = self._invalid = self._duplicates = self._admissions = 0
@property
def clusters(self):
"""Return immutable cluster snapshots, one local Pareto front per cluster."""
return tuple(tuple(cluster) for cluster in self._clusters)
@property
def stats(self):
"""Return counters across all completed or interrupted run calls."""
return QDEvoStats(self._proposals, self._evaluations, self._invalid, self._duplicates, self._admissions)
def _fitness(self, objectives):
return Fitness(objectives, weights=self._weights)
def _parents(self):
entries = [entry for cluster in self._clusters for entry in cluster]
if not entries:
return ()
count = 1 + (len(entries) > 1 and self._rng.random() < self.crossover_probability)
parents = tuple(entries[i] for i in self._rng.choice(len(entries), size=count, replace=False))
if count == 2 and self._fitness(parents[1].objectives).dominates(self._fitness(parents[0].objectives)):
parents = parents[::-1]
return parents
def _embedding(self, heuristic):
raw = np.asarray(self._embed(heuristic), dtype=float)
if (raw.ndim != 1 or not len(raw) or (self._width is not None and raw.size != self._width)
or not np.isfinite(raw).all() or not np.any(raw)):
raise ValueError("Provide fixed-width, finite, nonzero embeddings.")
scaled = raw / np.max(np.abs(raw))
return tuple(map(float, scaled / np.linalg.norm(scaled)))
def _offer(self, entry):
for cluster in self._clusters:
similarities = np.asarray([old.embedding for old in cluster]) @ entry.embedding
# Allow roundoff at the endpoints of the cosine interval.
if not np.all(similarities >= self.similarity - 8 * np.finfo(float).eps):
continue
fitness = self._fitness(entry.objectives)
incumbents = [self._fitness(old.objectives) for old in cluster]
if any(old.dominates(fitness) for old in incumbents):
return
survivors = [old for old, previous in zip(cluster, incumbents) if not fitness.dominates(previous)]
cluster[:] = [*survivors, entry]
break
else:
self._clusters.append([entry])
self._admissions += 1
def _measure(self, heuristic):
if heuristic in self._seen:
self._duplicates += 1
return
self._evaluations += 1
objectives = self._evaluate(heuristic)
if objectives is None:
self._invalid += 1
else:
objectives = tuple(map(float, objectives))
if len(objectives) != len(self._weights) or not all(map(isfinite, objectives)):
raise ValueError("Return one finite value per objective, or None for an invalid heuristic.")
embedding = self._embedding(heuristic)
self._width = len(embedding)
self._offer(QDEvoEntry(heuristic, objectives, embedding))
self._seen.add(heuristic)
## @brief Continue search under separate exact evaluation and proposal caps.
[docs]
def run(self, budget, *, initial=(), proposal_limit=None):
"""Evaluate optional seeds first, then spend up to budget more exact calls.
Previously evaluated candidates and declined proposals consume no
evaluation calls. Each generator invocation counts toward the
proposal cap, which defaults to ten times budget. Evaluation
returning None is counted as invalid, and callback errors propagate.
"""
budget = _positive_int(budget, "budget")
limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
seeds = tuple(initial)
if any(seed is None for seed in seeds) or len(set(seeds) - self._seen) > budget:
raise ValueError("Supply non-None seeds that fit the evaluation budget.")
stop = self._evaluations + budget
for heuristic in seeds:
self._measure(heuristic)
for _ in range(limit):
if self._evaluations == stop:
break
self._proposals += 1
heuristic = self._propose(self._parents(), self._rng)
if heuristic is not None:
self._measure(heuristic)
return self.stats