blocksim 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.
blocksim/table.py ADDED
@@ -0,0 +1,355 @@
1
+ """
2
+ Lookup tables: measured data as a block.
3
+
4
+ Not every relationship has a formula. A compressor map, an aerodynamic
5
+ coefficient, a pump curve, a material property against temperature --
6
+ these arrive as numbers from a rig or a wind tunnel, and the model needs
7
+ to interpolate them and, more importantly, to differentiate them
8
+ sensibly.
9
+
10
+ `LookupTable1D` and `LookupTable2D` are the general interpolators.
11
+ `MapTable` is the specialised one for turbomachinery: it carries the
12
+ axis conventions a compressor or turbine map needs, and its docstring is
13
+ the place to start for those.
14
+
15
+ Interpolation method is the choice that matters. Linear interpolation is
16
+ robust and has a discontinuous SLOPE at every breakpoint, which an
17
+ implicit solver taking a Jacobian will feel; a spline or a monotone
18
+ piecewise-cubic (`pchip`) is smooth but can overshoot between points if
19
+ the data is noisy. For anything inside a Newton loop -- an engine
20
+ balance, say -- smoothness is usually worth more than fidelity to the
21
+ last digit of the data, because a derivative that jumps at a breakpoint
22
+ will stall the iteration.
23
+
24
+ Extrapolation is the other one. Off the end of measured data every
25
+ method is guessing, and the guesses differ wildly; a table asked for a
26
+ point outside its range should say so rather than return a number that
27
+ looks like the others.
28
+ """
29
+
30
+ import numpy as np
31
+
32
+ # scipy.interpolate is imported in the constructor below, so merely
33
+ # importing blocksim does not pull it in.
34
+ from .core import Block
35
+
36
+ __all__ = ["LookupTable1D", "LookupTable2D", "MapTable"]
37
+
38
+
39
+ class LookupTable1D(Block):
40
+ """1-D lookup table: y = piecewise-linear interpolation of the input over
41
+ (breakpoints, values).
42
+
43
+ breakpoints
44
+ strictly increasing 1-D grid of input values
45
+
46
+ values
47
+ table output at each breakpoint (same length)
48
+
49
+ extrapolation
50
+ 'clip' -- hold the end values outside the grid (default)
51
+ 'linear' -- extend the end segments' slopes
52
+ """
53
+
54
+ def __init__(self, breakpoints, values, extrapolation="clip", name=None):
55
+ self.breakpoints = np.asarray(breakpoints, dtype=float).ravel()
56
+ self.values = np.asarray(values, dtype=float).ravel()
57
+ if self.breakpoints.size < 2:
58
+ raise ValueError("LookupTable1D needs at least 2 breakpoints")
59
+ if self.breakpoints.size != self.values.size:
60
+ raise ValueError(
61
+ f"breakpoints ({self.breakpoints.size}) and values "
62
+ f"({self.values.size}) must have the same length"
63
+ )
64
+ if np.any(np.diff(self.breakpoints) <= 0):
65
+ raise ValueError("breakpoints must be strictly increasing")
66
+ if extrapolation not in ("clip", "linear"):
67
+ raise ValueError("extrapolation must be 'clip' or 'linear'")
68
+ self.extrapolation = extrapolation
69
+
70
+ super().__init__(
71
+ num_inputs=1,
72
+ num_outputs=1,
73
+ name=name,
74
+ inputs=[("u", None)],
75
+ outputs=[("y", None)],
76
+ )
77
+
78
+ def output(self, t, u):
79
+ x = u[0]
80
+ bp, vals = self.breakpoints, self.values
81
+ if self.extrapolation == "linear":
82
+ if x < bp[0]:
83
+ slope = (vals[1] - vals[0]) / (bp[1] - bp[0])
84
+ return np.array([vals[0] + slope * (x - bp[0])], dtype=float)
85
+ if x > bp[-1]:
86
+ slope = (vals[-1] - vals[-2]) / (bp[-1] - bp[-2])
87
+ return np.array([vals[-1] + slope * (x - bp[-1])], dtype=float)
88
+ # inside the grid (and 'clip' outside): np.interp holds end values
89
+ return np.array([np.interp(x, bp, vals)], dtype=float)
90
+
91
+
92
+ class LookupTable2D(Block):
93
+ """2-D lookup table: z = bilinear interpolation of (u0, u1) over a
94
+ rectangular grid.
95
+
96
+ x_breakpoints
97
+ strictly increasing grid for the first input u0
98
+
99
+ y_breakpoints
100
+ strictly increasing grid for the second input u1
101
+
102
+ table
103
+ 2-D array of outputs, shape (len(x), len(y)) --
104
+ table[i, j] = z at (x_breakpoints[i], y_breakpoints[j])
105
+
106
+ extrapolation
107
+ 'clip' -- clamp inputs to the grid edges (default)
108
+ 'linear' -- extend the boundary cells' gradients
109
+ """
110
+
111
+ def __init__(
112
+ self, x_breakpoints, y_breakpoints, table, extrapolation="clip", name=None
113
+ ):
114
+ self.x_breakpoints = np.asarray(x_breakpoints, dtype=float).ravel()
115
+ self.y_breakpoints = np.asarray(y_breakpoints, dtype=float).ravel()
116
+ self.table = np.asarray(table, dtype=float)
117
+ if self.x_breakpoints.size < 2 or self.y_breakpoints.size < 2:
118
+ raise ValueError("LookupTable2D needs at least 2 breakpoints per axis")
119
+ if np.any(np.diff(self.x_breakpoints) <= 0) or np.any(
120
+ np.diff(self.y_breakpoints) <= 0
121
+ ):
122
+ raise ValueError("breakpoints must be strictly increasing")
123
+ if self.table.shape != (self.x_breakpoints.size, self.y_breakpoints.size):
124
+ raise ValueError(
125
+ f"table shape {self.table.shape} must be "
126
+ f"(len(x), len(y)) = "
127
+ f"({self.x_breakpoints.size}, {self.y_breakpoints.size})"
128
+ )
129
+ if extrapolation not in ("clip", "linear"):
130
+ raise ValueError("extrapolation must be 'clip' or 'linear'")
131
+ self.extrapolation = extrapolation
132
+
133
+ # fill_value=None -> linear extrapolation outside the grid; the
134
+ # 'clip' mode clamps the inputs before evaluating instead
135
+ from scipy.interpolate import RegularGridInterpolator
136
+
137
+ self._interp = RegularGridInterpolator(
138
+ (self.x_breakpoints, self.y_breakpoints),
139
+ self.table,
140
+ method="linear",
141
+ bounds_error=False,
142
+ fill_value=None,
143
+ )
144
+
145
+ super().__init__(
146
+ num_inputs=2,
147
+ num_outputs=1,
148
+ name=name,
149
+ inputs=[("u0", None), ("u1", None)],
150
+ outputs=[("y", None)],
151
+ )
152
+
153
+ def output(self, t, u):
154
+ x, y = u[0], u[1]
155
+ if self.extrapolation == "clip":
156
+ x = np.clip(x, self.x_breakpoints[0], self.x_breakpoints[-1])
157
+ y = np.clip(y, self.y_breakpoints[0], self.y_breakpoints[-1])
158
+ return np.array([self._interp((x, y))], dtype=float).ravel()
159
+
160
+
161
+ class MapTable(Block):
162
+ """N-D lookup with SEVERAL outputs sharing one grid.
163
+
164
+ `LookupTable1D` and `LookupTable2D` return one value. Turbomachinery
165
+ performance maps do not: a compressor map reads corrected flow, pressure
166
+ ratio AND efficiency off the same (corrected speed, R-line) point, and a
167
+ turbine map reads corrected flow and efficiency off the same (pressure
168
+ ratio, corrected speed) point. Splitting those into separate tables
169
+ would interpolate the same cell three times and, worse, let the three
170
+ tables drift out of step if one is ever re-gridded.
171
+
172
+ breakpoints
173
+ one strictly increasing 1-D grid per input axis --
174
+ `[speeds, rlines]` for a 2-D map. A bare 1-D array is
175
+ accepted for a single-axis map.
176
+
177
+ values
178
+ the tabulated outputs, as either
179
+ - a dict {name: array}, which also names the output
180
+ ports, in insertion order (the usual choice);
181
+ - a sequence of arrays, one per output; or
182
+ - one array shaped `grid` (a single output) or
183
+ `grid + (n_outputs,)`.
184
+ Every array must have exactly the grid's shape.
185
+
186
+ names, units
187
+ output port metadata; `names` overrides the dict keys.
188
+
189
+ extrapolation
190
+ 'clip' -- clamp the inputs to the grid (default)
191
+ 'linear' -- let the interpolator run off the grid
192
+ 'error' -- raise instead. Off-grid lookups usually mean
193
+ an engine balance has wandered somewhere unphysical, and
194
+ silently clamping hides that; 'error' is how you find out
195
+ where. See `evaluate` for a one-off check.
196
+
197
+ method
198
+ any `RegularGridInterpolator` method. The default
199
+ 'linear' has a discontinuous derivative at every cell
200
+ boundary, which is exactly the kind of kink a Newton
201
+ solver sitting on top of the map struggles with, so
202
+ 'cubic' or 'pchip' is often the better choice for maps
203
+ that a solver iterates on -- at the cost of needing more
204
+ breakpoints per axis (4 for cubic) and of overshoot
205
+ ('pchip' will not overshoot; 'cubic' will).
206
+
207
+ The block form takes one input port per axis and one output port per
208
+ tabulated quantity. `evaluate()` gives the same lookup without any
209
+ diagram, which is what a component model wants when it owns a map
210
+ internally and applies its own scaling to the result.
211
+ """
212
+
213
+ def __init__(
214
+ self,
215
+ breakpoints,
216
+ values,
217
+ names=None,
218
+ units=None,
219
+ extrapolation="clip",
220
+ method="linear",
221
+ name=None,
222
+ ):
223
+ self.breakpoints = _as_axes(breakpoints)
224
+ grid = tuple(a.size for a in self.breakpoints)
225
+
226
+ arrays, dict_names = _as_output_arrays(values, grid)
227
+ for i, a in enumerate(arrays):
228
+ if a.shape != grid:
229
+ label = (dict_names or [f"#{i}"])[i]
230
+ raise ValueError(
231
+ f"MapTable output {label} has shape {a.shape}, but the "
232
+ f"breakpoints define a grid of shape {grid}"
233
+ )
234
+
235
+ if extrapolation not in ("clip", "linear", "error"):
236
+ raise ValueError("extrapolation must be 'clip', 'linear' or 'error'")
237
+ self.extrapolation = extrapolation
238
+ self.method = method
239
+
240
+ names = list(names) if names is not None else dict_names
241
+ if names is None:
242
+ names = [f"y{i}" for i in range(len(arrays))]
243
+ if len(names) != len(arrays):
244
+ raise ValueError(f"{len(names)} name(s) for {len(arrays)} output(s)")
245
+ if units is None:
246
+ units = [None] * len(arrays)
247
+ elif isinstance(units, dict):
248
+ units = [units.get(n) for n in names]
249
+ elif len(units) != len(arrays):
250
+ raise ValueError(f"{len(units)} unit(s) for {len(arrays)} output(s)")
251
+ self.names = names
252
+
253
+ # one interpolator over the outputs stacked on a trailing axis, so a
254
+ # lookup costs one weight computation instead of one per output
255
+ from scipy.interpolate import RegularGridInterpolator
256
+
257
+ self.table = np.stack(arrays, axis=-1)
258
+ self._interp = RegularGridInterpolator(
259
+ tuple(self.breakpoints),
260
+ self.table,
261
+ method=method,
262
+ bounds_error=False,
263
+ fill_value=None, # extrapolate; 'clip' clamps the inputs instead
264
+ )
265
+
266
+ super().__init__(
267
+ num_inputs=len(self.breakpoints),
268
+ name=name,
269
+ inputs=[(f"u{i}", None) for i in range(len(self.breakpoints))],
270
+ outputs=list(zip(names, units)),
271
+ )
272
+
273
+ # -- introspection --------------------------------------------------------
274
+ @property
275
+ def bounds(self):
276
+ """[(lo, hi), ...] per input axis."""
277
+ return [(float(a[0]), float(a[-1])) for a in self.breakpoints]
278
+
279
+ def contains(self, point):
280
+ """Is `point` inside the grid? Cheap enough to assert on."""
281
+ point = np.atleast_1d(np.asarray(point, dtype=float)).ravel()
282
+ return bool(np.all([lo <= v <= hi for v, (lo, hi) in zip(point, self.bounds)]))
283
+
284
+ # -- lookup ---------------------------------------------------------------
285
+ def evaluate(self, *point):
286
+ """All outputs at one point, as a 1-D array in output-port order.
287
+
288
+ Accepts `map.evaluate(nc, rline)` or `map.evaluate([nc, rline])`.
289
+ """
290
+ if len(point) == 1 and not np.isscalar(point[0]):
291
+ point = np.asarray(point[0], dtype=float).ravel()
292
+ else:
293
+ point = np.asarray(point, dtype=float).ravel()
294
+ if point.size != len(self.breakpoints):
295
+ raise ValueError(
296
+ f"{self.name} takes {len(self.breakpoints)} input(s), got {point.size}"
297
+ )
298
+
299
+ if self.extrapolation == "clip":
300
+ point = np.array(
301
+ [np.clip(v, lo, hi) for v, (lo, hi) in zip(point, self.bounds)]
302
+ )
303
+ elif self.extrapolation == "error" and not self.contains(point):
304
+ raise ValueError(
305
+ f"{self.name}: {list(point)} is outside the map's range {self.bounds}"
306
+ )
307
+ return np.asarray(self._interp(point[None, :]), dtype=float).ravel()
308
+
309
+ def lookup(self, *point):
310
+ """`evaluate` keyed by output name -- for reading, not for hot code."""
311
+ return dict(zip(self.names, self.evaluate(*point)))
312
+
313
+ def output(self, t, u):
314
+ return self.evaluate(u)
315
+
316
+
317
+ def _as_axes(breakpoints):
318
+ """Normalise the axis argument to a list of validated 1-D grids."""
319
+ if isinstance(breakpoints, np.ndarray) and breakpoints.ndim == 1:
320
+ axes = [breakpoints.astype(float)]
321
+ elif len(breakpoints) and np.isscalar(breakpoints[0]):
322
+ axes = [np.asarray(breakpoints, dtype=float)] # a bare 1-D grid
323
+ else:
324
+ axes = [np.asarray(a, dtype=float).ravel() for a in breakpoints]
325
+ if not axes:
326
+ raise ValueError("MapTable needs at least one axis of breakpoints")
327
+ for i, a in enumerate(axes):
328
+ if a.size < 2:
329
+ raise ValueError(f"axis {i} needs at least 2 breakpoints")
330
+ if np.any(np.diff(a) <= 0):
331
+ raise ValueError(f"axis {i} breakpoints must be strictly increasing")
332
+ return axes
333
+
334
+
335
+ def _as_output_arrays(values, grid):
336
+ """Split the `values` argument into (arrays, names or None)."""
337
+ if isinstance(values, dict):
338
+ if not values:
339
+ raise ValueError("MapTable needs at least one output")
340
+ return [np.asarray(v, dtype=float) for v in values.values()], list(values)
341
+ if isinstance(values, (list, tuple)):
342
+ if not values:
343
+ raise ValueError("MapTable needs at least one output")
344
+ return [np.asarray(v, dtype=float) for v in values], None
345
+
346
+ a = np.asarray(values, dtype=float)
347
+ if a.shape == grid:
348
+ return [a], None
349
+ if a.ndim == len(grid) + 1 and a.shape[:-1] == grid:
350
+ # trailing axis indexes the outputs
351
+ return [a[..., i] for i in range(a.shape[-1])], None
352
+ raise ValueError(
353
+ f"MapTable values of shape {a.shape} match neither the grid {grid} "
354
+ f"nor {grid} + (n_outputs,)"
355
+ )