Source code for qdpy.symbolic._expression

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Immutable expression trees and vectorized real-valued evaluation.

from dataclasses import dataclass
from math import isfinite
from operator import index

import numpy as np

_OPERATORS = {
    "add": (2, np.add, "+"),
    "sub": (2, np.subtract, "-"),
    "mul": (2, np.multiply, "*"),
    "div": (2, np.divide, "/"),
    "neg": (1, np.negative, "-"),
    "square": (1, np.square, ""),
    "sqrt": (1, np.sqrt, "sqrt"),
    "sin": (1, np.sin, "sin"),
    "cos": (1, np.cos, "cos"),
    "exp": (1, np.exp, "exp"),
    "log": (1, np.log, "log"),
}
_NON_ALGEBRAIC = frozenset(("sin", "cos", "exp", "log"))


## @brief A safe expression tree whose parameter leaves each hold one free scalar.
[docs] @dataclass(frozen=True, order=True, slots=True) class Expression: """Define an immutable equation tree. Leaves are made with :meth:`variable`, :meth:`constant`, and :meth:`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``. """ op: str children: tuple["Expression", ...] = () value: int | float | None = None def __post_init__(self): children = tuple(self.children) object.__setattr__(self, "children", children) if self.op in ("variable", "constant", "parameter"): if children: raise ValueError("Expression leaves cannot have children.") if self.op == "variable": column = index(self.value) if column < 0: raise ValueError("Variable indices must be nonnegative.") object.__setattr__(self, "value", column) elif self.op == "constant": number = float(self.value) if not isfinite(number): raise ValueError("Expression constants must be finite.") object.__setattr__(self, "value", number) elif self.value is not None: raise ValueError("A parameter leaf takes its value from the fitted coefficients.") elif (self.op not in _OPERATORS or self.value is not None or len(children) != _OPERATORS[self.op][0] or not all(isinstance(child, Expression) for child in children)): raise ValueError(f"Invalid expression operation or operands: {self.op!r}.") ## @brief Build a variable leaf from a zero-based input column.
[docs] @classmethod def variable(cls, column: int) -> "Expression": """Return a leaf that reads the given zero-based column of the input.""" return cls("variable", value=column)
## @brief Build a free coefficient leaf.
[docs] @classmethod def parameter(cls) -> "Expression": """Return a free scalar leaf, with a separate coefficient for each occurrence.""" return cls("parameter")
## @brief Build a fixed, finite numeric leaf.
[docs] @classmethod def constant(cls, value: float) -> "Expression": """Return a fixed real-valued leaf.""" return cls("constant", value=value)
## @brief Count all nodes, including leaves. @property def node_count(self) -> int: """Count all operator and terminal occurrences.""" return 1 + sum(child.node_count for child in self.children) ## @brief Count independent parameter slots. @property def parameter_count(self) -> int: """Count free coefficient occurrences.""" return sum(child.parameter_count for child in self.children) + (self.op == "parameter") ## @brief Count trigonometric, exponential and logarithmic nodes. @property def non_algebraic_count(self) -> int: """Count sine, cosine, exponential, and logarithm occurrences.""" return sum(child.non_algebraic_count for child in self.children) + (self.op in _NON_ALGEBRAIC)
def _matrix(data): """Validate finite real inputs with one row per sample and one column per variable.""" values = np.asarray(data) if np.iscomplexobj(values): raise ValueError("X must contain real values.") x = np.asarray(values, dtype=float) if x.ndim != 2 or not all(x.shape) or not np.isfinite(x).all(): raise ValueError("X must be a nonempty, finite (samples, variables) matrix.") return x def _compile(expression): """Build a postfix program and a structurally affine subset of parameter slots.""" program = [] n_parameters = 0 n_variables = 0 def visit(node): nonlocal n_parameters, n_variables op, value = node.op, node.value if op == "parameter": slot = n_parameters n_parameters += 1 program.append((op, slot)) return (slot,) if op == "variable": n_variables = max(n_variables, value + 1) affine = [visit(child) for child in node.children] program.append((op, value)) if op in ("add", "sub"): return affine[0] + affine[1] if op in ("div", "neg"): return affine[0] if op == "mul": # Keep one side affine while treating the other side as fixed. return max(affine, key=len) return () linear = visit(expression) return tuple(program), linear, n_parameters, n_variables def _constant_column(values, width): basis = np.zeros((len(values), width)) basis[:, 0] = values return basis def _evaluate(program, x, coefficients, affine=None): """Interpret the tree in vector form or as [offset, basis] for affine fitting.""" stack = [] with np.errstate(all="ignore"): for op, value in program: if op == "variable": stack.append(x[:, value]) elif op == "constant": stack.append(np.broadcast_to(value, len(x))) elif op == "parameter": if affine and value in affine: basis = np.zeros((len(x), len(affine) + 1)) basis[:, affine[value]] = 1. stack.append(basis) else: stack.append(np.broadcast_to(coefficients[value], len(x))) else: arity, fn, _ = _OPERATORS[op] if arity == 1: result = fn(stack.pop()) else: right, left = stack.pop(), stack.pop() if left.ndim != right.ndim: if op in ("add", "sub"): if left.ndim == 1: left = _constant_column(left, right.shape[1]) else: right = _constant_column(right, left.shape[1]) else: if left.ndim == 1: left = left[:, None] else: right = right[:, None] result = fn(left, right) # Propagate undefined intermediate values, including from overflow. stack.append(np.where(np.isfinite(result), result, np.nan)) return stack[0] def _rmse(predictions, target): if not np.isfinite(predictions).all(): return float("inf") with np.errstate(over="ignore"): errors = np.abs(predictions - target) scale = float(np.max(errors)) if scale == 0.: return 0. if not isfinite(scale): scale = max(float(np.max(np.abs(predictions))), float(np.max(np.abs(target)))) errors = np.abs(predictions / scale - target / scale) else: errors /= scale return scale * float(np.sqrt(np.mean(np.square(errors)))) def _render(expression, coefficients): if expression.op == "variable": return f"x{expression.value}" if expression.op == "constant": return repr(expression.value) if expression.op == "parameter": return repr(next(coefficients)) operands = [_render(child, coefficients) for child in expression.children] arity, _, symbol = _OPERATORS[expression.op] if arity == 2: return f"({operands[0]} {symbol} {operands[1]})" if expression.op == "square": return f"({operands[0]})**2" return f"{symbol}({operands[0]})" ## @brief A fitted expression with independently usable NumPy inference.
[docs] @dataclass(frozen=True, slots=True) class FittedExpression: """Store a tree, its fitted coefficients, and its training RMSE. Coefficients follow the leaf order of :class:`Expression`. Models contain no training data or optimizer state. """ expression: Expression coefficients: tuple[float, ...] training_rmse: float def __post_init__(self): coefficients = tuple(map(float, self.coefficients)) if len(coefficients) != self.expression.parameter_count or not all(map(isfinite, coefficients)): raise ValueError("Supply a finite coefficient for each parameter leaf.") if not isfinite(self.training_rmse) or self.training_rmse < 0.: raise ValueError("The training RMSE must be finite and nonnegative.") object.__setattr__(self, "coefficients", coefficients) ## @brief Format the equation with its fitted coefficients. @property def formula(self) -> str: """Format the fitted expression with variable names x0, x1, and so on.""" return _render(self.expression, iter(self.coefficients)) ## @brief Vectorized evaluation with original operator domains. # @param X Finite sample matrix with one column per variable. # @return One prediction per row, with NaN for each undefined row.
[docs] def predict(self, X) -> np.ndarray: """Predict one value per row. Undefined or overflowing rows return NaN.""" x = _matrix(X) program, _, _, n_variables = _compile(self.expression) if x.shape[1] < n_variables: raise ValueError(f"The expression needs at least {n_variables} input columns.") return _evaluate(program, x, self.coefficients).copy()
## @brief Score the model on a separate labeled dataset. # @param X Finite sample matrix. # @param y One finite target per row. # @return Root mean squared error, or infinity for undefined predictions.
[docs] def rmse(self, X, y) -> float: """Return RMSE on labeled rows, or infinity if any prediction is undefined.""" predictions = self.predict(X) return _rmse(predictions, _target(y, len(predictions)))
def _target(y, n): values = np.asarray(y) if np.iscomplexobj(values): raise ValueError("y must contain real values.") target = np.asarray(values, dtype=float) if target.shape != (n,) or not np.isfinite(target).all(): raise ValueError("y must be a finite vector with one target per input row.") return target