Discovering Equations from Data with PythonSymbolic regression, genetic programming and the eqdisco toolbox

Appendix A
API reference

This appendix lists every public class and function of eqdisco, module by module, with the first sentence of its docstring. The lists are generated from the __all__ attribute of each module by book/build_api_appendix.py, so they are complete by construction; the full signatures, parameters, and attributes are in the online documentation and in the docstrings (help(eqdisco.GPOLSRegressor)). The conventions of the API are described in section 1.5, the notation in table 1.1.

A.1 eqdisco.expr: Expressions and primitives

Name

Kind

Description

FUNC

constant

Node kind of a function (operator) node

VAR

constant

Node kind of a variable (terminal) node

CONST

constant

Node kind of a constant node

Primitive

class

A function node of an expression

PRIMITIVES

constant

Registry of the built-in primitives by name

DEFAULT_FUNCTIONS

constant

Default function set of the tree-based estimators

Node

class

One node of a prefix expression

PrimitiveSet

class

Function and terminal sets of a search

Expression

class

A symbolic expression stored as a prefix sequence of Node

register_primitive

function

Add a user-defined primitive to the registry (used by parsing and JSON loading)

subtree_end

function

Index one past the last node of the subtree rooted at nodes[start]

check_safe_text

function

Reject text that is not a plain arithmetic expression over known names

A.2 eqdisco.equation: Fitted equations

Name

Kind

Description

Equation

class

A symbolic model ŷ = f(x; 𝜃)

scaled_expression

function

Build a + bf as one expression; trivial terms are omitted

regression_metrics

function

MSE, RMSE, MAE, R2, AIC and BIC of a prediction with k parameters

A.3 eqdisco.fitness: Losses, complexity and information criteria

Name

Kind

Description

mse

function

Mean squared error 1 N ∑ ⁡ k(yk −ŷk)2

rmse

function

Root mean squared error

nmse

function

MSE normalized by the variance of y (1 for the constant mean model)

mae

function

Mean absolute error

r2

function

Coefficient of determination R2 = 1 −SSE∕SST

max_error

function

Largest absolute residual

huber

function

Huber loss; delta defaults to 1.345 times the MAD of y (robust regression)

log_loss

function

Binary cross-entropy of probabilities p for labels y in {0, 1}

misclassification

function

Share of wrongly classified samples (labels compared directly)

balanced_error

function

One minus the balanced accuracy (mean recall over the classes)

LOSSES

constant

Registry of the loss functions by name

get_loss

function

Resolve a loss given by name or as a callable loss(y, yhat, sample_weight)

complexity

function

Complexity C(f) of an expression

COMPLEXITY_KINDS

constant

Names of the complexity measures

gaussian_loglik

function

Maximized Gaussian log-likelihood for residual sum of squares rss

aic

function

Akaike information criterion 2k −2 ln ⁡ L^ (Gaussian errors)

aicc

function

AIC with the small-sample correction of Hurvich and Tsai

bic

function

Bayesian information criterion kln ⁡ N −2 ln ⁡ L^ (Gaussian errors)

information_criterion

function

"aic", "aicc" or "bic" of a prediction with k parameters

description_length

function

Two-part description length (in nats) of data and model

per_case_errors

function

Absolute errors per sample (the cases of lexicase selection); inf if invalid

A.4 eqdisco.optimize: Parameter estimation

Name

Kind

Description

linear_scaling

function

Optimal intercept a and slope b of a + bf in least squares

lstsq

function

Least-squares weights of a linear-in-parameters model

FitResult

class

Result of fit_parameters

fit_parameters

function

Nonlinear least-squares estimate of the parameters 𝜃

jacobian_rank

function

Numerical rank of the Jacobian ∂f∕∂𝜃 on X

redundant_parameters

function

Indices of parameters that can be removed without reducing the Jacobian rank

A.5 eqdisco.ols: Orthogonal least squares

Name

Kind

Description

OLSResult

class

Result of ols_err and forward_ols

ols_err

function

ERR of every regressor, orthogonalized in a given order (modified Gram–Schmidt)

forward_ols

function

Forward regression with orthogonal least squares (FROLS)

A.6 eqdisco.generate: Initialization of trees

Name

Kind

Description

grow

function

Grow method: functions and terminals mixed until max_depth

full

function

Full method: every leaf at depth depth

ramped_half_and_half

function

n expressions, half grow and half full, depths ramped over [min_depth, max_depth]

ptc2

function

PTC2: a random tree with about target_size nodes (Luke, 2000)

random_expression

function

Convenience wrapper: method is "grow", "full" or "ptc2" (then max_depth is the size)

A.7 eqdisco.variation: Variation operators

Name

Kind

Description

choose_node

function

Index of a random node; an internal node with probability p_internal

within_limits

function

True if the expression respects the depth and size limits

subtree_crossover

function

Child of p1 with a random subtree replaced by a random subtree of p2

subtree_mutation

function

Replace a random subtree by a grown tree of depth at most max_depth

point_mutation

function

Replace every node with probability rate (default 1/size, at least one node)

hoist_mutation

function

Replace a random subtree by one of its own subtrees (Kinnear’s hoist)

shrink_mutation

function

Replace a random internal subtree by a terminal

insert_mutation

function

Insert a random function above a random subtree (the subtree becomes one argument)

constant_mutation

function

Multiply parameters by 1 + σ𝜖 and add σ𝜖′, 𝜖,𝜖′ ∼N(0,1)

semantic_crossover

function

Semantic similarity-based crossover (SSC) of Uy et al. (2011)

A.8 eqdisco.selection: Selection and survival

Name

Kind

Description

tournament

function

Indices of n winners of tournaments of size k (smaller fitness wins)

double_tournament

function

Double tournament: the smaller of two fitness-tournament winners wins with probability d/2

epsilon_lexicase

function

𝜀-lexicase selection

nondominated_sort

function

Fast non-dominated sorting: list of fronts (index arrays), best front first

crowding_distance

function

Crowding distance of the members of one front (boundary points get infinity)

nsga2_survivors

function

Elitist NSGA-II environmental selection of n rows of F

crowded_tournament

function

Binary (or k-ary) tournament on (rank, -crowding) as in NSGA-II

pareto_mask

function

Boolean mask of the non-dominated rows of F (all objectives minimized)

A.9 eqdisco.models: Estimators

Name

Kind

Description

SymbolicRegressor

class

Genetic programming for symbolic regression

SymbolicClassifier

class

Genetic programming for classification by a symbolic decision function

logistic_scaling

function

Intercept and slope of P(t = 1) = σ(a + bf) by Newton–Raphson (1-D logistic regression)

MultiGeneRegressor

class

Multi-gene genetic programming (MGGP) for symbolic regression

GPOLSRegressor

class

GP-OLS: genetic programming with orthogonal-least-squares pruning (Madár et al., 2005)

SymbolicTransformer

class

Evolve k explicit features zj = Fj(x) for a goal

Genes

class

An immutable list of gene trees (a multi-gene individual)

split_terms

function

Split an expression at its top-level add/sub/neg nodes

CooperativeOLSRegressor

class

Cooperative GP whose population is a library of terms selected by OLS (new in eqdisco)

SparseRegressor

class

Sparse regression over a library of candidate terms

FFXRegressor

class

Fast Function Extraction (FFX; McConaghy, 2011)

polynomial_library

function

All monomials of total degree 1..degree (without the constant)

function_library

function

Unary functions applied to every variable: g(xj)

hinge_library

function

Hinge functions max ⁡ (0,xj −t) and max ⁡ (0,t −xj) at quantile knots

make_library

function

Polynomial terms, unary functions of the variables and (optionally) hinges

library_matrix

function

Regressor matrix Θ(X): one column per term

stlsq

function

Sequentially thresholded least squares (Brunton, Proctor and Kutz, 2016)

ExhaustiveRegressor

class

Exhaustive symbolic regression with description-length ranking

BayesianSymbolicRegressor

class

Posterior sampling of model structures by Metropolis moves with parallel tempering

GrammarCERegressor

class

Risk-seeking cross-entropy search over a probabilistic expression grammar

enumerate_expressions

function

All canonical expressions with at most max_size nodes

LLMGuidedRegressor

class

Iterative equation discovery with a proposer (LLM or templates) and constant fitting

SymbolicEnsemble

class

Bootstrap ensemble of any eqdisco regressor

A.10 eqdisco.llm: Language-model proposals

Name

Kind

Description

build_prompt

function

Prompt that asks for n new candidate equations

parse_proposals

function

Parse an answer into expressions; constants c0, c1,

propose_expressions

function

Ask the proposer for n expressions and fit their parameters; failures give an empty list

TemplateProposer

class

Offline proposer that answers with templates (no language model)

LLMGuidedRegressor

class

Iterative equation discovery with a proposer (LLM or templates) and constant fitting

A.11 eqdisco.dynamics: Dynamic systems

Name

Kind

Description

lagged_regressors

function

Regressor matrix of a NARX model

NARXRegressor

class

NARX model identified by any eqdisco regressor

narx_order_scan

function

Model order selection: FROLS on a polynomial NARX library for every (na,nb)

derivative

function

Time derivative of sampled signals

ODEModel

class

A system of identified ODEs żi = gi(z,u)

SINDy

class

Sparse identification of nonlinear dynamics (Brunton, Proctor and Kutz, 2016)

SymbolicODE

class

ODE identification with any symbolic regressor, one state equation at a time

simulate_ode

function

Integrate z˙ = g(z[,u]) with solve_ivp

A.12 eqdisco.knowledge: Domain knowledge

Name

Kind

Description

Unit

class

Exponents of the SI base units; supports *, / and **

parse_unit

function

Parse a unit such as "kg*m/s^2", "1/s", "N" or "1" (dimensionless)

check_units

function

Dimensional analysis of an equation

unit_violations

function

Number of dimensional violations (used as a penalty by the search)

buckingham_pi

function

Dimensionless groups of the variables (Buckingham Π theorem)

dimensionless_features

function

Values of the dimensionless groups Πk = ∏ ⁡ jxjakj from data

ShapeConstraint

class

A constraint on the model or on one of its partial derivatives

check_constraints

function

Share of the domain where each constraint is violated

constraint_violation

function

Mean share of the domain where the constraints fail (0 = all satisfied)

fit_surrogate

function

Smooth neural-network surrogate of the data (standardized inputs and output)

separability

function

Relative violation of separability between group_a and the other variables

interaction_matrix

function

Pairwise interaction strength: separability of variable i from j with the others fixed

symmetry_tests

function

Translational and scaling symmetries of every pair of variables

suggest_structure

function

Plain-language list of the separabilities and symmetries detected (threshold tol)

A.13 eqdisco.simplify: Simplification

Name

Kind

Description

fold_constants

function

Replace every subtree without variables by its value (a parameter if it contained one)

apply_rules

function

Rewrite to a fixed point: constant folding, identities, cancellation and parameter merging

merge_parameters

function

Merge the parameters of every addition chain and multiplication chain into one

simplify_sympy

function

SymPy simplification, kept only if it is not larger and (on X) evaluates to the same values

round_coefficients

function

Round all parameters to the fewest significant digits that keep the MSE within (1+tolerance)

simplify

function

Simplification pipeline: rules, optional SymPy, optional refit and rounding

canonical_form

function

Canonical string (SymPy simplified, rounded coefficients) for comparing models

A.14 eqdisco.analysis: Model analysis

Name

Kind

Description

pareto_front_indices

function

Indices of the non-dominated points (both objectives minimized), by increasing complexity

pareto_front

function

Non-dominated equations by (error, size); the error is recomputed on (X, y) if given

knee_index

function

Knee of a front: the point farthest below the line joining its two extremes

hypervolume_2d

function

Area dominated by the front and bounded by the reference point ref

select_model

function

Choose one equation from a list (typically a Pareto front)

SELECTION_RULES

constant

Names of the model selection rules on a Pareto front

front_table

function

Table of a list of equations: complexity, parameters, MSE, R2, BIC and the formula

cross_validate_search

function

k-fold cross-validation of an equation search

extrapolation_split

function

Split by the value of one variable: samples above the quantile are the test set

residual_diagnostics

function

Statistical tests of the residuals e = y −ŷ

term_table

function

Additive terms of an equation with their weights, ERR and unique contributions

learning_curve

function

Train and test R2 and equation size for growing training sets

structure_agreement

function

Mean pairwise Jaccard similarity of the building-block sets of the equations (1 = same structure)

parameter_covariance

function

Asymptotic covariance of the parameters and the residual variance σ^2

confidence_intervals

function

Confidence intervals of the parameters

prediction_intervals

function

Delta-method intervals of the model output at X_new

partial_derivatives

function

SymPy expressions of ∂f∕∂xj for the variables of the equation

local_sensitivity

function

Derivative-based sensitivities averaged over the samples X

sobol_indices

function

First-order and total Sobol indices on independent uniform inputs

permutation_importance

function

Mean and standard deviation of the MSE increase when each variable is permuted

canonical_subtree

function

Canonical string of the subtree at i: parameters become c, commutative arguments are sorted

subtree_counts

function

Number of models that contain each canonical subtree of min_size..max_size nodes

frequent_building_blocks

function

Subtrees contained in at least min_support share of the models

building_block_network

function

Co-occurrence network of the frequent building blocks

variable_interaction_network

function

Variables linked by their joint occurrence inside nonlinear subtrees

mine_library

function

Frequent building blocks as expressions with free parameters (library learning)

semantic_distance_matrix

function

Pairwise distances of the models’ predictions on X

model_families

function

Cluster equations into families of (nearly) equivalent models

family_map

function

2-D coordinates of the models: metric MDS (SMACOF) of the semantic distances

A.15 eqdisco.viz: Static visualizations

Name

Kind

Description

BRAND

constant

Pannon blue of the figures (#285780)

OKABE_ITO

constant

The Okabe–Ito color-blind-safe palette

PALETTE

constant

Fixed colors of node kinds and figure elements

plot_tree

function

Draw an expression tree: functions blue, variables green, parameters orange

plot_pareto

function

Error–complexity front; the selected model is highlighted

plot_convergence

function

Best (and median) loss per generation; mean program size on a second axis

plot_parity

function

Predicted against measured values with the identity line and R2

plot_residuals

function

Two panels: residuals against fitted values, and a normal Q–Q plot

plot_partial_dependence

function

Response curves of the model along each variable (others at sampled values)

plot_sensitivity

function

Horizontal bars of a sensitivity table (local_sensitivity)

plot_sobol

function

First-order and total Sobol indices side by side

plot_terms

function

Bars of the error reduction ratios (or unique contributions) of the additive terms

plot_err_path

function

Cumulative ERR along a forward OLS selection (forward_ols)

plot_building_blocks

function

Co-occurrence network of building blocks: node area ~ support, edge width ~ lift

plot_variable_interactions

function

Variable interaction network: node area ~ usage, edge width ~ interaction frequency

plot_families

function

Dendrogram of the semantic distances and the map of the model families

plot_simulation

function

Measured and simulated (or predicted) trajectories

plot_phase_portrait

function

Phase portrait of measured and model trajectories

plot_equation

function

Typeset an equation with matplotlib mathtext (falls back to plain text)

plot_prediction_band

function

Model curve with an uncertainty band over one input variable

plot_interaction_matrix

function

Heat map of a pairwise interaction or separability matrix

plot_posterior

function

Posterior probabilities (or sample shares, column="share") of the most probable structures

plot_benchmark

function

Box plots of a benchmark metric per method (run_benchmark)

plot_compare_convergence

function

Convergence of several runs or methods on common axes ({name: history})

plot_drift

function

Population stability index per variable and the share of samples outside the training box

plot_dashboard

function

One-page report of a fitted search: equation, tree, Pareto front, parity and convergence

A.16 eqdisco.interactive: Interactive figures

Name

Kind

Description

pareto_figure

function

Plotly scatter of the Pareto front; hover shows the equation

response_surface

function

3-D surface of the equation over variables i and j (others at their medians)

convergence_figure

function

Best and median loss per generation

A.17 eqdisco.export: Code generation and PMML

Name

Kind

Description

sanitize_names

function

Valid, unique identifiers for the variable names (y(k-1) becomes y_k_1)

to_python

function

Python source (math for scalars, NumPy for arrays with numpy=True)

to_numpy_function

function

A NumPy-vectorized callable f(X) built with lambdify (no code is executed from text)

to_c

function

C source of a function double f(double x0, ...)

to_matlab

function

MATLAB/Octave function file (element-wise operators)

to_julia

function

Julia one-line function

to_excel

function

Excel formula with the variables replaced by cell references ({"T": "A2"} or a list)

to_latex

function

LaTeX equation lhs =

to_pmml

function

PMML 4.4 document of the equation

to_code

function

Source code of a function name that evaluates the equation in language lang

A.18 eqdisco.mlops: Registry, model cards, tracking and monitoring

Name

Kind

Description

fingerprint

function

SHA-256 fingerprint (first 16 hex digits) of the data

environment_info

function

Versions of Python, eqdisco and its main dependencies

ModelRegistry

class

File-based registry of versioned equations

ModelCard

class

Documentation of a discovered equation

RunTracker

class

Log parameters, metrics and equations of search runs

DriftMonitor

class

Monitor the inputs and residuals of a deployed equation

population_stability_index

function

PSI of a variable between reference and new samples (quantile bins of the reference)

psi_critical_value

function

Value that the PSI of two samples of one distribution exceeds with probability 1 - level

A.19 eqdisco.datasets: Data sets and benchmark problems

Name

Kind

Description

Problem

class

A benchmark problem with training and test data and its ground truth

get_problem

function

A benchmark problem by name

list_problems

function

Names of the problems; kind filters by prefix ("nguyen", "feynman", ...)

PROBLEMS

constant

Names of the bundled benchmark problems

FEYNMAN

constant

Feynman equations with variable ranges and SI units

load_kepler

function

Semi-major axis (AU) and sidereal orbital period (years) of the eight planets

make_runaway

function

Synthetic thermal-runaway data labeled by the Semenov criterion

make_regression_problem

function

A problem from any formula (string over feature_names), sampled uniformly

lorenz

function

Lorenz system ẋ = σ(y−x),ẏ = x(ρ−z)−y,ż = xy−βz

van_der_pol

function

Van der Pol oscillator ẋ = y,ẏ = μ(1 −x2)y −x

lotka_volterra

function

Predator–prey model ẋ = ax −bxy,ẏ = dxy −cy

duffing

function

Unforced Duffing oscillator ẋ = y,ẏ = −δy −αx −βx3

pendulum

function

Damped pendulum φ˙ = ω,ω˙ = −(g∕l) sin ⁡ φ −cω

narendra_parthasarathy

function

NARX benchmark y(k + 1) = y(k) 1 + y(k)2 + u(k)3 (Narendra and Parthasarathy, 1990)

A.20 eqdisco.benchmarks: Benchmark runner

Name

Kind

Description

is_symbolic_solution

function

True if found - truth is constant or found / truth is a nonzero constant

run_benchmark

function

Run {name: estimator} on the named problems with n_runs seeds each

summarize

function

Per method: median test R2, median size, solution rate and median time