Source code for qdpy.symbolic._search

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Compare MAP-Elites with aggregate and case-wise genetic programming.

from bisect import insort_right
from collections import deque
from dataclasses import dataclass
from functools import lru_cache

import numpy as np
from scipy.cluster.hierarchy import linkage
from sklearn.cluster import KMeans

from qdpy.algorithms.lexicase import _select_casewise, novelty_case_counts
from qdpy.algorithms.optimal_mixing import learn_categorical_linkage
from qdpy.containers import CVTGrid, Grid
from qdpy.phenotype import Features, Fitness, Individual

from ._expression import Expression, FittedExpression, _matrix, _OPERATORS, _target
from ._fit import _Fitter, _integer

_DEFAULT_OPERATORS = ("add", "sub", "mul", "div", "square", "sin", "cos", "exp", "log")


## @brief Applied search budget and numerical evaluation counts.
[docs] @dataclass(frozen=True, slots=True) class SymbolicRegressionStats: """Count tree proposals, unique fits, training evaluations, and probe checks. Invalid fits and invalid probe checks count unique structures. A proposal of a previously fitted structure reuses its outcome. """ proposals: int structures_fitted: int fit_evaluations: int invalid_fits: int probe_evaluations: int invalid_probes: int case_evaluations: int = 0
## @brief Count attempted and accepted linked changes in symbolic regression.
[docs] @dataclass(frozen=True, slots=True) class LinkedSymbolicRegressionStats(SymbolicRegressionStats): """Block trials include revisits whose cached fit is reused.""" block_proposals: int = 0 accepted_blocks: int = 0
## @brief Retained regression models and the native QD archive, if used.
[docs] @dataclass(frozen=True, slots=True) class SymbolicRegressionResult: """Expose retained models in training-error order and the search accounting. The QD archive holds an Individual with one FittedExpression per retained cell. GP mode returns its active population through models. Case-wise modes return the models retained by the passive grid. """ models: tuple[FittedExpression, ...] archive: Grid | None stats: SymbolicRegressionStats ## @brief Return the training winner if any equation was retained. @property def best(self) -> FittedExpression | None: """Return the training winner, or None if no valid candidate was retained.""" return self.models[0] if self.models else None
def _operation(op, children): if op in ("add", "mul"): children = tuple(sorted(children)) return Expression(op, children) def _positions(tree, path=()): yield path, tree for i, child in enumerate(tree.children): yield from _positions(child, (*path, i)) def _replace(tree, path, replacement): if not path: return replacement i, *rest = path children = list(tree.children) children[i] = _replace(children[i], rest, replacement) return _operation(tree.op, tuple(children)) class _Grammar: def __init__(self, n_variables, operators, literals, depth, nodes, parameters, rng): self.nodes = _integer(nodes, "max_nodes", 1) self.depth = min(_integer(depth, "max_depth", 0), self.nodes - 1) self.parameters = _integer(parameters, "max_parameters", 0) self.ops = tuple(dict.fromkeys(operators)) if any(op not in _OPERATORS for op in self.ops): raise ValueError("operators must contain supported Expression operations.") leaves = [Expression.variable(i) for i in range(n_variables)] leaves.extend(Expression.constant(value) for value in literals) if self.parameters: leaves.append(Expression.parameter()) self.leaves = tuple(dict.fromkeys(leaves)) self.rng = rng def choose(self, values): return values[int(self.rng.integers(len(values)))] def grow(self, depth): if depth == 0 or not self.ops or self.rng.random() < .28: return self.choose(self.leaves) op = self.choose(self.ops) return _operation(op, tuple(self.grow(depth - 1) for _ in range(_OPERATORS[op][0]))) def propose(self, pool): draw = self.rng.random() if not len(pool) or draw < .18: tree = self.grow(int(self.rng.integers(self.depth + 1))) else: parent = pool.parent(self.rng).expression path, old = self.choose(tuple(_positions(parent))) available = self.depth - len(path) if draw < .42: donor = pool.parent(self.rng).expression _, subtree = self.choose(tuple(_positions(donor))) elif draw < .62 and available and self.ops: op = self.choose(self.ops) children = [old] if _OPERATORS[op][0] == 2: children.append(self.grow(min(available - 1, 1))) if self.rng.random() < .5: children.reverse() subtree = _operation(op, tuple(children)) elif draw < .72 and old.children: subtree = self.choose(old.children) else: subtree = self.grow(min(available, 2)) tree = _replace(parent, path, subtree) if (tree.node_count <= self.nodes and tree.parameter_count <= self.parameters and all(len(path) <= self.depth for path, _ in _positions(tree))): return tree return self.choose(self.leaves) @lru_cache(maxsize=64) def _template_groups(paths): groups = [(path,) for path in paths] if len(paths) <= 2: return tuple(groups) distances = [] for i, left in enumerate(paths): for right in paths[i + 1:]: common = 0 for a, b in zip(left, right): if a != b: break common += 1 distances.append(len(left) + len(right) - 2 * common) for a, b, _, _ in linkage(distances, method="average")[:-1]: groups.append((*groups[int(a)], *groups[int(b)])) return tuple(groups) def _tree_slots(tree): return {path: node.op if node.children else node for path, node in _positions(tree)} class _TreeMixer: """Probe donor blocks in a sparse shared template of observed positions.""" def __init__(self, grammar, learned): self.grammar, self.learned = grammar, learned self.groups = [] self.trial = None self.probes = self.accepted = 0 def _start(self, pool): rng = self.grammar.rng ids = rng.choice(len(pool), min(len(pool), 24), replace=False) parents = [pool[int(i)] for i in ids] self.parent = parents[0] self.donors = [_tree_slots(model.expression) for model in parents] self.current = self.donors[0] paths = tuple(sorted(set().union(*(row.keys() for row in self.donors)))) if self.learned: alleles = {} samples = [[alleles.setdefault(row.get(path), len(alleles)) for path in paths] for row in self.donors] groups = [tuple(paths[i] for i in block) for block in learn_categorical_linkage(samples)] else: groups = _template_groups(paths) self.groups = [groups[int(i)] for i in rng.permutation(len(groups))] def _decode(self, slots, path=()): node = slots.get(path, self.grammar.leaves[0]) if isinstance(node, Expression): return node return _operation(node, tuple(self._decode(slots, (*path, i)) for i in range(_OPERATORS[node][0]))) def propose(self, pool): rng = self.grammar.rng if len(pool) >= 2 and rng.random() >= .18: if not self.groups: self._start(pool) while self.groups: block = self.groups.pop() possible = [row for row in self.donors if any(path in row and row[path] != self.current.get(path) for path in block)] if not possible: continue donor = self.grammar.choose(possible) trial = self.current | {path: donor[path] for path in block if path in donor} tree = self._decode(trial) if tree == self.parent.expression: self.current = trial elif tree.node_count <= self.grammar.nodes and tree.parameter_count <= self.grammar.parameters: self.trial = trial self.probes += 1 return tree self.groups.clear() return self.grammar.propose(pool) def observe(self, model): if self.trial is not None and model is not None and _fitness(model) <= _fitness(self.parent): self.parent, self.current = model, self.trial self.accepted += 1 self.trial = None def _make_archive(mode, grammar, cells, probes, seed): quality = ((0., np.inf),) if mode == "gp": return None if mode == "structural": shape = grammar.nodes, min(grammar.parameters, grammar.nodes) + 1, grammar.nodes domain = ((.5, shape[0] + .5), (-.5, shape[1] - .5), (-.5, shape[2] - .5)) return Grid(shape=shape, features_domain=domain, fitness_domain=quality) if probes is None: raise ValueError("Semantic MAP-Elites needs fixed, unlabeled probes.") samples = np.random.default_rng(seed).uniform(-1., 1., (max(256, 16 * cells), probes.shape[0])) kmeans = KMeans(n_clusters=cells, n_init=1, random_state=seed).fit(samples) return CVTGrid(shape=cells, centroids=kmeans.cluster_centers_.clip(-1., 1.), features_domain=((-1., 1.),) * probes.shape[0], fitness_domain=quality) class _ModelPool: def __init__(self, archive, population_size): self.archive = archive self.population_size = population_size self.population = [] def __len__(self): return len(self.population if self.archive is None else self.archive) def __getitem__(self, i): if self.archive is None: return self.population[i] return self.archive[i][0] def add(self, model, features): if self.archive is None: insort_right(self.population, model, key=_fitness) if len(self.population) > self.population_size: self.population.pop() else: self.archive.add(Individual([model], fitness=Fitness((model.training_rmse,), weights=(-1.,)), features=Features(features))) def parent(self, rng): return self[int(rng.integers(len(self)))] class _CasePool: """Select from the last nonempty generation and stage its replacements.""" def __init__(self, target, epsilon, *, binner=None, history_size=0, history_rng=None): self.target, self.epsilon = target * .5, epsilon self.models, self.pending, self.errors = [], {}, [] self._binner, self._history_rng = binner, history_rng self._history = deque(maxlen=history_size) self._behaviors = [] def __len__(self): return len(self.models) def parent(self, rng): return self.models[_select_casewise(self.matrix, rng, self.epsilon)] def add(self, model, x): if model.expression not in self.pending: predictions = model.predict(x) errors = np.abs(predictions * .5 - self.target) if self._binner is not None: labels = tuple(self._binner(predictions)) if len(labels) != len(x): raise ValueError("novelty_binner must return one label per training case.") self._behaviors.append(labels) self.pending[model.expression] = model self.errors.append(errors) return 1 return 0 def advance(self): if self.pending: matrix = np.stack(self.errors) if self._binner is not None: counts = novelty_case_counts(self._behaviors, history=self._history) matrix = np.concatenate((matrix, counts), axis=1) if self._history.maxlen: sample = self._behaviors[self._history_rng.integers(len(self._behaviors))] self._history.append(sample) self._behaviors.clear() self.models, self.pending = list(self.pending.values()), {} self.matrix = matrix self.errors.clear() def _fitness(model): return model.training_rmse ## @brief Search for equations using MAP-Elites or genetic programming. # @param X Finite training sample matrix. # @param y One finite training target per row. # @param mode Structural, semantic, gp, lexicase, epsilon-lexicase, or novelty-lexicase. # @param probes Fixed unlabeled sample rows for feasibility and semantic descriptors. # @param budget Number of proposed trees, including duplicates. # @param max_depth Maximum number of edges from root to leaf. # @param max_nodes Maximum number of operator and leaf occurrences in a tree. # @param max_parameters Maximum number of coefficient leaves. # @param operators Allowed Expression operations. # @param literals Fixed numeric terminals in the grammar. # @param cells Number of semantic archive centroids. # @param novelty_binner Optional callable returning hashable groups for training predictions. # @param novelty_history Maximum number of historical output rows used for novelty counts. # @param population_size Maximum GP population size. # @param passive_archive Collect a structural grid while GP selects by aggregate error. # @param nonlinear_bounds Coefficient bounds for the nonlinear optimizer. # @param fit_evaluations Training evaluation cap per unique structure. # @param fit_restarts Number of nonlinear restarts per fit. # @param variation Subtree, template-linkage, or learned-linkage variation. # @param max_fit_evaluations Optional total budget for training-expression evaluations. # @param seed Seed for variation, coefficient fitting, and archive geometry. # @return The retained models, native archive if present, and evaluation counts.
[docs] def symbolic_regression(X, y, *, mode: str = "structural", probes=None, budget: int = 512, max_depth: int = 4, max_nodes: int = 13, max_parameters: int = 4, operators=_DEFAULT_OPERATORS, literals=(1., 2.), cells: int = 24, population_size: int = 24, passive_archive: bool = False, nonlinear_bounds=(-20., 20.), fit_evaluations: int = 48, fit_restarts: int = 4, seed: int | None = None, novelty_binner=None, novelty_history: int = 256, variation="subtree", max_fit_evaluations=None) -> SymbolicRegressionResult: """Fit equations to one labeled training dataset. X has shape (samples, variables) and y has shape (samples,). Each proposal spends one unit of budget, including repeats. Search starts with the variable, literal, and free parameter terminals. Genetic variation uses the supplied operator names, at most max_depth edges, max_nodes nodes, and max_parameters free scalar leaves. Structural MAP-Elites uses node count, free coefficient count, and non-algebraic operator count. Semantic MAP-Elites uses one descriptor coordinate per unlabeled probe row. Predictions are compressed with arctangent at the training target scale, and cells defines the size of its CVT. GP retains population_size candidates by training RMSE. The lexicase modes use generations of population_size proposals and select parents on training cases. They collect a structural grid as a passive archive. Set passive_archive=True to collect the same grid alongside aggregate-error GP. Novelty-lexicase also selects on output rarity. By default it groups predictions in 16 fixed bins after arctangent compression using the training target scale. Pass novelty_binner to map a prediction vector to a sequence of hashable labels, one per training case. It keeps one sampled output row per completed generation, up to novelty_history. For structural or semantic MAP-Elites, template-linkage clusters homologous tree slots by distance in the template. Learned-linkage estimates their dependencies with a masked intron symbol. Both offer each fitted intermediate to the archive and continue the mix from changes that preserve or improve training error. Subtree remains the default. The optional total fit cap stops when fewer than two training evaluations remain. Supply probes with the same number of columns as X. If provided, candidates must give finite predictions on every probe in any mode. Nonlinear bounds, fit_evaluations, and fit_restarts configure coefficient fitting. Validation and test labels belong outside this call. The seed controls variation, fitting, and centroid generation. """ casewise = mode in ("lexicase", "epsilon-lexicase", "novelty-lexicase") if not casewise and mode not in ("structural", "semantic", "gp"): raise ValueError("Choose structural, semantic, gp, lexicase, epsilon-lexicase, or novelty-lexicase.") if (variation not in ("subtree", "template-linkage", "learned-linkage") or variation != "subtree" and mode not in ("structural", "semantic")): raise ValueError("Linked variation requires structural or semantic MAP-Elites.") budget = _integer(budget, "budget", 1) cells = _integer(cells, "cells", 1) population_size = _integer(population_size, "population_size", 1) x = _matrix(X) fitter = _Fitter(x, _target(y, len(x)), nonlinear_bounds, fit_evaluations, fit_restarts) fit_limit = None if max_fit_evaluations is None else _integer(max_fit_evaluations, "max_fit_evaluations", 2) per_fit_limit = fitter.budget if probes is not None: probes = _matrix(probes) if probes.shape[1] != x.shape[1]: raise ValueError("Probes must have the same number of columns as X.") variation_seed, geometry, coefficients = np.random.SeedSequence(seed).spawn(3) grammar = _Grammar(x.shape[1], operators, literals, max_depth, max_nodes, max_parameters, np.random.default_rng(variation_seed)) mixer = None if variation == "subtree" else _TreeMixer(grammar, variation == "learned-linkage") archive_mode = "structural" if casewise or (mode == "gp" and passive_archive) else mode archive = _make_archive(archive_mode, grammar, cells, probes, int(geometry.generate_state(1)[0])) reporter = _ModelPool(archive, population_size) pool = _ModelPool(None, population_size) if mode == "gp" and archive is not None else reporter if mode == "novelty-lexicase": history_size = _integer(novelty_history, "novelty_history", 0) if novelty_binner is None: def novelty_binner(predictions): scaled = np.arctan2(predictions, fitter.scale) / np.pi + .5 return np.minimum((16 * scaled).astype(int), 15) if not callable(novelty_binner): raise TypeError("novelty_binner must be callable.") pool = _CasePool(fitter.y, 0., binner=novelty_binner, history_size=history_size, history_rng=np.random.default_rng(variation_seed.spawn(1)[0])) elif casewise: pool = _CasePool(fitter.y, "mad" if mode == "epsilon-lexicase" else 0.) seen = set() fitted_models = {} if casewise or mixer is not None else None fit_calls = invalid_fits = probe_calls = invalid_probes = case_calls = 0 proposals = 0 propose = grammar.propose if mixer is None else mixer.propose for i in range(budget): if fit_limit is not None: remaining = fit_limit - fit_calls if remaining < 2: break fitter.budget = min(per_fit_limit, remaining) proposals += 1 if casewise and i % population_size == 0: pool.advance() tree = grammar.leaves[i] if i < len(grammar.leaves) else propose(pool) if tree in seen: if casewise and tree in fitted_models: case_calls += pool.add(fitted_models[tree], x) if mixer is not None: mixer.observe(fitted_models.get(tree)) continue seen.add(tree) fit = fitter.fit(tree, coefficients) fit_calls += fit.evaluations if fit.model is None: invalid_fits += 1 if mixer is not None: mixer.observe(None) continue features = (tree.node_count, tree.parameter_count, tree.non_algebraic_count) if probes is not None: probe_calls += 1 predictions = fit.model.predict(probes) if not np.isfinite(predictions).all(): invalid_probes += 1 if mixer is not None: mixer.observe(None) continue if mode == "semantic": features = (2. / np.pi) * np.arctan2(predictions, fitter.scale) reporter.add(fit.model, features) if fitted_models is not None: fitted_models[tree] = fit.model if mixer is not None: mixer.observe(fit.model) if casewise: case_calls += pool.add(fit.model, x) elif pool is not reporter: pool.add(fit.model, features) counts = proposals, len(seen), fit_calls, invalid_fits, probe_calls, invalid_probes, case_calls stats = (SymbolicRegressionStats(*counts) if mixer is None else LinkedSymbolicRegressionStats(*counts, mixer.probes, mixer.accepted)) models = tuple(sorted(reporter if casewise else pool, key=_fitness)) return SymbolicRegressionResult(models, archive, stats)