23 """Fixed-length token sequences supported by an observed n-gram graph.
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.
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.
35 def __init__(self, corpus, *, n, length):
36 self.
n = _positive_int(n,
"n")
37 self.
length = _positive_int(length,
"length")
39 raise ValueError(
"length must be at least n.")
42 for sequence
in corpus:
44 for offset
in range(len(row) - self.
_width):
45 context = row[offset:offset + self.
_width]
48 raise ValueError(
"The corpus must contain at least one complete n-gram.")
50 context: {token: self.
_advance(context, token)
for token
in counts}
53 reachable = [set(self.
_links)]
54 reachable[0].update(target
for edges
in self.
_links.values()
for target
in edges.values())
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:
64 if context
in reachable[-1])
66 raise ValueError(
"No sequence of the requested length is supported by the corpus.")
68 def _advance(self, context, token):
69 return (context + (token,))[1:]
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())]
79 """Return whether the fixed-length sequence stays in the corpus graph."""
81 if len(row) != self.
length:
91 """Draw a starting context uniformly, then use viable empirical edges."""
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
102 choices = {token: count
for token, count
in counts.items()
if self.
_links[context][token]
in viable}
105 token = self.
_draw(choices, rng)
106 sequence.append(token)
107 context = self.
_links[context][token]
108 return tuple(sequence)
110 def _validate(self, sequence):
111 row = tuple(sequence)
113 raise ValueError(
"Parent sequences must have the configured length and supported n-grams.")
116 def _bridge(self, start, end):
117 queue = deque([start])
118 parent = {start:
None}
120 context = queue.popleft()
123 while parent[context]
is not None:
124 context, token = parent[context]
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
133 def _splice(self, prefix, suffix, fallback, rng):
135 return (prefix + suffix)[:self.
length]
136 target = suffix[:self.
_width]
140 child = (prefix + bridge + suffix[self.
_width:])[:self.
length]
141 return self.
_complete(child, rng)
or fallback
145 """Return a supported child and allow unchanged offspring at dead ends."""
150 context = row[cut - self.
_width:cut]
151 alternatives = {token: count
for token, count
in self.
_transitions[context].items()
152 if token != row[cut]}
155 token = self.
_draw(alternatives, rng)
156 return self.
_splice(row[:cut] + (token,), row[cut + 1:], row, rng)
160 """Return a supported child using a shortest bridge between contexts."""
165 cut = rng.integers(low, high + 1)
166 return self.
_splice(left[:cut], right[cut:], left, rng)
172 """MAP-Elites with corpus-sampled starts and n-gram variation.
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.
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].")
195 self.
_initial = _positive_int(initial_candidates,
"initial_candidates")
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)
204 """Reset the native counters and private proposal RNG."""
206 self.
_rng = np.random.default_rng(self.
_seed)
215 child = self.
space.crossover(child, second, self.
_rng)
217 child = self.
space.mutate(child, self.
_rng)
222 if not self.
space.supports(individual):
223 raise ValueError(
"Reported sequences must stay within the n-gram support.")