5from bisect
import insort_right
6from collections
import deque
7from dataclasses
import dataclass
8from functools
import lru_cache
11from scipy.cluster.hierarchy
import linkage
12from sklearn.cluster
import KMeans
19from ._expression
import Expression, FittedExpression, _matrix, _OPERATORS, _target
20from ._fit
import _Fitter, _integer
22_DEFAULT_OPERATORS = (
"add",
"sub",
"mul",
"div",
"square",
"sin",
"cos",
"exp",
"log")
26@dataclass(frozen=True, slots=True)
28 """Count tree proposals, unique fits, training evaluations, and probe checks.
30 Invalid fits and invalid probe checks count unique structures.
31 A proposal of a previously fitted structure reuses its outcome.
35 structures_fitted: int
38 probe_evaluations: int
40 case_evaluations: int = 0
44@dataclass(frozen=True, slots=True)
46 """Block trials include revisits whose cached fit is reused."""
48 block_proposals: int = 0
49 accepted_blocks: int = 0
53@dataclass(frozen=True, slots=True)
55 """Expose retained models in training-error order and the search accounting.
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.
62 models: tuple[FittedExpression, ...]
64 stats: SymbolicRegressionStats
68 def best(self) -> FittedExpression | None:
69 """Return the training winner, or None if no valid candidate was retained."""
73def _operation(op, children):
74 if op
in (
"add",
"mul"):
75 children = tuple(sorted(children))
79def _positions(tree, path=()):
81 for i, child
in enumerate(tree.children):
82 yield from _positions(child, (*path, i))
85def _replace(tree, path, replacement):
89 children = list(tree.children)
90 children[i] = _replace(children[i], rest, replacement)
91 return _operation(tree.op, tuple(children))
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)
105 leaves.append(Expression.parameter())
106 self.
leaves = tuple(dict.fromkeys(leaves))
109 def choose(self, values):
110 return values[int(self.
rng.integers(len(values)))]
112 def grow(self, depth):
113 if depth == 0
or not self.
ops or self.
rng.random() < .28:
116 return _operation(op, tuple(self.
grow(depth - 1)
for _
in range(_OPERATORS[op][0])))
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)))
123 parent = pool.parent(self.
rng).expression
124 path, old = self.
choose(tuple(_positions(parent)))
125 available = self.
depth - len(path)
127 donor = pool.parent(self.
rng).expression
128 _, subtree = self.
choose(tuple(_positions(donor)))
129 elif draw < .62
and available
and self.
ops:
132 if _OPERATORS[op][0] == 2:
133 children.append(self.
grow(min(available - 1, 1)))
134 if self.
rng.random() < .5:
136 subtree = _operation(op, tuple(children))
137 elif draw < .72
and old.children:
138 subtree = self.
choose(old.children)
140 subtree = self.
grow(min(available, 2))
141 tree = _replace(parent, path, subtree)
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))):
149@lru_cache(maxsize=64)
150def _template_groups(paths):
151 groups = [(path,)
for path
in paths]
155 for i, left
in enumerate(paths):
156 for right
in paths[i + 1:]:
158 for a, b
in zip(left, right):
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)]))
168def _tree_slots(tree):
169 return {path: node.op
if node.children
else node
for path, node
in _positions(tree)}
173 """Probe donor blocks in a sparse shared template of observed positions."""
175 def __init__(self, grammar, learned):
179 self.
probes = self.accepted = 0
181 def _start(self, pool):
183 ids = rng.choice(len(pool), min(len(pool), 24), replace=
False)
184 parents = [pool[int(i)]
for i
in ids]
186 self.
donors = [_tree_slots(model.expression)
for model
in parents]
188 paths = tuple(sorted(set().union(*(row.keys()
for row
in self.
donors))))
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)]
194 groups = _template_groups(paths)
195 self.
groups = [groups[int(i)]
for i
in rng.permutation(len(groups))]
197 def _decode(self, slots, path=()):
198 node = slots.get(path, self.
grammar.leaves[0])
199 if isinstance(node, Expression):
201 return _operation(node, tuple(self.
_decode(slots, (*path, i))
for i
in range(_OPERATORS[node][0])))
203 def propose(self, pool):
205 if len(pool) >= 2
and rng.random() >= .18:
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)]
214 donor = self.
grammar.choose(possible)
215 trial = self.
current | {path: donor[path]
for path
in block
if path
in donor}
217 if tree == self.
parent.expression:
219 elif tree.node_count <= self.
grammar.nodes
and tree.parameter_count <= self.
grammar.parameters:
224 return self.
grammar.propose(pool)
226 def observe(self, model):
227 if self.
trial is not None and model
is not None and _fitness(model) <= _fitness(self.
parent):
233def _make_archive(mode, grammar, cells, probes, seed):
234 quality = ((0., np.inf),)
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)
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)
251 def __init__(self, archive, population_size):
259 def __getitem__(self, i):
264 def add(self, model, features):
266 insort_right(self.
population, model, key=_fitness)
273 def parent(self, rng):
274 return self[int(rng.integers(len(self)))]
278 """Select from the last nonempty generation and stage its replacements."""
280 def __init__(self, target, epsilon, *, binner=None, history_size=0, history_rng=None):
284 self.
_history = deque(maxlen=history_size)
290 def parent(self, rng):
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)
298 labels = tuple(self.
_binner(predictions))
299 if len(labels) != len(x):
300 raise ValueError(
"novelty_binner must return one label per training case.")
302 self.
pending[model.expression] = model
303 self.
errors.append(errors)
309 matrix = np.stack(self.
errors)
312 matrix = np.concatenate((matrix, counts), axis=1)
323 return model.training_rmse
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.
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.
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.
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.
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.
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.
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)
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.")
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]))
432 pool =
_CasePool(fitter.y,
"mad" if mode ==
"epsilon-lexicase" else 0.)
434 fitted_models = {}
if casewise
or mixer
is not None else None
435 fit_calls = invalid_fits = probe_calls = invalid_probes = case_calls = 0
437 propose = grammar.propose
if mixer
is None else mixer.propose
439 for i
in range(budget):
440 if fit_limit
is not None:
441 remaining = fit_limit - fit_calls
444 fitter.budget = min(per_fit_limit, remaining)
446 if casewise
and i % population_size == 0:
448 tree = grammar.leaves[i]
if i < len(grammar.leaves)
else propose(pool)
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))
456 fit = fitter.fit(tree, coefficients)
457 fit_calls += fit.evaluations
458 if fit.model
is None:
460 if mixer
is not None:
464 features = (tree.node_count, tree.parameter_count, tree.non_algebraic_count)
465 if probes
is not None:
467 predictions = fit.model.predict(probes)
468 if not np.isfinite(predictions).all():
470 if mixer
is not None:
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)
481 case_calls += pool.add(fit.model, x)
482 elif pool
is not reporter:
483 pool.add(fit.model, features)
485 counts = proposals, len(seen), fit_calls, invalid_fits, probe_calls, invalid_probes, case_calls
488 models = tuple(sorted(reporter
if casewise
else pool, key=_fitness))
:param obj: Slice indicating on which objectives the domination is tested.
A safe expression tree whose parameter leaves each hold one free scalar.
Count attempted and accepted linked changes in symbolic regression.
Retained regression models and the native QD archive, if used.
FittedExpression|None best(self)
Return the training winner if any equation was retained.
Applied search budget and numerical evaluation counts.
_decode(self, slots, path=())