QDpy
Loading...
Searching...
No Matches
_search.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5from bisect import insort_right
6from collections import deque
7from dataclasses import dataclass
8from functools import lru_cache
9
10import numpy as np
11from scipy.cluster.hierarchy import linkage
12from sklearn.cluster import KMeans
13
14from qdpy.algorithms.lexicase import _select_casewise, novelty_case_counts
15from qdpy.algorithms.optimal_mixing import learn_categorical_linkage
16from qdpy.containers import CVTGrid, Grid
17from qdpy.phenotype import Features, Fitness, Individual
18
19from ._expression import Expression, FittedExpression, _matrix, _OPERATORS, _target
20from ._fit import _Fitter, _integer
21
22_DEFAULT_OPERATORS = ("add", "sub", "mul", "div", "square", "sin", "cos", "exp", "log")
23
24
25
26@dataclass(frozen=True, slots=True)
28 """Count tree proposals, unique fits, training evaluations, and probe checks.
29
30 Invalid fits and invalid probe checks count unique structures.
31 A proposal of a previously fitted structure reuses its outcome.
32 """
33
34 proposals: int
35 structures_fitted: int
36 fit_evaluations: int
37 invalid_fits: int
38 probe_evaluations: int
39 invalid_probes: int
40 case_evaluations: int = 0
41
42
43
44@dataclass(frozen=True, slots=True)
46 """Block trials include revisits whose cached fit is reused."""
47
48 block_proposals: int = 0
49 accepted_blocks: int = 0
50
51
52
53@dataclass(frozen=True, slots=True)
55 """Expose retained models in training-error order and the search accounting.
56
57 The QD archive holds an Individual with one FittedExpression per
58 retained cell. GP mode returns its active population through models.
59 Case-wise modes return the models retained by the passive grid.
60 """
61
62 models: tuple[FittedExpression, ...]
63 archive: Grid | None
64 stats: SymbolicRegressionStats
65
66
67 @property
68 def best(self) -> FittedExpression | None:
69 """Return the training winner, or None if no valid candidate was retained."""
70 return self.models[0] if self.models else None
71
72
73def _operation(op, children):
74 if op in ("add", "mul"):
75 children = tuple(sorted(children))
76 return Expression(op, children)
77
78
79def _positions(tree, path=()):
80 yield path, tree
81 for i, child in enumerate(tree.children):
82 yield from _positions(child, (*path, i))
83
84
85def _replace(tree, path, replacement):
86 if not path:
87 return replacement
88 i, *rest = path
89 children = list(tree.children)
90 children[i] = _replace(children[i], rest, replacement)
91 return _operation(tree.op, tuple(children))
92
93
95 def __init__(self, n_variables, operators, literals, depth, nodes, parameters, rng):
96 self.nodes = _integer(nodes, "max_nodes", 1)
97 self.depth = min(_integer(depth, "max_depth", 0), self.nodes - 1)
98 self.parameters = _integer(parameters, "max_parameters", 0)
99 self.ops = tuple(dict.fromkeys(operators))
100 if any(op not in _OPERATORS for op in self.ops):
101 raise ValueError("operators must contain supported Expression operations.")
102 leaves = [Expression.variable(i) for i in range(n_variables)]
103 leaves.extend(Expression.constant(value) for value in literals)
104 if self.parameters:
105 leaves.append(Expression.parameter())
106 self.leaves = tuple(dict.fromkeys(leaves))
107 self.rng = rng
108
109 def choose(self, values):
110 return values[int(self.rng.integers(len(values)))]
111
112 def grow(self, depth):
113 if depth == 0 or not self.ops or self.rng.random() < .28:
114 return self.choose(self.leaves)
115 op = self.choose(self.ops)
116 return _operation(op, tuple(self.grow(depth - 1) for _ in range(_OPERATORS[op][0])))
117
118 def propose(self, pool):
119 draw = self.rng.random()
120 if not len(pool) or draw < .18:
121 tree = self.grow(int(self.rng.integers(self.depth + 1)))
122 else:
123 parent = pool.parent(self.rng).expression
124 path, old = self.choose(tuple(_positions(parent)))
125 available = self.depth - len(path)
126 if draw < .42:
127 donor = pool.parent(self.rng).expression
128 _, subtree = self.choose(tuple(_positions(donor)))
129 elif draw < .62 and available and self.ops:
130 op = self.choose(self.ops)
131 children = [old]
132 if _OPERATORS[op][0] == 2:
133 children.append(self.grow(min(available - 1, 1)))
134 if self.rng.random() < .5:
135 children.reverse()
136 subtree = _operation(op, tuple(children))
137 elif draw < .72 and old.children:
138 subtree = self.choose(old.children)
139 else:
140 subtree = self.grow(min(available, 2))
141 tree = _replace(parent, path, subtree)
142
143 if (tree.node_count <= self.nodes and tree.parameter_count <= self.parameters
144 and all(len(path) <= self.depth for path, _ in _positions(tree))):
145 return tree
146 return self.choose(self.leaves)
147
148
149@lru_cache(maxsize=64)
150def _template_groups(paths):
151 groups = [(path,) for path in paths]
152 if len(paths) <= 2:
153 return tuple(groups)
154 distances = []
155 for i, left in enumerate(paths):
156 for right in paths[i + 1:]:
157 common = 0
158 for a, b in zip(left, right):
159 if a != b:
160 break
161 common += 1
162 distances.append(len(left) + len(right) - 2 * common)
163 for a, b, _, _ in linkage(distances, method="average")[:-1]:
164 groups.append((*groups[int(a)], *groups[int(b)]))
165 return tuple(groups)
166
167
168def _tree_slots(tree):
169 return {path: node.op if node.children else node for path, node in _positions(tree)}
170
171
173 """Probe donor blocks in a sparse shared template of observed positions."""
174
175 def __init__(self, grammar, learned):
176 self.grammar, self.learned = grammar, learned
177 self.groups = []
178 self.trial = None
179 self.probes = self.accepted = 0
180
181 def _start(self, pool):
182 rng = self.grammar.rng
183 ids = rng.choice(len(pool), min(len(pool), 24), replace=False)
184 parents = [pool[int(i)] for i in ids]
185 self.parent = parents[0]
186 self.donors = [_tree_slots(model.expression) for model in parents]
187 self.current = self.donors[0]
188 paths = tuple(sorted(set().union(*(row.keys() for row in self.donors))))
189 if self.learned:
190 alleles = {}
191 samples = [[alleles.setdefault(row.get(path), len(alleles)) for path in paths] for row in self.donors]
192 groups = [tuple(paths[i] for i in block) for block in learn_categorical_linkage(samples)]
193 else:
194 groups = _template_groups(paths)
195 self.groups = [groups[int(i)] for i in rng.permutation(len(groups))]
196
197 def _decode(self, slots, path=()):
198 node = slots.get(path, self.grammar.leaves[0])
199 if isinstance(node, Expression):
200 return node
201 return _operation(node, tuple(self._decode(slots, (*path, i)) for i in range(_OPERATORS[node][0])))
202
203 def propose(self, pool):
204 rng = self.grammar.rng
205 if len(pool) >= 2 and rng.random() >= .18:
206 if not self.groups:
207 self._start(pool)
208 while self.groups:
209 block = self.groups.pop()
210 possible = [row for row in self.donors
211 if any(path in row and row[path] != self.current.get(path) for path in block)]
212 if not possible:
213 continue
214 donor = self.grammar.choose(possible)
215 trial = self.current | {path: donor[path] for path in block if path in donor}
216 tree = self._decode(trial)
217 if tree == self.parent.expression:
218 self.current = trial
219 elif tree.node_count <= self.grammar.nodes and tree.parameter_count <= self.grammar.parameters:
220 self.trial = trial
221 self.probes += 1
222 return tree
223 self.groups.clear()
224 return self.grammar.propose(pool)
225
226 def observe(self, model):
227 if self.trial is not None and model is not None and _fitness(model) <= _fitness(self.parent):
228 self.parent, self.current = model, self.trial
229 self.accepted += 1
230 self.trial = None
231
232
233def _make_archive(mode, grammar, cells, probes, seed):
234 quality = ((0., np.inf),)
235 if mode == "gp":
236 return None
237 if mode == "structural":
238 shape = grammar.nodes, min(grammar.parameters, grammar.nodes) + 1, grammar.nodes
239 domain = ((.5, shape[0] + .5), (-.5, shape[1] - .5), (-.5, shape[2] - .5))
240 return Grid(shape=shape, features_domain=domain, fitness_domain=quality)
241
242 if probes is None:
243 raise ValueError("Semantic MAP-Elites needs fixed, unlabeled probes.")
244 samples = np.random.default_rng(seed).uniform(-1., 1., (max(256, 16 * cells), probes.shape[0]))
245 kmeans = KMeans(n_clusters=cells, n_init=1, random_state=seed).fit(samples)
246 return CVTGrid(shape=cells, centroids=kmeans.cluster_centers_.clip(-1., 1.),
247 features_domain=((-1., 1.),) * probes.shape[0], fitness_domain=quality)
248
249
251 def __init__(self, archive, population_size):
252 self.archive = archive
253 self.population_size = population_size
254 self.population = []
255
256 def __len__(self):
257 return len(self.population if self.archive is None else self.archive)
258
259 def __getitem__(self, i):
260 if self.archive is None:
261 return self.population[i]
262 return self.archive[i][0]
263
264 def add(self, model, features):
265 if self.archive is None:
266 insort_right(self.population, model, key=_fitness)
267 if len(self.population) > self.population_size:
268 self.population.pop()
269 else:
270 self.archive.add(Individual([model], fitness=Fitness((model.training_rmse,), weights=(-1.,)),
271 features=Features(features)))
272
273 def parent(self, rng):
274 return self[int(rng.integers(len(self)))]
275
276
278 """Select from the last nonempty generation and stage its replacements."""
279
280 def __init__(self, target, epsilon, *, binner=None, history_size=0, history_rng=None):
281 self.target, self.epsilon = target * .5, epsilon
282 self.models, self.pending, self.errors = [], {}, []
283 self._binner, self._history_rng = binner, history_rng
284 self._history = deque(maxlen=history_size)
285 self._behaviors = []
286
287 def __len__(self):
288 return len(self.models)
289
290 def parent(self, rng):
291 return self.models[_select_casewise(self.matrix, rng, self.epsilon)]
292
293 def add(self, model, x):
294 if model.expression not in self.pending:
295 predictions = model.predict(x)
296 errors = np.abs(predictions * .5 - self.target)
297 if self._binner is not None:
298 labels = tuple(self._binner(predictions))
299 if len(labels) != len(x):
300 raise ValueError("novelty_binner must return one label per training case.")
301 self._behaviors.append(labels)
302 self.pending[model.expression] = model
303 self.errors.append(errors)
304 return 1
305 return 0
306
307 def advance(self):
308 if self.pending:
309 matrix = np.stack(self.errors)
310 if self._binner is not None:
311 counts = novelty_case_counts(self._behaviors, history=self._history)
312 matrix = np.concatenate((matrix, counts), axis=1)
313 if self._history.maxlen:
314 sample = self._behaviors[self._history_rng.integers(len(self._behaviors))]
315 self._history.append(sample)
316 self._behaviors.clear()
317 self.models, self.pending = list(self.pending.values()), {}
318 self.matrix = matrix
319 self.errors.clear()
320
321
322def _fitness(model):
323 return model.training_rmse
324
325
326
349def symbolic_regression(X, y, *, mode: str = "structural", probes=None,
350 budget: int = 512, max_depth: int = 4, max_nodes: int = 13,
351 max_parameters: int = 4, operators=_DEFAULT_OPERATORS,
352 literals=(1., 2.), cells: int = 24, population_size: int = 24,
353 passive_archive: bool = False, nonlinear_bounds=(-20., 20.), fit_evaluations: int = 48,
354 fit_restarts: int = 4, seed: int | None = None,
355 novelty_binner=None, novelty_history: int = 256, variation="subtree",
356 max_fit_evaluations=None) -> SymbolicRegressionResult:
357 """Fit equations to one labeled training dataset.
358
359 X has shape (samples, variables) and y has shape (samples,). Each
360 proposal spends one unit of budget, including repeats. Search starts
361 with the variable, literal, and free parameter terminals. Genetic
362 variation uses the supplied operator names, at most max_depth edges,
363 max_nodes nodes, and max_parameters free scalar leaves.
364
365 Structural MAP-Elites uses node count, free coefficient count, and
366 non-algebraic operator count. Semantic MAP-Elites uses one descriptor
367 coordinate per unlabeled probe row. Predictions are compressed with
368 arctangent at the training target scale, and cells defines the size
369 of its CVT. GP retains population_size candidates by training RMSE.
370 The lexicase modes use generations of population_size proposals
371 and select parents on training cases. They collect a structural
372 grid as a passive archive. Set passive_archive=True to
373 collect the same grid alongside aggregate-error GP.
374
375 Novelty-lexicase also selects on output rarity. By default it groups
376 predictions in 16 fixed bins after arctangent compression using the
377 training target scale. Pass novelty_binner to map a prediction vector
378 to a sequence of hashable labels, one per training case. It keeps one
379 sampled output row per completed generation, up to novelty_history.
380
381 For structural or semantic MAP-Elites, template-linkage clusters
382 homologous tree slots by distance in the template. Learned-linkage
383 estimates their dependencies with a masked intron symbol. Both
384 offer each fitted intermediate to the archive and continue the mix
385 from changes that preserve or improve training error. Subtree
386 remains the default. The optional total fit cap stops when fewer
387 than two training evaluations remain.
388
389 Supply probes with the same number of columns as X. If provided,
390 candidates must give finite predictions on every probe in any mode.
391 Nonlinear bounds, fit_evaluations, and fit_restarts configure
392 coefficient fitting. Validation and test labels belong outside this
393 call. The seed controls variation, fitting, and centroid generation.
394 """
395 casewise = mode in ("lexicase", "epsilon-lexicase", "novelty-lexicase")
396 if not casewise and mode not in ("structural", "semantic", "gp"):
397 raise ValueError("Choose structural, semantic, gp, lexicase, epsilon-lexicase, or novelty-lexicase.")
398 if (variation not in ("subtree", "template-linkage", "learned-linkage")
399 or variation != "subtree" and mode not in ("structural", "semantic")):
400 raise ValueError("Linked variation requires structural or semantic MAP-Elites.")
401 budget = _integer(budget, "budget", 1)
402 cells = _integer(cells, "cells", 1)
403 population_size = _integer(population_size, "population_size", 1)
404 x = _matrix(X)
405 fitter = _Fitter(x, _target(y, len(x)), nonlinear_bounds, fit_evaluations, fit_restarts)
406 fit_limit = None if max_fit_evaluations is None else _integer(max_fit_evaluations, "max_fit_evaluations", 2)
407 per_fit_limit = fitter.budget
408 if probes is not None:
409 probes = _matrix(probes)
410 if probes.shape[1] != x.shape[1]:
411 raise ValueError("Probes must have the same number of columns as X.")
412
413 variation_seed, geometry, coefficients = np.random.SeedSequence(seed).spawn(3)
414 grammar = _Grammar(x.shape[1], operators, literals, max_depth, max_nodes, max_parameters,
415 np.random.default_rng(variation_seed))
416 mixer = None if variation == "subtree" else _TreeMixer(grammar, variation == "learned-linkage")
417 archive_mode = "structural" if casewise or (mode == "gp" and passive_archive) else mode
418 archive = _make_archive(archive_mode, grammar, cells, probes, int(geometry.generate_state(1)[0]))
419 reporter = _ModelPool(archive, population_size)
420 pool = _ModelPool(None, population_size) if mode == "gp" and archive is not None else reporter
421 if mode == "novelty-lexicase":
422 history_size = _integer(novelty_history, "novelty_history", 0)
423 if novelty_binner is None:
424 def novelty_binner(predictions):
425 scaled = np.arctan2(predictions, fitter.scale) / np.pi + .5
426 return np.minimum((16 * scaled).astype(int), 15)
427 if not callable(novelty_binner):
428 raise TypeError("novelty_binner must be callable.")
429 pool = _CasePool(fitter.y, 0., binner=novelty_binner, history_size=history_size,
430 history_rng=np.random.default_rng(variation_seed.spawn(1)[0]))
431 elif casewise:
432 pool = _CasePool(fitter.y, "mad" if mode == "epsilon-lexicase" else 0.)
433 seen = set()
434 fitted_models = {} if casewise or mixer is not None else None
435 fit_calls = invalid_fits = probe_calls = invalid_probes = case_calls = 0
436 proposals = 0
437 propose = grammar.propose if mixer is None else mixer.propose
438
439 for i in range(budget):
440 if fit_limit is not None:
441 remaining = fit_limit - fit_calls
442 if remaining < 2:
443 break
444 fitter.budget = min(per_fit_limit, remaining)
445 proposals += 1
446 if casewise and i % population_size == 0:
447 pool.advance()
448 tree = grammar.leaves[i] if i < len(grammar.leaves) else propose(pool)
449 if tree in seen:
450 if casewise and tree in fitted_models:
451 case_calls += pool.add(fitted_models[tree], x)
452 if mixer is not None:
453 mixer.observe(fitted_models.get(tree))
454 continue
455 seen.add(tree)
456 fit = fitter.fit(tree, coefficients)
457 fit_calls += fit.evaluations
458 if fit.model is None:
459 invalid_fits += 1
460 if mixer is not None:
461 mixer.observe(None)
462 continue
463
464 features = (tree.node_count, tree.parameter_count, tree.non_algebraic_count)
465 if probes is not None:
466 probe_calls += 1
467 predictions = fit.model.predict(probes)
468 if not np.isfinite(predictions).all():
469 invalid_probes += 1
470 if mixer is not None:
471 mixer.observe(None)
472 continue
473 if mode == "semantic":
474 features = (2. / np.pi) * np.arctan2(predictions, fitter.scale)
475 reporter.add(fit.model, features)
476 if fitted_models is not None:
477 fitted_models[tree] = fit.model
478 if mixer is not None:
479 mixer.observe(fit.model)
480 if casewise:
481 case_calls += pool.add(fit.model, x)
482 elif pool is not reporter:
483 pool.add(fit.model, features)
484
485 counts = proposals, len(seen), fit_calls, invalid_fits, probe_calls, invalid_probes, case_calls
486 stats = (SymbolicRegressionStats(*counts) if mixer is None
487 else LinkedSymbolicRegressionStats(*counts, mixer.probes, mixer.accepted))
488 models = tuple(sorted(reporter if casewise else pool, key=_fitness))
489 return SymbolicRegressionResult(models, archive, stats)
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
A safe expression tree whose parameter leaves each hold one free scalar.
Count attempted and accepted linked changes in symbolic regression.
Definition _search.py:45
Retained regression models and the native QD archive, if used.
Definition _search.py:54
FittedExpression|None best(self)
Return the training winner if any equation was retained.
Definition _search.py:68
Applied search budget and numerical evaluation counts.
Definition _search.py:27
_decode(self, slots, path=())
Definition _search.py:197