QDpy
Loading...
Searching...
No Matches
_expression.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5from dataclasses import dataclass
6from math import isfinite
7from operator import index
8
9import numpy as np
10
11_OPERATORS = {
12 "add": (2, np.add, "+"),
13 "sub": (2, np.subtract, "-"),
14 "mul": (2, np.multiply, "*"),
15 "div": (2, np.divide, "/"),
16 "neg": (1, np.negative, "-"),
17 "square": (1, np.square, ""),
18 "sqrt": (1, np.sqrt, "sqrt"),
19 "sin": (1, np.sin, "sin"),
20 "cos": (1, np.cos, "cos"),
21 "exp": (1, np.exp, "exp"),
22 "log": (1, np.log, "log"),
23}
24_NON_ALGEBRAIC = frozenset(("sin", "cos", "exp", "log"))
25
26
27
28@dataclass(frozen=True, order=True, slots=True)
30 """Define an immutable equation tree.
31
32 Leaves are made with :meth:`variable`, :meth:`constant`, and
33 :meth:`parameter`. Each parameter leaf occupies a separate slot in
34 left-to-right traversal order, even if the same leaf object is reused.
35
36 For an operation, supply its name and its children. Binary operations
37 are ``add``, ``sub``, ``mul``, and ``div``. Unary operations are
38 ``neg``, ``square``, ``sqrt``, ``sin``, ``cos``, ``exp``, and ``log``.
39 """
40
41 op: str
42 children: tuple["Expression", ...] = ()
43 value: int | float | None = None
44
45 def __post_init__(self):
46 children = tuple(self.children)
47 object.__setattr__(self, "children", children)
48 if self.op in ("variable", "constant", "parameter"):
49 if children:
50 raise ValueError("Expression leaves cannot have children.")
51 if self.op == "variable":
52 column = index(self.value)
53 if column < 0:
54 raise ValueError("Variable indices must be nonnegative.")
55 object.__setattr__(self, "value", column)
56 elif self.op == "constant":
57 number = float(self.value)
58 if not isfinite(number):
59 raise ValueError("Expression constants must be finite.")
60 object.__setattr__(self, "value", number)
61 elif self.value is not None:
62 raise ValueError("A parameter leaf takes its value from the fitted coefficients.")
63 elif (self.op not in _OPERATORS or self.value is not None
64 or len(children) != _OPERATORS[self.op][0]
65 or not all(isinstance(child, Expression) for child in children)):
66 raise ValueError(f"Invalid expression operation or operands: {self.op!r}.")
67
68
69 @classmethod
70 def variable(cls, column: int) -> "Expression":
71 """Return a leaf that reads the given zero-based column of the input."""
72 return cls("variable", value=column)
73
74
75 @classmethod
76 def parameter(cls) -> "Expression":
77 """Return a free scalar leaf, with a separate coefficient for each occurrence."""
78 return cls("parameter")
79
80
81 @classmethod
82 def constant(cls, value: float) -> "Expression":
83 """Return a fixed real-valued leaf."""
84 return cls("constant", value=value)
85
86
87 @property
88 def node_count(self) -> int:
89 """Count all operator and terminal occurrences."""
90 return 1 + sum(child.node_count for child in self.children)
91
92
93 @property
94 def parameter_count(self) -> int:
95 """Count free coefficient occurrences."""
96 return sum(child.parameter_count for child in self.children) + (self.op == "parameter")
97
98
99 @property
100 def non_algebraic_count(self) -> int:
101 """Count sine, cosine, exponential, and logarithm occurrences."""
102 return sum(child.non_algebraic_count for child in self.children) + (self.op in _NON_ALGEBRAIC)
103
104
105def _matrix(data):
106 """Validate finite real inputs with one row per sample and one column per variable."""
107 values = np.asarray(data)
108 if np.iscomplexobj(values):
109 raise ValueError("X must contain real values.")
110 x = np.asarray(values, dtype=float)
111 if x.ndim != 2 or not all(x.shape) or not np.isfinite(x).all():
112 raise ValueError("X must be a nonempty, finite (samples, variables) matrix.")
113 return x
114
115
116def _compile(expression):
117 """Build a postfix program and a structurally affine subset of parameter slots."""
118 program = []
119 n_parameters = 0
120 n_variables = 0
121
122 def visit(node):
123 nonlocal n_parameters, n_variables
124 op, value = node.op, node.value
125 if op == "parameter":
126 slot = n_parameters
127 n_parameters += 1
128 program.append((op, slot))
129 return (slot,)
130 if op == "variable":
131 n_variables = max(n_variables, value + 1)
132 affine = [visit(child) for child in node.children]
133 program.append((op, value))
134 if op in ("add", "sub"):
135 return affine[0] + affine[1]
136 if op in ("div", "neg"):
137 return affine[0]
138 if op == "mul":
139 # Keep one side affine while treating the other side as fixed.
140 return max(affine, key=len)
141 return ()
142
143 linear = visit(expression)
144 return tuple(program), linear, n_parameters, n_variables
145
146
147def _constant_column(values, width):
148 basis = np.zeros((len(values), width))
149 basis[:, 0] = values
150 return basis
151
152
153def _evaluate(program, x, coefficients, affine=None):
154 """Interpret the tree in vector form or as [offset, basis] for affine fitting."""
155 stack = []
156 with np.errstate(all="ignore"):
157 for op, value in program:
158 if op == "variable":
159 stack.append(x[:, value])
160 elif op == "constant":
161 stack.append(np.broadcast_to(value, len(x)))
162 elif op == "parameter":
163 if affine and value in affine:
164 basis = np.zeros((len(x), len(affine) + 1))
165 basis[:, affine[value]] = 1.
166 stack.append(basis)
167 else:
168 stack.append(np.broadcast_to(coefficients[value], len(x)))
169 else:
170 arity, fn, _ = _OPERATORS[op]
171 if arity == 1:
172 result = fn(stack.pop())
173 else:
174 right, left = stack.pop(), stack.pop()
175 if left.ndim != right.ndim:
176 if op in ("add", "sub"):
177 if left.ndim == 1:
178 left = _constant_column(left, right.shape[1])
179 else:
180 right = _constant_column(right, left.shape[1])
181 else:
182 if left.ndim == 1:
183 left = left[:, None]
184 else:
185 right = right[:, None]
186 result = fn(left, right)
187 # Propagate undefined intermediate values, including from overflow.
188 stack.append(np.where(np.isfinite(result), result, np.nan))
189 return stack[0]
190
191
192def _rmse(predictions, target):
193 if not np.isfinite(predictions).all():
194 return float("inf")
195 with np.errstate(over="ignore"):
196 errors = np.abs(predictions - target)
197 scale = float(np.max(errors))
198 if scale == 0.:
199 return 0.
200 if not isfinite(scale):
201 scale = max(float(np.max(np.abs(predictions))), float(np.max(np.abs(target))))
202 errors = np.abs(predictions / scale - target / scale)
203 else:
204 errors /= scale
205 return scale * float(np.sqrt(np.mean(np.square(errors))))
206
207
208def _render(expression, coefficients):
209 if expression.op == "variable":
210 return f"x{expression.value}"
211 if expression.op == "constant":
212 return repr(expression.value)
213 if expression.op == "parameter":
214 return repr(next(coefficients))
215 operands = [_render(child, coefficients) for child in expression.children]
216 arity, _, symbol = _OPERATORS[expression.op]
217 if arity == 2:
218 return f"({operands[0]} {symbol} {operands[1]})"
219 if expression.op == "square":
220 return f"({operands[0]})**2"
221 return f"{symbol}({operands[0]})"
222
223
224
225@dataclass(frozen=True, slots=True)
227 """Store a tree, its fitted coefficients, and its training RMSE.
228
229 Coefficients follow the leaf order of :class:`Expression`. Models
230 contain no training data or optimizer state.
231 """
232
233 expression: Expression
234 coefficients: tuple[float, ...]
235 training_rmse: float
236
237 def __post_init__(self):
238 coefficients = tuple(map(float, self.coefficients))
239 if len(coefficients) != self.expression.parameter_count or not all(map(isfinite, coefficients)):
240 raise ValueError("Supply a finite coefficient for each parameter leaf.")
241 if not isfinite(self.training_rmse) or self.training_rmse < 0.:
242 raise ValueError("The training RMSE must be finite and nonnegative.")
243 object.__setattr__(self, "coefficients", coefficients)
244
245
246 @property
247 def formula(self) -> str:
248 """Format the fitted expression with variable names x0, x1, and so on."""
249 return _render(self.expression, iter(self.coefficients))
250
251
254 def predict(self, X) -> np.ndarray:
255 """Predict one value per row. Undefined or overflowing rows return NaN."""
256 x = _matrix(X)
257 program, _, _, n_variables = _compile(self.expression)
258 if x.shape[1] < n_variables:
259 raise ValueError(f"The expression needs at least {n_variables} input columns.")
260 return _evaluate(program, x, self.coefficients).copy()
261
262
266 def rmse(self, X, y) -> float:
267 """Return RMSE on labeled rows, or infinity if any prediction is undefined."""
268 predictions = self.predict(X)
269 return _rmse(predictions, _target(y, len(predictions)))
270
271
272def _target(y, n):
273 values = np.asarray(y)
274 if np.iscomplexobj(values):
275 raise ValueError("y must contain real values.")
276 target = np.asarray(values, dtype=float)
277 if target.shape != (n,) or not np.isfinite(target).all():
278 raise ValueError("y must be a finite vector with one target per input row.")
279 return target
A safe expression tree whose parameter leaves each hold one free scalar.
int parameter_count(self)
Count independent parameter slots.
"Expression" parameter(cls)
Build a free coefficient leaf.
"Expression" variable(cls, int column)
Build a variable leaf from a zero-based input column.
"Expression" constant(cls, float value)
Build a fixed, finite numeric leaf.
int node_count(self)
Count all nodes, including leaves.
int non_algebraic_count(self)
Count trigonometric, exponential and logarithmic nodes.
A fitted expression with independently usable NumPy inference.
float rmse(self, X, y)
Score the model on a separate labeled dataset.
str formula(self)
Format the equation with its fitted coefficients.
np.ndarray predict(self, X)
Vectorized evaluation with original operator domains.