Symbolic regression API

See Symbolic regression with MAP-Elites for worked examples.

Evolve analytical expressions with MAP-Elites or case-wise parent selection.

class qdpy.symbolic.CoefficientFit(model: FittedExpression | None, evaluations: int)[source]

Report a fitted model or None if no finite fit was found within the budget.

class qdpy.symbolic.Expression(op: str, children: tuple[Expression, ...] = (), value: int | float | None = None)[source]

Define an immutable equation tree.

Leaves are made with variable(), constant(), and parameter(). Each parameter leaf occupies a separate slot in left-to-right traversal order, even if the same leaf object is reused.

For an operation, supply its name and its children. Binary operations are add, sub, mul, and div. Unary operations are neg, square, sqrt, sin, cos, exp, and log.

classmethod constant(value: float) → Expression[source]

Return a fixed real-valued leaf.

property node_count: int

Count all operator and terminal occurrences.

property non_algebraic_count: int

Count sine, cosine, exponential, and logarithm occurrences.

classmethod parameter() → Expression[source]

Return a free scalar leaf, with a separate coefficient for each occurrence.

property parameter_count: int

Count free coefficient occurrences.

classmethod variable(column: int) → Expression[source]

Return a leaf that reads the given zero-based column of the input.

class qdpy.symbolic.FittedExpression(expression: Expression, coefficients: tuple[float, ...], training_rmse: float)[source]

Store a tree, its fitted coefficients, and its training RMSE.

Coefficients follow the leaf order of Expression. Models contain no training data or optimizer state.

property formula: str

Format the fitted expression with variable names x0, x1, and so on.

predict(X) → ndarray[source]

Predict one value per row. Undefined or overflowing rows return NaN.

rmse(X, y) → float[source]

Return RMSE on labeled rows, or infinity if any prediction is undefined.

class qdpy.symbolic.LinkedSymbolicRegressionStats(proposals: int, structures_fitted: int, fit_evaluations: int, invalid_fits: int, probe_evaluations: int, invalid_probes: int, case_evaluations: int = 0, block_proposals: int = 0, accepted_blocks: int = 0)[source]

Block trials include revisits whose cached fit is reused.

class qdpy.symbolic.ResidualSymbolicElite(expression: Expression, model: FittedExpression, loss: float, outlier_cluster: int)[source]

The fitted model predicts using its weighted expression tree.

class qdpy.symbolic.ResidualSymbolicResult(elites: tuple[ResidualSymbolicElite, ...], archive: Grid, groups: tuple[int, ...], stats: ResidualSymbolicStats)[source]

Each retained row records the group’s original integer label.

property best

Return the lowest-loss elite, or None for an empty archive.

class qdpy.symbolic.ResidualSymbolicStats(proposals: int, coefficient_evaluations: int, invalid_evaluations: int, archive_updates: int)[source]

Coefficient evaluations include each initial setting and all CMA-ES trials.

class qdpy.symbolic.SymbolicRegressionResult(models: tuple[FittedExpression, ...], archive: Grid | None, stats: SymbolicRegressionStats)[source]

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.

property best: FittedExpression | None

Return the training winner, or None if no valid candidate was retained.

class qdpy.symbolic.SymbolicRegressionStats(proposals: int, structures_fitted: int, fit_evaluations: int, invalid_fits: int, probe_evaluations: int, invalid_probes: int, case_evaluations: int = 0)[source]

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.

qdpy.symbolic.fit_expression(expression: Expression, X, y, *, nonlinear_bounds=(-20., 20.), max_evaluations: int = 48, restarts: int = 4, seed: int | None = None) → CoefficientFit[source]

Fit an expression’s free scalars on one finite data matrix.

X has shape (samples, variables) and y has one real target per row. Solve the structurally affine coefficients together by SVD least squares. For mixed expressions, repeat that solve inside a bounded SciPy least-squares search over the remaining coefficients (variable projection). Bounds apply only to nonlinear coefficients.

The evaluation limit includes finite differences and the final check in the original expression. Restarts divide that budget between starting points. The seed controls randomized start locations. A missing model indicates that the fit found no finite solution on all training rows within the budget. Nonlinear fitting can terminate at a local optimum.

qdpy.symbolic.residual_symbolic_regression(X, y, *, groups=None, clusters=4, loss='medae', layout='residual', budget=128, fit_evaluations=25, max_fit_evaluations=None, max_depth=4, max_nodes=12, operators=('add', 'sub', 'mul', 'div', 'log', 'exp'), literals=(1.,), coefficient_bounds=(-12., 12.), fit_sigma=.6, cma_population=6, initial_expressions=(), seed=0)[source]

Run DRSR on labeled training data with an optional structural control.

The archive indexes the group with highest mean absolute error, raw tree size, and raw non-algebraic operator count. With layout="structural", the same search drops the group axis from competition. Choose mae, medae (median absolute error) or rmse as the optimization loss. The model’s RMSE is recorded independently. If supplied, the rows’ integer group labels take precedence over the default k-means clustering of scaled X and y.

Each raw tree gains one multiplicative weight per node. Constant folding reuses the native expression evaluator. Bounded CMA-ES trials require the existing cma extra. Undefined predictions consume a trial. Every finite trial can enter the archive, including lower-ranked coefficients that represent a different residual niche.

qdpy.symbolic.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[source]

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.