arxflex 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
arxflex/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """arxflex: ARX models with nonlinear input blocks, specified as formulas.
2
+
3
+ The methods are described in C. A. Thilker, P. Bacher, D. Cali and H. Madsen
4
+ (2022), Identification of non-linear autoregressive models with exogenous
5
+ inputs for room air temperature modelling, Energy and AI 9, 100165,
6
+ https://doi.org/10.1016/j.egyai.2022.100165.
7
+
8
+ Each file is named after its main function. The model is given as a dict of
9
+ formula terms, fitted with fitmodel() and simulated with simulate_model():
10
+
11
+ from arxflex import fitmodel
12
+ fit = fitmodel(df, "Ti", {"AR": 2, "ambient": "Ta - Ti",
13
+ "heating": "v(sigmoid, Tset - Ti) * (Tfor - Ti)"})
14
+
15
+ The functions take their settings as arguments. The only value kept in the
16
+ package is BAD_FIT, the objective value for invalid parameters, which
17
+ fitmodel() and compile_model() accept as bad_fit=.
18
+ """
19
+
20
+ from .nonlinear_blocks import (Block, BlockError, BSplineBlock, SigmoidBlock,
21
+ PchipBlock, bspline_basis, register_block, make_block)
22
+ from .parse_formula import Term, FormulaError, parse_formula
23
+ from .least_squares import least_squares
24
+ from .compile_model import CompiledModel, compile_model, BAD_FIT
25
+ from .simulate_model import simulate_model
26
+ from .fitmodel import fitmodel, print_fit, fit_row
27
+ from .contribution import contribution
28
+ from .plot_simulation import plot_simulation
29
+ from .plot_residuals import plot_residuals
30
+ from .plot_acf import plot_acf
31
+ from .plot_ccf import plot_ccf
32
+ from .plot_blocks import plot_blocks
33
+ from .plot_daily_residuals import plot_daily_residuals
34
+
35
+ __version__ = "0.1.0"
36
+
37
+ __all__ = ["Block", "BlockError", "BSplineBlock", "SigmoidBlock", "PchipBlock",
38
+ "bspline_basis", "register_block", "make_block",
39
+ "Term", "FormulaError", "parse_formula", "least_squares",
40
+ "CompiledModel", "compile_model", "BAD_FIT", "simulate_model",
41
+ "fitmodel", "print_fit", "fit_row", "contribution", "plot_simulation",
42
+ "plot_residuals", "plot_acf", "plot_ccf", "plot_blocks",
43
+ "plot_daily_residuals"]
@@ -0,0 +1,308 @@
1
+ """Bind a model specification to data: design matrix, parameter packing, objective.
2
+
3
+ compile_model() turns
4
+
5
+ {"AR": 2,
6
+ "ambient": "Ta - Ti",
7
+ "solar": "s(timeofday, k=5) * Ps",
8
+ "heating": "v(sigmoid, Tset - Ti) * (Tfor - Ti)"}
9
+
10
+ into a CompiledModel, which holds one term per entry and knows
11
+
12
+ * where each term's nonlinear parameters sit in one global parameter vector,
13
+ so the spline coefficients, spline knots and valve parameters of all terms
14
+ are optimised together in a single call to the optimiser,
15
+ * the box bounds and linear inequality constraints of that vector, with the
16
+ constraints of each block moved into its own columns,
17
+ * how to build the design matrix and the least squares objective.
18
+
19
+ The column order of the design matrix follows the older
20
+ construct_design_matrix(): the output lags newest first, then for each term its
21
+ lags oldest first. With "AR": 0 there are no output lags, and the model is a
22
+ plain regression on the lagged terms.
23
+
24
+ Missing values are allowed. A NaN in the output or in an input reaches the
25
+ design matrix through every lag it enters, and the rows that are not fully
26
+ finite are dropped from the least squares (see used_rows() and design_used()).
27
+ A gap of one sample therefore costs L rows, L being the largest lag in the
28
+ model. Nothing is interpolated, and no row is dropped from design(), so the
29
+ rows stay aligned with the data.
30
+ """
31
+
32
+ import numpy as np
33
+
34
+ from .least_squares import least_squares
35
+ from .nonlinear_blocks import BlockError
36
+ from .parse_formula import parse_formula, FormulaError
37
+
38
+ AR_KEY = "AR" # reserved key of the model dict: the number of output lags
39
+ BAD_FIT = 1e10 # objective value returned for invalid nonlinear parameters
40
+
41
+
42
+ def _is_numeric(series):
43
+ """Can this column be used as a model variable?
44
+
45
+ np.issubdtype() raises TypeError on a pandas extension dtype (string,
46
+ categorical, ...) instead of returning False, so a frame holding a text
47
+ column used to crash here. Nullable numeric dtypes (Int64, Float64) are
48
+ numeric and are kept.
49
+ """
50
+ try:
51
+ import pandas as pd
52
+ return bool(pd.api.types.is_numeric_dtype(series))
53
+ except ImportError:
54
+ pass
55
+ try:
56
+ return bool(np.issubdtype(series.dtype, np.number))
57
+ except TypeError:
58
+ return False
59
+
60
+
61
+ def _numeric(series):
62
+ """Column as float64, with the missing values of a nullable dtype as NaN."""
63
+ try:
64
+ return series.to_numpy(dtype=float, na_value=np.nan)
65
+ except TypeError: # plain numpy-backed column: no na_value kwarg
66
+ return series.to_numpy(float)
67
+
68
+
69
+ class CompiledModel:
70
+ """A model specification bound to one data set. Built by compile_model()."""
71
+
72
+ def __init__(self, y, y_name, terms, Nd, columns=None, bad_fit=BAD_FIT):
73
+ self.y_all = np.asarray(y, float)
74
+ self.y_name = y_name
75
+ self.columns = {} if columns is None else columns
76
+ self.bad_fit = float(bad_fit)
77
+ self.terms = list(terms)
78
+ self.Nd = int(Nd)
79
+ self.n = len(self.y_all)
80
+ self.L = max([self.Nd] + [t.lags for t in self.terms])
81
+ if self.n <= self.L:
82
+ raise ValueError(f"only {self.n} samples for {self.L} lags")
83
+
84
+ # ---- parameter layout ------------------------------------------
85
+ self.slices, start = [], 0
86
+ for t in self.terms:
87
+ self.slices.append(slice(start, start + t.nparam))
88
+ start += t.nparam
89
+ self.nparam = start
90
+
91
+ # ---- what does not change during the optimisation --------------
92
+ self.y = self.y_all[self.L:]
93
+ # (n - L) x Nd; with Nd = 0 an empty block, so design() needs no special case
94
+ self.ar = np.column_stack(
95
+ [self.y_all[self.L - 1 - j:self.n - 1 - j] for j in range(self.Nd)]
96
+ ) if self.Nd else np.empty((self.n - self.L, 0))
97
+ self._const_lags = [None if t.block is not None else self._lags(t.const, t.lags)
98
+ for t in self.terms]
99
+
100
+ # Rows that are unusable whatever the nonlinear parameters are: a
101
+ # missing output, or a missing value in one of the fixed columns.
102
+ ok = np.isfinite(self.y) & np.all(np.isfinite(self.ar), axis=1)
103
+ for const in self._const_lags:
104
+ if const is not None:
105
+ ok &= np.all(np.isfinite(const), axis=1)
106
+ self.base_ok = ok
107
+ if not ok.any():
108
+ raise ValueError(
109
+ f"no usable samples: all {len(ok)} rows of the design matrix "
110
+ "contain a missing value")
111
+
112
+ # ---- helpers --------------------------------------------------------
113
+ def _lags(self, x, q):
114
+ """Columns x_{k-q} .. x_{k-1} (oldest lag first) for k = L .. n-1."""
115
+ x = np.asarray(x, float)
116
+ return np.column_stack([x[self.L - q + i:self.n - q + i] for i in range(q)])
117
+
118
+ def dynamic_terms(self):
119
+ """Indices of the terms that depend on the output and must be recomputed
120
+ during simulation."""
121
+ return [i for i, t in enumerate(self.terms) if t.uses_y]
122
+
123
+ def blocks(self):
124
+ """[(term, block, slice)] for the terms that have a nonlinear block."""
125
+ return [(t, t.block, s) for t, s in zip(self.terms, self.slices)
126
+ if t.block is not None]
127
+
128
+ # ---- the parameter vector ------------------------------------------
129
+ def init(self):
130
+ if self.nparam == 0:
131
+ return np.zeros(0)
132
+ return np.concatenate([t.block.init() for t, _, _ in self.blocks()])
133
+
134
+ def bounds(self):
135
+ b = []
136
+ for t, block, _ in self.blocks():
137
+ b += list(block.bounds())
138
+ return b
139
+
140
+ def constraints(self):
141
+ """(A, lb, ub) over the whole parameter vector, or None if there are none."""
142
+ rows, lbs, ubs = [], [], []
143
+ for t, block, sl in self.blocks():
144
+ c = block.constraints()
145
+ if c is None:
146
+ continue
147
+ A, lb, ub = c
148
+ A = np.atleast_2d(A)
149
+ full = np.zeros((A.shape[0], self.nparam))
150
+ full[:, sl] = A
151
+ rows.append(full)
152
+ lbs.append(np.atleast_1d(lb))
153
+ ubs.append(np.atleast_1d(ub))
154
+ if not rows:
155
+ return None
156
+ return np.vstack(rows), np.concatenate(lbs), np.concatenate(ubs)
157
+
158
+ def valid(self, params):
159
+ return all(block.valid(params[sl]) for _, block, sl in self.blocks())
160
+
161
+ def unpack(self, params):
162
+ """{term name: that term's nonlinear parameters}."""
163
+ params = np.asarray(params, float)
164
+ return {t.name: params[sl] for t, sl in zip(self.terms, self.slices)
165
+ if t.nparam}
166
+
167
+ # ---- the model ------------------------------------------------------
168
+ def columns(self, params):
169
+ """One column per term, before lagging."""
170
+ params = np.asarray(params, float)
171
+ return [t.column(params[sl]) for t, sl in zip(self.terms, self.slices)]
172
+
173
+ def design(self, params):
174
+ """Design matrix X and target y."""
175
+ params = np.asarray(params, float)
176
+ blocks = [self.ar]
177
+ for t, sl, const in zip(self.terms, self.slices, self._const_lags):
178
+ blocks.append(const if const is not None else self._lags(t.column(params[sl]), t.lags))
179
+ return np.hstack(blocks), self.y
180
+
181
+ def used_rows(self, X=None, y=None):
182
+ """Boolean mask of the design matrix rows the least squares can use.
183
+
184
+ A row is used when the target and every column of that row are finite.
185
+ With X and y omitted only the fixed part is checked (base_ok).
186
+ """
187
+ if X is None:
188
+ return self.base_ok
189
+ if y is None:
190
+ y = self.y
191
+ return self.base_ok & np.isfinite(y) & np.all(np.isfinite(X), axis=1)
192
+
193
+ def design_used(self, params):
194
+ """design(params) with the rows holding a missing value dropped.
195
+
196
+ Returns (X, y, mask); mask is over the rows of design(), so
197
+ X.shape[0] == mask.sum().
198
+ """
199
+ X, y = self.design(params)
200
+ mask = self.used_rows(X, y)
201
+ return X[mask], y[mask], mask
202
+
203
+ @property
204
+ def ntheta(self):
205
+ """Number of regression coefficients, i.e. columns of the design matrix."""
206
+ return self.Nd + sum(t.lags for t in self.terms)
207
+
208
+ def objective(self, params):
209
+ """Residual sum of squares after solving the regression coefficients by
210
+ least squares.
211
+
212
+ Rows with a missing value are left out; if too few remain to identify
213
+ the regression coefficients, bad_fit is returned instead.
214
+ """
215
+ params = np.asarray(params, float)
216
+ if not self.valid(params):
217
+ return self.bad_fit
218
+ try:
219
+ X, y, _ = self.design_used(params)
220
+ except BlockError:
221
+ return self.bad_fit
222
+ if len(y) <= self.ntheta:
223
+ return self.bad_fit
224
+ return least_squares(X, y)[1]
225
+
226
+ def parameter_names(self):
227
+ """Names of the regression coefficients, in design matrix order."""
228
+ names = [f"{self.y_name}(k-{j + 1})" for j in range(self.Nd)]
229
+ for t in self.terms:
230
+ names += [f"{t.name}(k-{t.lags - i})" for i in range(t.lags)]
231
+ return names
232
+
233
+ def theta_slices(self):
234
+ """{name: slice} of the regression coefficients, "AR" plus one per term."""
235
+ out, start = {AR_KEY: slice(0, self.Nd)}, self.Nd
236
+ for t in self.terms:
237
+ out[t.name] = slice(start, start + t.lags)
238
+ start += t.lags
239
+ return out
240
+
241
+ # ---- subsets --------------------------------------------------------
242
+ def restrict(self, n):
243
+ """A copy using only the first n samples (for fitting on a training period)."""
244
+ sl = slice(0, n)
245
+ return CompiledModel(self.y_all[sl], self.y_name,
246
+ [t.restrict(sl) for t in self.terms], self.Nd,
247
+ columns={k: v[sl] for k, v in self.columns.items()},
248
+ bad_fit=self.bad_fit)
249
+
250
+ def __repr__(self):
251
+ return (f"CompiledModel({self.y_name}, Nd={self.Nd}, n={self.n}, "
252
+ f"terms={[t.name for t in self.terms]}, nparam={self.nparam})")
253
+
254
+
255
+ def compile_model(data, y, model, lags=None, bad_fit=BAD_FIT):
256
+ """Parse a model specification and bind it to the data.
257
+
258
+ data : data frame; every variable of the formulas is a column of it, and so
259
+ is the output variable
260
+ y : name of the output column
261
+ model : {"AR": number of output lags, term name: formula, ...}. A formula
262
+ may be a string, or a dict {"formula": ..., "lags": ...} to give
263
+ that term a different number of lags. "AR": 0 leaves the output
264
+ lags out of the model.
265
+ lags : default number of lags of the terms (default: the AR order, or 1
266
+ when it is 0)
267
+ bad_fit : objective value returned for invalid nonlinear parameters
268
+ """
269
+ if y not in data.columns:
270
+ raise ValueError(f"output variable {y!r} is not a column of the data")
271
+ if AR_KEY not in model:
272
+ raise ValueError(f'the model needs an {AR_KEY!r} entry with the number of output lags')
273
+ Nd = int(model[AR_KEY])
274
+ if Nd < 0:
275
+ raise ValueError(f"{AR_KEY} must be 0 or more")
276
+ default_lags = max(Nd, 1) if lags is None else int(lags)
277
+
278
+ columns = {c: _numeric(data[c]) for c in data.columns
279
+ if c.isidentifier() and _is_numeric(data[c])}
280
+ terms = []
281
+ for name, spec in model.items():
282
+ if name == AR_KEY:
283
+ continue
284
+ term_lags = default_lags
285
+ if isinstance(spec, dict):
286
+ spec = dict(spec)
287
+ term_lags = int(spec.pop("lags", default_lags))
288
+ text = spec.pop("formula")
289
+ if spec:
290
+ raise ValueError(f"term {name!r}: unknown options {sorted(spec)}")
291
+ else:
292
+ text = spec
293
+ if term_lags < 1:
294
+ raise ValueError(f"term {name!r}: lags must be at least 1")
295
+ try:
296
+ terms.append(parse_formula(text, columns, name=name, lags=term_lags, y_name=y))
297
+ except FormulaError as e:
298
+ raise FormulaError(f"term {name!r}: {e}")
299
+ if not terms:
300
+ raise ValueError("the model has no input terms")
301
+
302
+ # Missing values are dropped row by row further down (CompiledModel), but a
303
+ # column with nothing usable in it at all is a mistake worth naming here.
304
+ used = {y} | {v for t in terms for v in t.variables}
305
+ empty = [c for c in sorted(used) if not np.any(np.isfinite(columns[c]))]
306
+ if empty:
307
+ raise ValueError("no finite values at all in: " + ", ".join(empty))
308
+ return CompiledModel(columns[y], y, terms, Nd, columns=columns, bad_fit=bad_fit)
@@ -0,0 +1,94 @@
1
+ """What each term of a fit contributes to the output."""
2
+
3
+ import numpy as np
4
+
5
+ from .compile_model import AR_KEY
6
+
7
+ CONTRIBUTION_KINDS = ("sample", "gain", "gain_loop")
8
+
9
+
10
+ def contribution(r, term_name, kind="sample"):
11
+ """What a term of the fit r contributes to the output, one value per row
12
+ of the data (as plotted by the regcontribution panels of
13
+ plot_simulation()).
14
+
15
+ kind="sample": sum(theta) * term(k), the term's regression input times the
16
+ sum of its coefficients over the lags, in units of the output per sample.
17
+ With the AR coefficients summing to about 1, as for a discretised RC
18
+ model, y(k) - y(k-1) is about sum over the terms of sum(theta) * term, so
19
+ this is the change of the output per sample that the term causes: for a
20
+ heat flow, the heat per sample divided by the heat capacity ("relative
21
+ energy"). It follows the shape of the term, e.g. of the valve curve.
22
+ It is not the lagged sum sum_i theta_i * term(k-i) that enters the one-step
23
+ prediction: when the coefficients of the lags have opposite signs, that sum
24
+ is dominated by the change of the term from one sample to the next.
25
+ term_name "AR" gives (sum of the AR coefficients - 1) * y(k): the part of
26
+ the AR terms that acts as a loss in proportion to the output (zero when the
27
+ coefficients sum to 1). With it, the contributions of all terms sum to
28
+ y(k+1) - y(k) on average, and so to about zero over a long period.
29
+
30
+ kind="gain": the same divided by phi(1) = 1 - sum of the AR coefficients,
31
+ i.e. the term times the DC gain of its transfer function: the
32
+ steady-state change of the output the term gives, in units of the output.
33
+ "AR" then gives -y(k), so that again all contributions sum to about zero:
34
+ in steady state y = sum over the terms of gain * term.
35
+
36
+ kind="gain_loop": as "gain", but a linear term that is affine in the
37
+ output, c(x) + beta * y such as "Ta - Ti", has its y-part moved to the
38
+ left-hand side of the steady-state equation, which then divides by
39
+ 1 - sum(a) - sum over those terms of beta * sum(theta). Such a term
40
+ contributes only gain * c(x), e.g. gain * Ta, with a gain that is a
41
+ fraction of 1 instead of a large number. y inside a nonlinear term (e.g.
42
+ the valve curve) stays where it is. "AR" is again -y(k).
43
+
44
+ With the AR coefficients summing to near 1, phi(1) is near zero and the
45
+ "gain" values are large and uncertain."""
46
+ if kind not in CONTRIBUTION_KINDS:
47
+ raise ValueError(f"contribution must be one of {CONTRIBUTION_KINDS}, not {kind!r}")
48
+ y = np.asarray(r["y_data"], float)
49
+ a_sum = float(np.sum(r["theta"][r["theta_of"][AR_KEY]])) if r["Nd"] else 0.0
50
+ if term_name == AR_KEY:
51
+ c = (a_sum - 1.0) * y
52
+ return c if kind == "sample" else -y
53
+ theta_sum = float(np.sum(r["theta"][r["theta_of"][term_name]]))
54
+ if kind == "sample":
55
+ return theta_sum * reg_column(r, term_name)
56
+ if kind == "gain":
57
+ return theta_sum * reg_column(r, term_name) / (1.0 - a_sum)
58
+ affine = affine_in_output(r)
59
+ denominator = 1.0 - a_sum - sum(
60
+ beta * float(np.sum(r["theta"][r["theta_of"][nm]]))
61
+ for nm, (_, beta) in affine.items())
62
+ x = affine[term_name][0] if term_name in affine else reg_column(r, term_name)
63
+ return theta_sum * x / denominator
64
+
65
+
66
+ def affine_in_output(r):
67
+ """{term name: (c, beta)} for the linear terms that are c(x) + beta * y,
68
+ with c a column and beta a number, e.g. "Ta - Ti" with y = Ti gives
69
+ (Ta, -1). Found by evaluating the term with y set to 0, 1 and 2."""
70
+ cm, y = r["compiled"], r["y"]
71
+ out = {}
72
+ for term in cm.terms:
73
+ if term.block is not None or not term.uses_y:
74
+ continue
75
+ cols = [np.asarray(term.bind({**cm.columns, y: np.full(cm.n, v)}).column(), float)
76
+ for v in (0.0, 1.0, 2.0)]
77
+ d1, d2 = cols[1] - cols[0], cols[2] - cols[1]
78
+ ok = np.isfinite(d1) & np.isfinite(d2)
79
+ if not ok.any():
80
+ continue
81
+ beta = float(np.median(d1[ok]))
82
+ if np.allclose(d1[ok], beta) and np.allclose(d2[ok], beta):
83
+ out[term.name] = (cols[0], beta)
84
+ return out
85
+
86
+
87
+ def reg_column(r, term_name):
88
+ """The term's column in the design matrix, before lagging and theta: the
89
+ formula evaluated at the fitted nonlinear parameters."""
90
+ cm = r["compiled"]
91
+ for term, sl in zip(cm.terms, cm.slices):
92
+ if term.name == term_name:
93
+ return np.asarray(term.column(r["params"][sl]), float)
94
+ raise KeyError(term_name)