Source code for qdpy.algorithms.gram_elites

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Corpus-trained n-gram generation, mutation, and crossover for MAP-Elites.
# @see https://doi.org/10.1145/3472538.3472599

"""Illuminate fixed-length token sequences with n-gram genetic operators."""

from collections import Counter, deque

import numpy as np

from qdpy.base import registry

from .base import QDAlgorithm
from .modern import _positive_int
from .task_search import _validate_grid

__all__ = ["NGramSequenceSpace", "GramElites"]


## @brief Learn allowed token transitions and keep variation within their support.
[docs] class NGramSequenceSpace: """Fixed-length token sequences supported by an observed n-gram graph. :param corpus: Iterable of token sequences. Tokens must be hashable. :param n: Number of tokens per n-gram, including its predicted token. :param length: Length of each candidate, at least n. Sampling uses corpus transition counts, restricted to edges that can complete the required length. Mutation and crossover use a shortest context bridge, then trim or extend the tail to length. A splice that cannot be completed returns the first parent. """ def __init__(self, corpus, *, n, length): self.n = _positive_int(n, "n") self.length = _positive_int(length, "length") if self.length < self.n: raise ValueError("length must be at least n.") self._width = self.n - 1 self._transitions = {} for sequence in corpus: row = tuple(sequence) for offset in range(len(row) - self._width): context = row[offset:offset + self._width] self._transitions.setdefault(context, Counter())[row[offset + self._width]] += 1 if not self._transitions: raise ValueError("The corpus must contain at least one complete n-gram.") self._links = { context: {token: self._advance(context, token) for token in counts} for context, counts in self._transitions.items() } reachable = [set(self._links)] reachable[0].update(target for edges in self._links.values() for target in edges.values()) for _ in range(self.length - self._width): previous = reachable[-1] viable = {context for context, edges in self._links.items() if any(target in previous for target in edges.values())} reachable.append(viable) if viable == previous: break self._reachable = reachable self._starts = tuple(context for context in self._links if context in reachable[-1]) if not self._starts: raise ValueError("No sequence of the requested length is supported by the corpus.") def _advance(self, context, token): return (context + (token,))[1:] @staticmethod def _draw(counts, rng): tokens = tuple(counts) weights = np.fromiter(counts.values(), dtype=float) return tokens[rng.choice(len(tokens), p=weights / weights.sum())] ## @brief Check the length and every contiguous n-gram of a candidate.
[docs] def supports(self, sequence): """Return whether the fixed-length sequence stays in the corpus graph.""" row = tuple(sequence) if len(row) != self.length: return False try: return all(row[i + self._width] in self._transitions.get(row[i:i + self._width], ()) for i in range(self.length - self._width)) except TypeError: return False
## @brief Draw a complete sequence from the empirical transition model.
[docs] def sample(self, rng): """Draw a starting context uniformly, then use viable empirical edges.""" context = self._starts[rng.integers(len(self._starts))] return self._complete(context, rng)
def _complete(self, prefix, rng): sequence = list(prefix) context = tuple(sequence[len(sequence) - self._width:]) while len(sequence) < self.length: steps_left = self.length - len(sequence) - 1 viable = self._reachable[min(steps_left, len(self._reachable) - 1)] counts = self._transitions.get(context, {}) choices = {token: count for token, count in counts.items() if self._links[context][token] in viable} if not choices: return None token = self._draw(choices, rng) sequence.append(token) context = self._links[context][token] return tuple(sequence) def _validate(self, sequence): row = tuple(sequence) if not self.supports(row): raise ValueError("Parent sequences must have the configured length and supported n-grams.") return row def _bridge(self, start, end): queue = deque([start]) parent = {start: None} while queue: context = queue.popleft() if context == end: path = [] while parent[context] is not None: context, token = parent[context] path.append(token) return tuple(reversed(path)) for token, nxt in self._links.get(context, {}).items(): if nxt not in parent: parent[nxt] = context, token queue.append(nxt) return None def _splice(self, prefix, suffix, fallback, rng): if not self._width: return (prefix + suffix)[:self.length] target = suffix[:self._width] bridge = self._bridge(prefix[-self._width:], target) if bridge is None: return fallback child = (prefix + bridge + suffix[self._width:])[:self.length] return self._complete(child, rng) or fallback ## @brief Replace one interior token and reconnect the remaining suffix.
[docs] def mutate(self, sequence, rng): """Return a supported child and allow unchanged offspring at dead ends.""" row = self._validate(sequence) if self.length <= 2 * self._width: return row cut = rng.integers(self._width, self.length - self._width) context = row[cut - self._width:cut] alternatives = {token: count for token, count in self._transitions[context].items() if token != row[cut]} if not alternatives: return row token = self._draw(alternatives, rng) return self._splice(row[:cut] + (token,), row[cut + 1:], row, rng)
## @brief Join an interior prefix and suffix from two supported parents.
[docs] def crossover(self, first, second, rng): """Return a supported child using a shortest bridge between contexts.""" left, right = self._validate(first), self._validate(second) low, high = max(1, self._width), min(self.length - 1, self.length - self._width) if low > high: return left cut = rng.integers(low, high + 1) return self._splice(left[:cut], right[cut:], left, rng)
## @brief Illuminate supported token sequences in a native Grid or CVTGrid.
[docs] @registry.register class GramElites(QDAlgorithm): """MAP-Elites with corpus-sampled starts and n-gram variation. :param container: Best-only scalar Grid or CVTGrid. :param budget: Candidate proposals to evaluate. :param space: Fitted NGramSequenceSpace. :param initial_candidates: Number of corpus-sampled proposals before variation. :param crossover_probability: Probability of drawing a second parent and crossing. :param mutation_probability: Probability of applying n-gram mutation to the child. :param batch_size: Maximum proposals per native optimisation batch. :param seed: Seed for proposals and parent selection. :param kwargs: Native algorithm settings, including optimisation_task. """ def __init__(self, container, budget, space, *, initial_candidates=8, crossover_probability=1., mutation_probability=.02, batch_size=1, seed=0, **kwargs): _validate_grid(container, empty=False) if not isinstance(space, NGramSequenceSpace): raise TypeError("space must be an NGramSequenceSpace.") if any(not space.supports(row) for row in container): raise ValueError("Seeded elites must be supported by the sequence space.") if not (0. <= crossover_probability <= 1. and 0. <= mutation_probability <= 1.): raise ValueError("Variation probabilities must lie in [0, 1].") self.space = space self._initial = _positive_int(initial_candidates, "initial_candidates") self._crossover = crossover_probability self._mutation = mutation_probability self._seed = seed kwargs.setdefault("optimisation_task", container.fitness_weights or "maximisation") super().__init__(container, _positive_int(budget, "budget"), dimension=space.length, batch_size=_positive_int(batch_size, "batch_size"), **kwargs) def reinit(self): """Reset the native counters and private proposal RNG.""" super().reinit() self._rng = np.random.default_rng(self._seed) def _internal_ask(self, base_ind): if not self.container or self.nb_suggestions < self._initial: child = self.space.sample(self._rng) else: child = self.container[self._rng.integers(len(self.container))] if self._rng.random() < self._crossover: second = self.container[self._rng.integers(len(self.container))] child = self.space.crossover(child, second, self._rng) if self._rng.random() < self._mutation: child = self.space.mutate(child, self._rng) base_ind[:] = child return base_ind def _tell_before_container_update(self, individual): if not self.space.supports(individual): raise ValueError("Reported sequences must stay within the n-gram support.") return super()._tell_before_container_update(individual)