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/thermal.py ADDED
@@ -0,0 +1,395 @@
1
+ """
2
+ Thermal networks and heat transfer.
3
+
4
+ Same architecture as `blocksim.hydraulics`, for the same reason:
5
+ temperatures are states and heat flows are outputs, so a thermal network
6
+ is causal by construction and needs no loop solver. A `ThermalMass` holds
7
+ a temperature; `Conduction`, `Convection`, `Radiation` and `Advection`
8
+ each read two temperatures and report the watts flowing between them.
9
+
10
+ dT/dt = Q_net / (m c)
11
+
12
+ The three modes are deliberately separate blocks rather than one
13
+ "thermal resistance", because they are not the same kind of thing:
14
+ conduction and convection are linear in the temperature difference,
15
+ radiation goes as the difference of fourth powers, and advection carries
16
+ enthalpy with a mass flow that can reverse. Writing them as one block
17
+ with a mode flag would hide exactly the distinction that decides which
18
+ one dominates.
19
+
20
+ `HeatExchanger` is the effectiveness-NTU method rather than a
21
+ discretized wall, because that is how an exchanger is actually
22
+ specified: you know its UA and its two capacity rates, and you want the
23
+ outlet temperatures without integrating along its length.
24
+
25
+ Everything is SI: temperature in kelvin, heat in watts, conductance in
26
+ W/K, capacitance in J/K.
27
+ """
28
+
29
+ from dataclasses import dataclass
30
+
31
+ import numpy as np
32
+
33
+ from .core import Block
34
+
35
+ __all__ = [
36
+ "Advection",
37
+ "Conduction",
38
+ "Convection",
39
+ "HeatExchanger",
40
+ "Material",
41
+ "Radiation",
42
+ "ThermalMass",
43
+ "conductance_of_slab",
44
+ "exchanger_effectiveness",
45
+ ]
46
+
47
+ #: Stefan-Boltzmann, W / (m^2 K^4)
48
+ SIGMA = 5.670374419e-8
49
+
50
+ ZERO_CELSIUS = 273.15
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Material:
55
+ """Bulk properties of a solid.
56
+
57
+ density : kg/m^3
58
+ specific_heat : J/(kg K)
59
+ conductivity : W/(m K)
60
+ emissivity : 0..1, for radiating surfaces
61
+ """
62
+
63
+ density: float = 2700.0
64
+ specific_heat: float = 900.0
65
+ conductivity: float = 205.0
66
+ emissivity: float = 0.9
67
+
68
+ def capacitance(self, volume):
69
+ """Thermal capacitance of `volume` cubic metres, J/K."""
70
+ return self.density * self.specific_heat * volume
71
+
72
+ def diffusivity(self):
73
+ """m^2/s -- how fast a temperature front moves through it."""
74
+ return self.conductivity / (self.density * self.specific_heat)
75
+
76
+
77
+ ALUMINIUM = Material()
78
+ STEEL = Material(density=7850.0, specific_heat=490.0, conductivity=45.0)
79
+ WATER = Material(density=997.0, specific_heat=4182.0, conductivity=0.6)
80
+
81
+
82
+ def conductance_of_slab(area, thickness, material=ALUMINIUM):
83
+ """kA/L, W/K -- the conductance of a slab conducting through its
84
+ thickness."""
85
+ if thickness <= 0.0 or area <= 0.0:
86
+ raise ValueError("area and thickness must be positive")
87
+ return material.conductivity * area / thickness
88
+
89
+
90
+ # ==============================================================================
91
+ # capacitance
92
+ # ==============================================================================
93
+ class ThermalMass(Block):
94
+ """A lump of material at one temperature: the state of a thermal node.
95
+
96
+ Inputs : n heat flows in (W)
97
+ Outputs : [temperature (K), temperature (degC)]
98
+
99
+ dT/dt = sum(Q_in) / C
100
+
101
+ Lumping is only honest when the piece is small compared with the
102
+ thermal wave it sees -- Biot number well below 1, or the diffusion
103
+ length over the timescale of interest larger than the piece. Past
104
+ that, chain several masses through `Conduction` instead, which is the
105
+ thermal equivalent of a finite-difference mesh.
106
+ """
107
+
108
+ def __init__(self, capacitance=1000.0, T0=293.15, n_ports=1, name=None):
109
+ if capacitance <= 0.0:
110
+ raise ValueError(f"capacitance must be positive, got {capacitance}")
111
+ self.capacitance = float(capacitance)
112
+ self.n_ports = int(n_ports)
113
+ super().__init__(
114
+ num_inputs=self.n_ports,
115
+ num_outputs=2,
116
+ num_states=1,
117
+ name=name,
118
+ inputs=[(f"Q{i}", "W") for i in range(self.n_ports)],
119
+ outputs=[("T", "K"), ("T_C", "degC")],
120
+ states=[("T", "K")],
121
+ )
122
+ self.x0 = np.array([float(T0)])
123
+
124
+ @classmethod
125
+ def of(cls, volume, material=ALUMINIUM, **kw):
126
+ """A mass sized from a geometry and a material rather than from a
127
+ capacitance in joules per kelvin."""
128
+ return cls(capacitance=material.capacitance(volume), **kw)
129
+
130
+ def derivative(self, t, x, u):
131
+ return np.array([float(np.sum(u)) / self.capacitance])
132
+
133
+ def output(self, t, x):
134
+ return np.array([x[0], x[0] - ZERO_CELSIUS])
135
+
136
+
137
+ # ==============================================================================
138
+ # the three modes
139
+ # ==============================================================================
140
+ class Conduction(Block):
141
+ """Fourier conduction through a fixed conductance.
142
+
143
+ Inputs : [T_a, T_b] (K)
144
+ Outputs : [Q, W flowing a to b]
145
+
146
+ Q = G (T_a - T_b), G = k A / L
147
+ """
148
+
149
+ def __init__(self, conductance=1.0, name=None):
150
+ if conductance <= 0.0:
151
+ raise ValueError("conductance must be positive")
152
+ self.conductance = float(conductance)
153
+ super().__init__(
154
+ num_inputs=2,
155
+ num_outputs=1,
156
+ name=name,
157
+ inputs=[("Ta", "K"), ("Tb", "K")],
158
+ outputs=[("Q", "W")],
159
+ )
160
+
161
+ @classmethod
162
+ def slab(cls, area, thickness, material=ALUMINIUM, **kw):
163
+ return cls(conductance=conductance_of_slab(area, thickness, material), **kw)
164
+
165
+ def output(self, t, u):
166
+ return np.array([self.conductance * (u[0] - u[1])])
167
+
168
+
169
+ class Convection(Block):
170
+ """Newton cooling from a surface to a fluid.
171
+
172
+ Inputs
173
+ [T_surface, T_fluid] and, when `variable=True`, the film
174
+ coefficient h in W/(m^2 K)
175
+
176
+ Outputs
177
+ [Q, W leaving the surface]
178
+
179
+ ::
180
+
181
+ Q = h A (T_s - T_f)
182
+
183
+ `variable=True` is how a correlation is wired in: compute h from the
184
+ flow somewhere else -- a `LookupTable2D` on Reynolds and Prandtl, or
185
+ an expression -- and feed it here, rather than burying one
186
+ correlation in this block.
187
+ """
188
+
189
+ def __init__(self, h=10.0, area=1.0, variable=False, name=None):
190
+ if area <= 0.0:
191
+ raise ValueError("area must be positive")
192
+ self.h = float(h)
193
+ self.area = float(area)
194
+ self.variable = bool(variable)
195
+ inputs = [("Ts", "K"), ("Tf", "K")]
196
+ if variable:
197
+ inputs.append(("h", "W/(m^2*K)"))
198
+ super().__init__(
199
+ num_inputs=len(inputs),
200
+ num_outputs=1,
201
+ name=name,
202
+ inputs=inputs,
203
+ outputs=[("Q", "W")],
204
+ )
205
+
206
+ def output(self, t, u):
207
+ h = float(u[2]) if self.variable else self.h
208
+ return np.array([h * self.area * (u[0] - u[1])])
209
+
210
+
211
+ class Radiation(Block):
212
+ """Grey-body exchange between two surfaces.
213
+
214
+ Inputs
215
+ [T_a, T_b] (K, absolute -- this is the one place where
216
+ using celsius is not merely unconventional but wrong)
217
+
218
+ Outputs
219
+ [Q, W flowing a to b]
220
+
221
+ ::
222
+
223
+ Q = sigma eps A F (T_a^4 - T_b^4)
224
+
225
+ `view_factor` is the fraction of a's radiation that reaches b; 1.0 is
226
+ a surface fully enclosed by the other, which is the usual case for a
227
+ body radiating to space or to a large room.
228
+ """
229
+
230
+ def __init__(self, area=1.0, emissivity=0.9, view_factor=1.0, name=None):
231
+ if not 0.0 < emissivity <= 1.0:
232
+ raise ValueError("emissivity must be in (0, 1]")
233
+ if not 0.0 <= view_factor <= 1.0:
234
+ raise ValueError("view factor must be in [0, 1]")
235
+ self.area = float(area)
236
+ self.emissivity = float(emissivity)
237
+ self.view_factor = float(view_factor)
238
+ self.coefficient = SIGMA * self.emissivity * self.area * self.view_factor
239
+ super().__init__(
240
+ num_inputs=2,
241
+ num_outputs=1,
242
+ name=name,
243
+ inputs=[("Ta", "K"), ("Tb", "K")],
244
+ outputs=[("Q", "W")],
245
+ )
246
+
247
+ def linearized_conductance(self, T):
248
+ """The 4 sigma eps A F T^3 that a small swing about `T` behaves
249
+ like -- useful for sizing, and for deciding whether radiation
250
+ matters at all next to the convection beside it."""
251
+ return 4.0 * self.coefficient * T**3
252
+
253
+ def output(self, t, u):
254
+ return np.array([self.coefficient * (u[0] ** 4 - u[1] ** 4)])
255
+
256
+
257
+ class Advection(Block):
258
+ """Enthalpy carried by a mass flow: `Q = m_dot cp (T_in - T_ref)`.
259
+
260
+ Inputs : [mass flow (kg/s), T_upstream, T_downstream]
261
+ Outputs : [Q into the downstream node (W), outlet temperature (K)]
262
+
263
+ The flow may reverse. When it does the upstream temperature is the
264
+ *downstream* node's, which is what upwinding means and what keeps a
265
+ reversing loop from importing energy from nowhere.
266
+ """
267
+
268
+ def __init__(self, specific_heat=1005.0, name=None):
269
+ if specific_heat <= 0.0:
270
+ raise ValueError("specific heat must be positive")
271
+ self.specific_heat = float(specific_heat)
272
+ super().__init__(
273
+ num_inputs=3,
274
+ num_outputs=2,
275
+ name=name,
276
+ inputs=[("mdot", "kg/s"), ("T_up", "K"), ("T_down", "K")],
277
+ outputs=[("Q", "W"), ("T_out", "K")],
278
+ )
279
+
280
+ def output(self, t, u):
281
+ mdot, t_up, t_down = float(u[0]), float(u[1]), float(u[2])
282
+ source = t_up if mdot >= 0.0 else t_down # upwind
283
+ return np.array([mdot * self.specific_heat * (source - t_down), source])
284
+
285
+
286
+ # ==============================================================================
287
+ # exchanger
288
+ # ==============================================================================
289
+ def exchanger_effectiveness(ntu, ratio, arrangement="counter"):
290
+ """Effectiveness of an exchanger with `ntu = UA / C_min` and capacity
291
+ ratio `C_min / C_max`.
292
+
293
+ The three standard closed forms. `ratio = 0` -- one side condensing
294
+ or evaporating, so its temperature does not move -- gives
295
+ `1 - exp(-NTU)` for every arrangement, which is the limit all three
296
+ of these collapse to.
297
+ """
298
+ ntu = max(float(ntu), 0.0)
299
+ ratio = float(np.clip(ratio, 0.0, 1.0))
300
+
301
+ if ratio < 1e-12:
302
+ return 1.0 - np.exp(-ntu)
303
+
304
+ if arrangement == "counter":
305
+ if abs(ratio - 1.0) < 1e-9:
306
+ return ntu / (1.0 + ntu)
307
+ exponent = np.exp(-ntu * (1.0 - ratio))
308
+ return (1.0 - exponent) / (1.0 - ratio * exponent)
309
+
310
+ if arrangement == "parallel":
311
+ return (1.0 - np.exp(-ntu * (1.0 + ratio))) / (1.0 + ratio)
312
+
313
+ if arrangement == "crossflow": # both fluids unmixed, the usual series
314
+ return 1.0 - np.exp(ntu**0.22 / ratio * (np.exp(-ratio * ntu**0.78) - 1.0))
315
+
316
+ raise ValueError(
317
+ f"unknown arrangement {arrangement!r}; use counter, parallel or crossflow"
318
+ )
319
+
320
+
321
+ class HeatExchanger(Block):
322
+ """Two streams exchanging heat, by effectiveness-NTU.
323
+
324
+ Inputs : [mdot_hot, T_hot_in, mdot_cold, T_cold_in]
325
+ Outputs : [Q (W), T_hot_out, T_cold_out, effectiveness, NTU]
326
+
327
+ No states: an exchanger is fast compared with everything it connects,
328
+ so it is written as the algebraic map it is. Put its metal mass in a
329
+ `ThermalMass` beside it if the warm-up transient matters.
330
+ """
331
+
332
+ def __init__(
333
+ self,
334
+ UA=1000.0,
335
+ cp_hot=4182.0,
336
+ cp_cold=4182.0,
337
+ arrangement="counter",
338
+ name=None,
339
+ ):
340
+ if UA <= 0.0:
341
+ raise ValueError("UA must be positive")
342
+ self.UA = float(UA)
343
+ self.cp_hot = float(cp_hot)
344
+ self.cp_cold = float(cp_cold)
345
+ self.arrangement = arrangement
346
+ super().__init__(
347
+ num_inputs=4,
348
+ num_outputs=5,
349
+ name=name,
350
+ inputs=[
351
+ ("mdot_h", "kg/s"),
352
+ ("Th_in", "K"),
353
+ ("mdot_c", "kg/s"),
354
+ ("Tc_in", "K"),
355
+ ],
356
+ outputs=[
357
+ ("Q", "W"),
358
+ ("Th_out", "K"),
359
+ ("Tc_out", "K"),
360
+ ("effectiveness", None),
361
+ ("NTU", None),
362
+ ],
363
+ )
364
+
365
+ def output_pattern(self):
366
+ """Effectiveness and NTU come from the capacity rates, which is
367
+ to say from the two mass flows -- the temperatures set how much
368
+ heat that effectiveness moves, not the effectiveness itself."""
369
+ return (
370
+ np.zeros((5, 0), dtype=bool),
371
+ np.array(
372
+ [
373
+ [True, True, True, True], # Q
374
+ [True, True, True, True], # T hot out
375
+ [True, True, True, True], # T cold out
376
+ [True, False, True, False], # effectiveness
377
+ [True, False, True, False], # NTU
378
+ ]
379
+ ),
380
+ )
381
+
382
+ def output(self, t, u):
383
+ mdot_h, t_h, mdot_c, t_c = (float(v) for v in u)
384
+ c_hot = abs(mdot_h) * self.cp_hot
385
+ c_cold = abs(mdot_c) * self.cp_cold
386
+
387
+ if c_hot <= 0.0 or c_cold <= 0.0:
388
+ return np.array([0.0, t_h, t_c, 0.0, 0.0])
389
+
390
+ c_min, c_max = min(c_hot, c_cold), max(c_hot, c_cold)
391
+ ntu = self.UA / c_min
392
+ eff = exchanger_effectiveness(ntu, c_min / c_max, self.arrangement)
393
+
394
+ heat = eff * c_min * (t_h - t_c)
395
+ return np.array([heat, t_h - heat / c_hot, t_c + heat / c_cold, eff, ntu])