QDpy
Loading...
Searching...
No Matches
gram_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Illuminate fixed-length token sequences with n-gram genetic operators."""
7
8from collections import Counter, deque
9
10import numpy as np
11
12from qdpy.base import registry
13
14from .base import QDAlgorithm
15from .modern import _positive_int
16from .task_search import _validate_grid
17
18__all__ = ["NGramSequenceSpace", "GramElites"]
19
20
21
23 """Fixed-length token sequences supported by an observed n-gram graph.
24
25 :param corpus: Iterable of token sequences. Tokens must be hashable.
26 :param n: Number of tokens per n-gram, including its predicted token.
27 :param length: Length of each candidate, at least n.
28
29 Sampling uses corpus transition counts, restricted to edges that can
30 complete the required length. Mutation and crossover use a shortest
31 context bridge, then trim or extend the tail to length. A splice
32 that cannot be completed returns the first parent.
33 """
34
35 def __init__(self, corpus, *, n, length):
36 self.n = _positive_int(n, "n")
37 self.length = _positive_int(length, "length")
38 if self.length < self.n:
39 raise ValueError("length must be at least n.")
40 self._width = self.n - 1
41 self._transitions = {}
42 for sequence in corpus:
43 row = tuple(sequence)
44 for offset in range(len(row) - self._width):
45 context = row[offset:offset + self._width]
46 self._transitions.setdefault(context, Counter())[row[offset + self._width]] += 1
47 if not self._transitions:
48 raise ValueError("The corpus must contain at least one complete n-gram.")
49 self._links = {
50 context: {token: self._advance(context, token) for token in counts}
51 for context, counts in self._transitions.items()
52 }
53 reachable = [set(self._links)]
54 reachable[0].update(target for edges in self._links.values() for target in edges.values())
55 for _ in range(self.length - self._width):
56 previous = reachable[-1]
57 viable = {context for context, edges in self._links.items()
58 if any(target in previous for target in edges.values())}
59 reachable.append(viable)
60 if viable == previous:
61 break
62 self._reachable = reachable
63 self._starts = tuple(context for context in self._links
64 if context in reachable[-1])
65 if not self._starts:
66 raise ValueError("No sequence of the requested length is supported by the corpus.")
67
68 def _advance(self, context, token):
69 return (context + (token,))[1:]
70
71 @staticmethod
72 def _draw(counts, rng):
73 tokens = tuple(counts)
74 weights = np.fromiter(counts.values(), dtype=float)
75 return tokens[rng.choice(len(tokens), p=weights / weights.sum())]
76
77
78 def supports(self, sequence):
79 """Return whether the fixed-length sequence stays in the corpus graph."""
80 row = tuple(sequence)
81 if len(row) != self.length:
82 return False
83 try:
84 return all(row[i + self._width] in self._transitions.get(row[i:i + self._width], ())
85 for i in range(self.length - self._width))
86 except TypeError:
87 return False
88
89
90 def sample(self, rng):
91 """Draw a starting context uniformly, then use viable empirical edges."""
92 context = self._starts[rng.integers(len(self._starts))]
93 return self._complete(context, rng)
94
95 def _complete(self, prefix, rng):
96 sequence = list(prefix)
97 context = tuple(sequence[len(sequence) - self._width:])
98 while len(sequence) < self.length:
99 steps_left = self.length - len(sequence) - 1
100 viable = self._reachable[min(steps_left, len(self._reachable) - 1)]
101 counts = self._transitions.get(context, {})
102 choices = {token: count for token, count in counts.items() if self._links[context][token] in viable}
103 if not choices:
104 return None
105 token = self._draw(choices, rng)
106 sequence.append(token)
107 context = self._links[context][token]
108 return tuple(sequence)
109
110 def _validate(self, sequence):
111 row = tuple(sequence)
112 if not self.supports(row):
113 raise ValueError("Parent sequences must have the configured length and supported n-grams.")
114 return row
115
116 def _bridge(self, start, end):
117 queue = deque([start])
118 parent = {start: None}
119 while queue:
120 context = queue.popleft()
121 if context == end:
122 path = []
123 while parent[context] is not None:
124 context, token = parent[context]
125 path.append(token)
126 return tuple(reversed(path))
127 for token, nxt in self._links.get(context, {}).items():
128 if nxt not in parent:
129 parent[nxt] = context, token
130 queue.append(nxt)
131 return None
132
133 def _splice(self, prefix, suffix, fallback, rng):
134 if not self._width:
135 return (prefix + suffix)[:self.length]
136 target = suffix[:self._width]
137 bridge = self._bridge(prefix[-self._width:], target)
138 if bridge is None:
139 return fallback
140 child = (prefix + bridge + suffix[self._width:])[:self.length]
141 return self._complete(child, rng) or fallback
142
143
144 def mutate(self, sequence, rng):
145 """Return a supported child and allow unchanged offspring at dead ends."""
146 row = self._validate(sequence)
147 if self.length <= 2 * self._width:
148 return row
149 cut = rng.integers(self._width, self.length - self._width)
150 context = row[cut - self._width:cut]
151 alternatives = {token: count for token, count in self._transitions[context].items()
152 if token != row[cut]}
153 if not alternatives:
154 return row
155 token = self._draw(alternatives, rng)
156 return self._splice(row[:cut] + (token,), row[cut + 1:], row, rng)
157
158
159 def crossover(self, first, second, rng):
160 """Return a supported child using a shortest bridge between contexts."""
161 left, right = self._validate(first), self._validate(second)
162 low, high = max(1, self._width), min(self.length - 1, self.length - self._width)
163 if low > high:
164 return left
165 cut = rng.integers(low, high + 1)
166 return self._splice(left[:cut], right[cut:], left, rng)
167
168
169
170@registry.register
172 """MAP-Elites with corpus-sampled starts and n-gram variation.
173
174 :param container: Best-only scalar Grid or CVTGrid.
175 :param budget: Candidate proposals to evaluate.
176 :param space: Fitted NGramSequenceSpace.
177 :param initial_candidates: Number of corpus-sampled proposals before variation.
178 :param crossover_probability: Probability of drawing a second parent and crossing.
179 :param mutation_probability: Probability of applying n-gram mutation to the child.
180 :param batch_size: Maximum proposals per native optimisation batch.
181 :param seed: Seed for proposals and parent selection.
182 :param kwargs: Native algorithm settings, including optimisation_task.
183 """
184
185 def __init__(self, container, budget, space, *, initial_candidates=8, crossover_probability=1.,
186 mutation_probability=.02, batch_size=1, seed=0, **kwargs):
187 _validate_grid(container, empty=False)
188 if not isinstance(space, NGramSequenceSpace):
189 raise TypeError("space must be an NGramSequenceSpace.")
190 if any(not space.supports(row) for row in container):
191 raise ValueError("Seeded elites must be supported by the sequence space.")
192 if not (0. <= crossover_probability <= 1. and 0. <= mutation_probability <= 1.):
193 raise ValueError("Variation probabilities must lie in [0, 1].")
194 self.space = space
195 self._initial = _positive_int(initial_candidates, "initial_candidates")
196 self._crossover = crossover_probability
197 self._mutation = mutation_probability
198 self._seed = seed
199 kwargs.setdefault("optimisation_task", container.fitness_weights or "maximisation")
200 super().__init__(container, _positive_int(budget, "budget"), dimension=space.length,
201 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
202
203 def reinit(self):
204 """Reset the native counters and private proposal RNG."""
205 super().reinit()
206 self._rng = np.random.default_rng(self._seed)
207
208 def _internal_ask(self, base_ind):
209 if not self.container or self.nb_suggestions < self._initial:
210 child = self.space.sample(self._rng)
211 else:
212 child = self.container[self._rng.integers(len(self.container))]
213 if self._rng.random() < self._crossover:
214 second = self.container[self._rng.integers(len(self.container))]
215 child = self.space.crossover(child, second, self._rng)
216 if self._rng.random() < self._mutation:
217 child = self.space.mutate(child, self._rng)
218 base_ind[:] = child
219 return base_ind
220
221 def _tell_before_container_update(self, individual):
222 if not self.space.supports(individual):
223 raise ValueError("Reported sequences must stay within the n-gram support.")
224 return super()._tell_before_container_update(individual)
Illuminate supported token sequences in a native Grid or CVTGrid.
_tell_before_container_update(self, individual)
Read pre-admission state for optimiser feedback.
Learn allowed token transitions and keep variation within their support.
sample(self, rng)
Draw a complete sequence from the empirical transition model.
supports(self, sequence)
Check the length and every contiguous n-gram of a candidate.
mutate(self, sequence, rng)
Replace one interior token and reconnect the remaining suffix.
_splice(self, prefix, suffix, fallback, rng)
crossover(self, first, second, rng)
Join an interior prefix and suffix from two supported parents.