urson 0.3.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.
urson/matprops.py ADDED
@@ -0,0 +1,734 @@
1
+ # SPDX-FileCopyrightText: 2026 ETH Zurich
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """All material property correlations are stored here."""
5
+
6
+ import functools
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ import CoolProp.CoolProp as CP # noqa: N817
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+ from numba import njit # type: ignore[import-untyped]
14
+
15
+ # Set clipping max and min to prevent errors during convergence
16
+ _P_MAX = 7e8
17
+ _P_MIN = 1e5
18
+ _T_MAX = 1.9e3
19
+ _T_MIN = 274
20
+ _RE_MIN = 1.0e-3 # Reynolds number floor for the friction factor; phi = f Re is 64 below it
21
+ _RE_MAX = 1.0e8 # Reynolds number cap for f and Nu, the end of the Moody chart; f is constant above it
22
+ _PR_MIN = 0.5 # Prandtl number range of the Gnielinski correlation
23
+ _PR_MAX = 2000.0
24
+ _RE_LAMINAR = 2000.0 # upper bound of laminar heat transfer
25
+ _RE_TURBULENT = 2300.0 # lower bound of turbulent heat transfer (Gnielinski)
26
+ _NU_LAM_PIPE = 0.5 * (3.66 + 4.36) # laminar pipe Nu, average of constant wall temperature and heat flux
27
+ _NU_LAM_PLATES = 0.5 * (7.54 + 8.23) # laminar parallel plate Nu (D_h = 2w), same average
28
+
29
+ # Sentinel for an optional input not needed unless explicitly requested (e.g. `get_enthalpy`'s `cp`).
30
+ _EMPTY = np.empty((0, 0))
31
+
32
+
33
+ @functools.lru_cache(maxsize=64)
34
+ def _const_array(value: float, shape: tuple[int, ...]) -> npt.NDArray[np.float64]:
35
+ """Cached constant array, reused across calls with the same (value, shape) pair.
36
+
37
+ Constant array for 0 derivatives in functions. Avoids overhead when called millions
38
+ of times in the Newton loop. Read-only: never mutate the returned array in place.
39
+ """
40
+ arr = np.full(shape, value)
41
+ arr.flags.writeable = False
42
+ return arr
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class PropertyResult:
47
+ """A material property value with its partial derivatives w.r.t. p and T.
48
+
49
+ Always array-valued, even for constant-formula properties, so callers can slice/index
50
+ freely without checking for a bare scalar. Plain data container, no arithmetic operators.
51
+ """
52
+
53
+ value: npt.NDArray[np.float64] # Value of the property
54
+ dp: npt.NDArray[np.float64] # Derivative wrt pressure
55
+ dT: npt.NDArray[np.float64] # Derivative wrt temperature # noqa
56
+
57
+
58
+ @dataclass(frozen=True, slots=True)
59
+ class EnthalpyResult:
60
+ """Fluid enthalpy and its partial derivatives, plus `cp`.
61
+
62
+ cp treated separately as enthalpy derivative minus pressure contribution.
63
+ cp needed for SUPG.
64
+ """
65
+
66
+ value: npt.NDArray[np.float64] # Value of the property
67
+ dp: npt.NDArray[np.float64] # Derivative wrt pressure
68
+ dT: npt.NDArray[np.float64] # Derivative wrt temperature # noqa
69
+ cp: npt.NDArray[np.float64] # specific heat for SUPG calcs
70
+
71
+
72
+ @njit(cache=True) # type: ignore[untyped-decorator]
73
+ def _clip_T(T_in: float) -> float:
74
+ """Cap limits of T to prevent errors in unconverged intermediate states."""
75
+ return max(min(T_in, _T_MAX), _T_MIN)
76
+
77
+
78
+ @njit(cache=True) # type: ignore[untyped-decorator]
79
+ def _clip_p(p_in: float) -> float:
80
+ """Cap limits of p to prevent errors in unconverged intermediate states."""
81
+ return max(min(p_in, _P_MAX), _P_MIN)
82
+
83
+
84
+ def create_abstract_state(fluid_type: str) -> CP.AbstractState:
85
+ """Create a CoolProp AbstractState for a fluid, to be reused across property lookups."""
86
+ return CP.AbstractState("BICUBIC&HEOS", fluid_type)
87
+
88
+
89
+ def get_viscosity(
90
+ T: npt.NDArray[np.float64],
91
+ p: npt.NDArray[np.float64],
92
+ fluid: dict[str, Any],
93
+ T_flow_lagged: bool = False,
94
+ want_dp: bool = False,
95
+ want_dT: bool = False,
96
+ ) -> PropertyResult:
97
+ """Get viscosity and its T/p derivatives, at temperature T [K] and pressure p [Pa].
98
+
99
+ `fluid["viscosity"]` = 0 looks it up from CoolProp instead of treating it as a constant.
100
+ `T_flow_lagged` zeroes dmu_dT when T is not the primary unknown being solved for.
101
+
102
+ `fluid["viscosity"]` = -1 uses a 4 coefficient temperature-only approximation.
103
+ """
104
+ mu0 = fluid["viscosity"]
105
+
106
+ if mu0 > 0:
107
+ # Constant Viscosity
108
+ zeros = _const_array(0.0, T.shape)
109
+ return PropertyResult(_const_array(float(mu0), T.shape), zeros, zeros)
110
+
111
+ # Determine if dT is wanted or not based on lagging.
112
+ want_dT_eff = want_dT and not T_flow_lagged
113
+
114
+ if mu0 == -1:
115
+ # Get visocsity using a 4 coefficient approximation.
116
+ A = 1.856e-14 # Pa-s
117
+ B = 4209 # K
118
+ C = 0.04527 # K^-1
119
+ D = -3.376e-5 # K^-2
120
+
121
+ # Cap limits on temperature
122
+ low_limit = 273.0
123
+ up_limit = 643.0
124
+
125
+ T = np.maximum(T, low_limit)
126
+ T = np.minimum(T, up_limit)
127
+
128
+ mu = A * np.exp(B / T + C * T + D * T**2)
129
+
130
+ out_of_limits = (low_limit >= T) | (up_limit <= T)
131
+ dmu_dT = np.empty(T.shape) if want_dT_eff else _const_array(0.0, T.shape)
132
+ if want_dT_eff:
133
+ dmu_dT = np.where(out_of_limits, 0.0, mu * (-B / T**2 + C + 2 * D * T))
134
+ zeros = _const_array(0.0, T.shape)
135
+
136
+ return PropertyResult(mu, zeros, dmu_dT)
137
+
138
+ # Otherwise use CoolProp viscosity
139
+
140
+ AS = fluid["abstract_state"]
141
+
142
+ # CoolProp has no closed-form viscosity derivative, so dmu/dT is a forward difference.
143
+ dT = 0.5 # K
144
+ dp = 1 # Pa
145
+
146
+ mu = np.empty(T.shape)
147
+ dmu_dp = np.empty(T.shape) if want_dp else _const_array(0.0, T.shape)
148
+ dmu_dT = np.empty(T.shape) if want_dT_eff else _const_array(0.0, T.shape)
149
+
150
+ for i in range(T.size):
151
+ T_i = _clip_T(T.flat[i])
152
+ p_i = _clip_p(p.flat[i])
153
+ AS.update(CP.PT_INPUTS, p_i, T_i)
154
+ mu_i = AS.viscosity()
155
+ mu.flat[i] = mu_i
156
+
157
+ if want_dp:
158
+ AS.update(CP.PT_INPUTS, p_i + dp, T_i)
159
+ mu_plus = AS.viscosity()
160
+ dmu_dp.flat[i] = (mu_plus - mu_i) / dp
161
+
162
+ if want_dT_eff:
163
+ AS.update(CP.PT_INPUTS, p_i, T_i + dT)
164
+ mu_plus = AS.viscosity()
165
+ dmu_dT.flat[i] = (mu_plus - mu_i) / dT
166
+
167
+ return PropertyResult(mu, dmu_dp, dmu_dT)
168
+
169
+
170
+ @njit(cache=True) # type: ignore[untyped-decorator]
171
+ def _eos_linear_kernel_values(
172
+ T: npt.NDArray[np.float64],
173
+ T_flow: npt.NDArray[np.float64],
174
+ p: npt.NDArray[np.float64],
175
+ rho_0: float,
176
+ T0: float,
177
+ p0: float,
178
+ alpha: float,
179
+ Kf: float,
180
+ cp_f: float,
181
+ T_flow_lagged: bool,
182
+ need_density: bool,
183
+ need_u: bool,
184
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
185
+ """Numba kernel for the closed-form linear-density EOS branch of `get_EOS`.
186
+
187
+ Returns two stacked bundles rather than 8 separate arrays: numba boxes a returned tuple
188
+ one element at a time on *every* call regardless of caching, so an 8-way return here (this
189
+ function is called millions of times) was measurably more expensive than the handful of
190
+ microseconds its own arithmetic takes - bundling same-shaped outputs into one array each
191
+ cuts that boxing cost ~4x. `_eos_linear_values` below unpacks the bundles and restores the
192
+ `_EMPTY` convention for fields `need_density`/`need_u` didn't ask for.
193
+
194
+ `main` stacks (rho_value, drho_dp, drho_dT, drho_dT_true, rho_true_value, u_value), all
195
+ T's shape. `duf` stacks (duf_dT, duf_dp), `T[..., 0:1]`'s shape.
196
+ """
197
+ rho_value = np.zeros_like(T_flow)
198
+ drho_dp = np.zeros_like(p)
199
+ drho_dT = np.zeros_like(T_flow)
200
+ drho_dT_true = np.zeros_like(T_flow)
201
+ rho_true_value = np.zeros_like(T_flow)
202
+ if need_density:
203
+ rho_value = rho_0 * (1 - alpha * (T_flow - T0) + 1 / Kf * (p - p0))
204
+ drho_dT_true = np.full(T_flow.shape, -rho_0 * alpha)
205
+ drho_dT = np.zeros(T_flow.shape) if T_flow_lagged else drho_dT_true
206
+ drho_dp = np.full(p.shape, rho_0 / Kf)
207
+ rho_true_value = rho_value
208
+
209
+ u_value = np.zeros_like(T)
210
+ duf_dT = np.zeros_like(T[..., 0:1])
211
+ duf_dp = np.zeros_like(T[..., 0:1])
212
+ if need_u:
213
+ u_value = cp_f * T - alpha * T * p / rho_0 + p**2 / (2 * Kf * rho_0)
214
+ duf_dT = cp_f - alpha * p[..., 0:1] / rho_0
215
+ duf_dp = p[..., 0:1] / (Kf * rho_0) - alpha * T[..., 0:1] / rho_0
216
+
217
+ if need_density and need_u:
218
+ # Density at the same point internal energy uses (T, not T_flow), for cp's exact fidelity.
219
+ # Cheap either way (closed-form), so computed here whenever both are wanted, regardless
220
+ # of whether `T` and `T_flow` actually differ (`T_flow_lagged`).
221
+ rho_true_value = rho_0 * (1 - alpha * (T - T0)) * (1 + 1 / Kf * (p - p0))
222
+ drho_dT_true = np.full(T.shape, -rho_0 * alpha)
223
+
224
+ main = np.empty((6,) + T.shape)
225
+ main[0] = rho_value
226
+ main[1] = drho_dp
227
+ main[2] = drho_dT
228
+ main[3] = drho_dT_true
229
+ main[4] = rho_true_value
230
+ main[5] = u_value
231
+
232
+ duf = np.empty((2,) + duf_dT.shape)
233
+ duf[0] = duf_dT
234
+ duf[1] = duf_dp
235
+
236
+ return main, duf
237
+
238
+
239
+ def _eos_linear_values(
240
+ T: npt.NDArray[np.float64],
241
+ T_flow: npt.NDArray[np.float64],
242
+ p: npt.NDArray[np.float64],
243
+ fluid: dict[str, Any],
244
+ T_flow_lagged: bool,
245
+ need_density: bool,
246
+ need_u: bool,
247
+ ) -> tuple[
248
+ npt.NDArray[np.float64],
249
+ npt.NDArray[np.float64],
250
+ npt.NDArray[np.float64],
251
+ npt.NDArray[np.float64],
252
+ npt.NDArray[np.float64],
253
+ npt.NDArray[np.float64],
254
+ npt.NDArray[np.float64],
255
+ npt.NDArray[np.float64],
256
+ ]:
257
+ """Closed-form (non-CoolProp) `get_EOS` branch for a linear density fluid model."""
258
+ # `float(...)`: config values may parse as Python int (e.g. a YAML "4200" with no decimal
259
+ # point) - numba treats int and float scalar args as different types, so an unnormalized
260
+ # mix costs an extra compiled specialization the first time it's hit.
261
+ rho_0 = float(fluid["density"])
262
+ T0 = float(fluid["reference_temperature"])
263
+ p0 = float(fluid["reference_pressure"])
264
+ alpha = float(fluid["therm_expansion"])
265
+ Kf = float(fluid["bulk_mod"])
266
+ cp_f = float(fluid["specific_heat"])
267
+
268
+ # Evaluated in numba kernel.
269
+ main, duf = _eos_linear_kernel_values(
270
+ T, T_flow, p, rho_0, T0, p0, alpha, Kf, cp_f, T_flow_lagged, need_density, need_u
271
+ )
272
+ rho_value, drho_dp, drho_dT, drho_dT_true, rho_true_value, u_value = main
273
+ duf_dT, duf_dp = duf
274
+
275
+ if not need_density:
276
+ rho_value = drho_dp = drho_dT = drho_dT_true = rho_true_value = _EMPTY
277
+ if not need_u:
278
+ u_value = duf_dp = duf_dT = _EMPTY
279
+
280
+ return rho_value, drho_dp, drho_dT, drho_dT_true, u_value, duf_dp, duf_dT, rho_true_value
281
+
282
+
283
+ def _eos_coolprop_values( # noqa
284
+ T: npt.NDArray[np.float64],
285
+ T_flow: npt.NDArray[np.float64],
286
+ p: npt.NDArray[np.float64],
287
+ fluid: dict[str, Any],
288
+ T_flow_lagged: bool,
289
+ need_density: bool,
290
+ need_u: bool,
291
+ want_dp: bool,
292
+ want_dT: bool,
293
+ ) -> tuple[
294
+ npt.NDArray[np.float64],
295
+ npt.NDArray[np.float64],
296
+ npt.NDArray[np.float64],
297
+ npt.NDArray[np.float64],
298
+ npt.NDArray[np.float64],
299
+ npt.NDArray[np.float64],
300
+ npt.NDArray[np.float64],
301
+ npt.NDArray[np.float64],
302
+ ]:
303
+ """CoolProp `get_EOS` branch: optimized for `AbstractState` update only when actually needed.
304
+
305
+ Density is read at `T_flow`.
306
+ Internal energy at `T`.
307
+ In the operator_split solver, T != T_flow. In the monolithic solver, T = T_flow.
308
+ """
309
+ AS = fluid["abstract_state"]
310
+ same_point = not T_flow_lagged
311
+
312
+ # Initialize containers
313
+ rho_value = np.empty(T_flow.shape) if need_density else _EMPTY
314
+ drho_dp = np.empty(T_flow.shape) if need_density and want_dp else _const_array(0.0, T_flow.shape)
315
+ drho_dT_true = np.empty(T_flow.shape) if need_density and want_dT else _const_array(0.0, T_flow.shape)
316
+
317
+ u_value = np.empty(T.shape) if need_u else _EMPTY
318
+ duf_dT = np.empty(T.shape) if need_u and want_dT else _const_array(0.0, T.shape)
319
+ duf_dp = np.empty(T.shape) if need_u and want_dp else _const_array(0.0, T.shape)
320
+
321
+ # Determine if drho_dT at T is required for evaluating cp
322
+ need_rho_true_at_u_point = need_density and need_u and not same_point
323
+ rho_true_value = np.empty(T.shape) if need_rho_true_at_u_point else rho_value
324
+ drho_true_dT = np.empty(T.shape) if need_rho_true_at_u_point and want_dT else _const_array(0.0, T.shape)
325
+
326
+ for i in range(T.size):
327
+ if need_density:
328
+ T_flow_i = _clip_T(T_flow.flat[i])
329
+ p_i = _clip_p(p.flat[i])
330
+ AS.update(CP.PT_INPUTS, p_i, T_flow_i)
331
+ rho_value.flat[i] = AS.rhomass()
332
+ if want_dp:
333
+ drho_dp.flat[i] = AS.first_partial_deriv(CP.iDmass, CP.iP, CP.iT)
334
+ if want_dT:
335
+ drho_dT_true.flat[i] = AS.first_partial_deriv(CP.iDmass, CP.iT, CP.iP)
336
+
337
+ if need_u:
338
+ if not (need_density and same_point):
339
+ T_i = _clip_T(T.flat[i])
340
+ p_i = _clip_p(p.flat[i])
341
+ AS.update(CP.PT_INPUTS, p_i, T_i)
342
+ # else: `AS` is already at (p_i, T_flow_i) == (p_i, T_i) from the density read above.
343
+ u_value.flat[i] = AS.umass()
344
+ if want_dT:
345
+ duf_dT.flat[i] = AS.first_partial_deriv(CP.iUmass, CP.iT, CP.iP)
346
+ if want_dp:
347
+ duf_dp.flat[i] = AS.first_partial_deriv(CP.iUmass, CP.iP, CP.iT)
348
+
349
+ if need_rho_true_at_u_point:
350
+ rho_true_value.flat[i] = AS.rhomass()
351
+ if want_dT:
352
+ drho_true_dT.flat[i] = AS.first_partial_deriv(CP.iDmass, CP.iT, CP.iP)
353
+
354
+ if need_rho_true_at_u_point:
355
+ drho_dT_true = drho_true_dT
356
+ drho_dT = _const_array(0.0, T_flow.shape) if T_flow_lagged else drho_dT_true
357
+
358
+ return rho_value, drho_dp, drho_dT, drho_dT_true, u_value, duf_dp, duf_dT, rho_true_value
359
+
360
+
361
+ def get_EOS( # noqa: N802
362
+ T: npt.NDArray[np.float64],
363
+ T_flow: npt.NDArray[np.float64],
364
+ p: npt.NDArray[np.float64],
365
+ fluid: dict[str, Any],
366
+ *,
367
+ T_flow_lagged: bool = False,
368
+ want_density: bool = False,
369
+ want_internal_energy: bool = False,
370
+ want_enthalpy: bool = False,
371
+ want_dp: bool = False,
372
+ want_dT: bool = False,
373
+ ) -> tuple[
374
+ PropertyResult, # rho, at T_flow; `_EMPTY`s unless `want_density`
375
+ PropertyResult, # u, at T; `_EMPTY`s unless `want_internal_energy`
376
+ EnthalpyResult, # hf, with `cp`; `_EMPTY`s unless `want_enthalpy`
377
+ ]:
378
+ """Get density, internal energy, and/or enthalpy and their derivatives.
379
+
380
+ Density is evaluated at `T_flow`. Enternal energy is evaluated at `T`.
381
+ Enthalpy is reconstructructed from these base values as hf = u + p / rho,
382
+ resulting in a mixed formulation for enthalpy.
383
+
384
+ The enthalpy return also returns cp stripped of its pressure contribution
385
+ for use in the SUPG formulation.
386
+ """
387
+ need_density = want_density or want_enthalpy
388
+ need_u = want_internal_energy or want_enthalpy
389
+
390
+ if fluid["density"] != 0: # Density = 0 is the sentinel.
391
+ # Use linearized EOS
392
+ rho_value, drho_dp, drho_dT, drho_dT_true, u_value, duf_dp, duf_dT, rho_true_value = (
393
+ _eos_linear_values(T, T_flow, p, fluid, T_flow_lagged, need_density, need_u)
394
+ )
395
+ else:
396
+ # Use real EOS from CoolProp
397
+ rho_value, drho_dp, drho_dT, drho_dT_true, u_value, duf_dp, duf_dT, rho_true_value = (
398
+ _eos_coolprop_values(T, T_flow, p, fluid, T_flow_lagged, need_density, need_u, want_dp, want_dT)
399
+ )
400
+
401
+ # Distribute results to storage dataclasses.
402
+ rho = PropertyResult(_EMPTY, _EMPTY, _EMPTY)
403
+ if want_density:
404
+ rho = PropertyResult(rho_value, drho_dp, drho_dT)
405
+
406
+ u = PropertyResult(_EMPTY, _EMPTY, _EMPTY)
407
+ if want_internal_energy:
408
+ u = PropertyResult(u_value, duf_dp, duf_dT)
409
+
410
+ hf = EnthalpyResult(_EMPTY, _EMPTY, _EMPTY, _EMPTY)
411
+ if want_enthalpy:
412
+ rho_for_hf = PropertyResult(rho_value, drho_dp, drho_dT)
413
+ u_for_hf = PropertyResult(u_value, duf_dp, duf_dT)
414
+ hf = get_enthalpy(
415
+ rho_for_hf,
416
+ u_for_hf,
417
+ p,
418
+ rho_true_value=rho_true_value,
419
+ rho_dT_true=drho_dT_true,
420
+ want_dp=want_dp,
421
+ want_dT=want_dT,
422
+ want_cp=True,
423
+ )
424
+
425
+ return rho, u, hf
426
+
427
+
428
+ @njit(cache=True) # type: ignore[untyped-decorator]
429
+ def _porosity_values(
430
+ p: npt.NDArray[np.float64],
431
+ p_0: npt.NDArray[np.float64],
432
+ phi_0: float,
433
+ K_d: float,
434
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
435
+ """Porosity evaluation kernel.
436
+
437
+ Assume alpha_m = alpha_s and temperature therefore does not affect porosity.
438
+ """
439
+ phi = 1.0 - (1.0 - phi_0) * np.exp(-(p - p_0) / K_d)
440
+ dphi_dp = -(phi - 1.0) / K_d
441
+ return phi, dphi_dp
442
+
443
+
444
+ def get_porosity(
445
+ p: npt.NDArray[np.float64],
446
+ p_0: npt.NDArray[np.float64],
447
+ phi_0: float,
448
+ K_d: float,
449
+ ) -> PropertyResult:
450
+ """Get the current porosity based on the undeformed reference state."""
451
+ phi, dphi_dp = _porosity_values(p, p_0, phi_0, K_d)
452
+ dphi_dT = _const_array(0.0, phi.shape)
453
+
454
+ return PropertyResult(phi, dphi_dp, dphi_dT)
455
+
456
+
457
+ @njit(cache=True) # type: ignore[untyped-decorator]
458
+ def _volumetric_strain_values(
459
+ p: npt.NDArray[np.float64],
460
+ p_0: npt.NDArray[np.float64],
461
+ T: npt.NDArray[np.float64],
462
+ T_0: npt.NDArray[np.float64],
463
+ K_d: float,
464
+ biot: float,
465
+ therm_expansion: float,
466
+ T_flow_lagged: bool,
467
+ volumetric_strain_on: bool,
468
+ ) -> tuple[npt.NDArray[np.float64], float, float]:
469
+ """Volumetric strain kernel."""
470
+ if volumetric_strain_on:
471
+ strain = biot / K_d * (p - p_0) + therm_expansion * (T - T_0)
472
+ dstrain_dp = biot / K_d
473
+ dstrain_dT = 0.0 if T_flow_lagged else therm_expansion
474
+ else:
475
+ strain = np.zeros_like(p)
476
+ dstrain_dp = 0.0
477
+ dstrain_dT = 0.0
478
+ return strain, dstrain_dp, dstrain_dT
479
+
480
+
481
+ def get_volumetricstrain(
482
+ p: npt.NDArray[np.float64],
483
+ p_0: npt.NDArray[np.float64],
484
+ T: npt.NDArray[np.float64],
485
+ T_0: npt.NDArray[np.float64],
486
+ K_d: float,
487
+ biot: float,
488
+ therm_expansion: float,
489
+ T_flow_lagged: bool = False,
490
+ volumetric_strain_on: bool = True,
491
+ ) -> PropertyResult:
492
+ """Get the volumetric strain of the solid skeleton relative to the undeformed reference state.
493
+
494
+ Non-volumetric sources are neglected. `T_flow_lagged` zeroes dstrain_dT when T is not the
495
+ primary unknown. `volumetric_strain_on=False` forces zero strain, e.g. for initial conditions.
496
+ """
497
+ strain, dstrain_dp, dstrain_dT = _volumetric_strain_values(
498
+ p, p_0, T, T_0, K_d, biot, therm_expansion, T_flow_lagged, volumetric_strain_on
499
+ )
500
+ return PropertyResult(
501
+ strain, _const_array(dstrain_dp, strain.shape), _const_array(dstrain_dT, strain.shape)
502
+ )
503
+
504
+
505
+ @njit(cache=True) # type: ignore[untyped-decorator]
506
+ def _porosity_lagrangian_values(
507
+ p: npt.NDArray[np.float64],
508
+ p_0: npt.NDArray[np.float64],
509
+ T: npt.NDArray[np.float64],
510
+ T_0: npt.NDArray[np.float64],
511
+ phi_0: float,
512
+ K_d: float,
513
+ biot: float,
514
+ therm_expansion: float,
515
+ T_flow_lagged: bool,
516
+ volumetric_strain_on: bool,
517
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64]]:
518
+ """Kernel for lagrangian porosity: phi_L = phi * (1 + volumetric strain)."""
519
+ phi, dphi_dp = _porosity_values(p, p_0, phi_0, K_d)
520
+ strain, dstrain_dp, dstrain_dT = _volumetric_strain_values(
521
+ p, p_0, T, T_0, K_d, biot, therm_expansion, T_flow_lagged, volumetric_strain_on
522
+ )
523
+
524
+ one_plus_strain = 1.0 + strain
525
+ phi_L = phi * one_plus_strain
526
+ dphi_L_dp = dphi_dp * one_plus_strain + phi * dstrain_dp
527
+ dphi_L_dT = phi * dstrain_dT # d_phi_dT = 0 assuming alpha_m = alpha_s
528
+
529
+ return phi_L, dphi_L_dp, dphi_L_dT
530
+
531
+
532
+ def get_porosity_lagrangian(
533
+ p: npt.NDArray[np.float64],
534
+ p_0: npt.NDArray[np.float64],
535
+ T: npt.NDArray[np.float64],
536
+ T_0: npt.NDArray[np.float64],
537
+ phi_0: float,
538
+ K_d: float,
539
+ biot: float,
540
+ therm_expansion: float,
541
+ T_flow_lagged: bool = False,
542
+ volumetric_strain_on: bool = True,
543
+ ) -> PropertyResult:
544
+ """Get the Lagrangian porosity which includes the volumetric strain in the deformed state.
545
+
546
+ Non-volumetric strain sources are neglected. `T_flow_lagged` zeroes dphi_L/dT when T is
547
+ not the primary unknown. `volumetric_strain_on=False` forces zero strain.
548
+ """
549
+ phi_L, dphi_L_dp, dphi_L_dT = _porosity_lagrangian_values(
550
+ p, p_0, T, T_0, phi_0, K_d, biot, therm_expansion, T_flow_lagged, volumetric_strain_on
551
+ )
552
+ return PropertyResult(phi_L, dphi_L_dp, dphi_L_dT)
553
+
554
+
555
+ @njit(cache=True) # type: ignore[untyped-decorator]
556
+ def _enthalpy_values(
557
+ rho_value: npt.NDArray[np.float64],
558
+ rho_dp: npt.NDArray[np.float64],
559
+ rho_dT: npt.NDArray[np.float64],
560
+ u_value: npt.NDArray[np.float64],
561
+ u_dp: npt.NDArray[np.float64],
562
+ u_dT: npt.NDArray[np.float64],
563
+ p: npt.NDArray[np.float64],
564
+ want_dp: bool,
565
+ want_dT: bool,
566
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64]]:
567
+ """Numba kernel for evaluating enthalpy: hf = u_f + p / rho_f."""
568
+ hf = u_value + p / rho_value
569
+ dhf_dT = np.zeros_like(hf)
570
+ dhf_dp = np.zeros_like(hf)
571
+ if want_dT:
572
+ dhf_dT = u_dT - p / rho_value**2 * rho_dT
573
+ if want_dp:
574
+ dhf_dp = u_dp + 1 / rho_value - p / rho_value**2 * rho_dp
575
+ return hf, dhf_dp, dhf_dT
576
+
577
+
578
+ @njit(cache=True) # type: ignore[untyped-decorator]
579
+ def _enthalpy_cp_values(
580
+ rho_true_value: npt.NDArray[np.float64],
581
+ u_dT: npt.NDArray[np.float64],
582
+ p: npt.NDArray[np.float64],
583
+ rho_dT_true: npt.NDArray[np.float64],
584
+ ) -> npt.NDArray[np.float64]:
585
+ """cp, (dh/dT)_p with the pressure-work term stripped out for SUPG's Peclet number."""
586
+ return u_dT - p / rho_true_value**2 * rho_dT_true
587
+
588
+
589
+ def get_enthalpy(
590
+ rho_f: PropertyResult,
591
+ u_f: PropertyResult,
592
+ p: npt.NDArray[np.float64],
593
+ *,
594
+ rho_true_value: npt.NDArray[np.float64] = _EMPTY,
595
+ rho_dT_true: npt.NDArray[np.float64] = _EMPTY,
596
+ want_dp: bool = False,
597
+ want_dT: bool = False,
598
+ want_cp: bool = False,
599
+ ) -> EnthalpyResult:
600
+ """Get fluid enthalpy from already-evaluated density and internal energy.
601
+
602
+ hf = u_f + p / rho_f.
603
+ """
604
+ # Evaluated in numba kernel.
605
+ hf, dhf_dp, dhf_dT = _enthalpy_values(
606
+ rho_f.value, rho_f.dp, rho_f.dT, u_f.value, u_f.dp, u_f.dT, p, want_dp, want_dT
607
+ )
608
+
609
+ cp = np.zeros(hf.shape)
610
+ if want_cp:
611
+ cp = _enthalpy_cp_values(rho_true_value, u_f.dT, p, rho_dT_true)
612
+
613
+ return EnthalpyResult(hf, dhf_dp, dhf_dT, cp)
614
+
615
+
616
+ def get_effective_permeability(
617
+ kf: npt.NDArray[np.float64] | float,
618
+ T: npt.NDArray[np.float64], # noqa
619
+ p: npt.NDArray[np.float64], # noqa
620
+ fluid: dict[str, Any], # noqa
621
+ T_flow_lagged: bool = False, # noqa
622
+ ) -> PropertyResult:
623
+ """Get the effective permeability. Apply Forchheimer flow and other modifiers."""
624
+ kf_eff = np.asarray(kf, dtype=np.float64)
625
+ dkf_dT = _const_array(0.0, T.shape)
626
+ dkf_dp = _const_array(0.0, T.shape)
627
+
628
+ return PropertyResult(kf_eff, dkf_dp, dkf_dT)
629
+
630
+
631
+ def get_friction_factor(
632
+ Re: npt.NDArray[np.float64], rel_roughness: float
633
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
634
+ """Churchill (1977) Darcy friction factor as phi = f Re and dphi/dRe.
635
+
636
+ Smooth across laminar, transitional, and turbulent flow; phi -> 64 as Re -> 0. Evaluated in
637
+ log space to avoid overflow; f is held constant above `_RE_MAX`.
638
+ """
639
+ Re = np.maximum(Re, _RE_MIN)
640
+ Re_c = np.minimum(Re, _RE_MAX)
641
+ r7 = (7.0 / Re_c) ** 0.9
642
+ t = r7 + 0.27 * rel_roughness
643
+ L = -np.log(t)
644
+ dL = 0.9 * r7 / (Re_c * t)
645
+
646
+ # ln of the turbulent term A = (2.457 L)^16 and transition term B = (37530/Re)^16
647
+ with np.errstate(divide="ignore"):
648
+ ln_aL = np.log(np.abs(2.457 * L)) # -inf when L = 0, giving A = 0
649
+ lnA = 16.0 * ln_aL
650
+ lnB = 16.0 * np.log(37530.0 / Re_c)
651
+ lnAB = np.logaddexp(lnA, lnB)
652
+
653
+ # P = Re^12 (A + B)^-1.5 and phi = 8 (8^12 + P)^(1/12)
654
+ lnP = 12.0 * np.log(Re_c) - 1.5 * lnAB
655
+ ln_sum = np.logaddexp(12.0 * np.log(8.0), lnP)
656
+ phi_c = 8.0 * np.exp(ln_sum / 12.0)
657
+
658
+ # Chain rule through ln P, with dA/(A + B) and dB/(A + B) kept in log space
659
+ dA_AB = 16.0 * 2.457 * np.sign(L) * np.exp(15.0 * ln_aL - lnAB) * dL
660
+ dB_AB = -16.0 * np.exp(lnB - lnAB) / Re_c
661
+ dlnP = 12.0 / Re_c - 1.5 * (dA_AB + dB_AB)
662
+ dphi_c = phi_c * np.exp(lnP - ln_sum) * dlnP / 12.0
663
+
664
+ # Above the cap, f = phi_c / Re_c is constant, so phi = f Re
665
+ capped = Re > _RE_MAX
666
+ f_c = phi_c / Re_c
667
+ phi = np.where(capped, f_c * Re, phi_c)
668
+ dphi = np.where(capped, f_c, dphi_c)
669
+ return phi, dphi
670
+
671
+
672
+ def _gnielinski_values(
673
+ Re: npt.NDArray[np.float64], Pr: npt.NDArray[np.float64], rel_roughness: float
674
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64]]:
675
+ """Gnielinski turbulent Nu, with Churchill Darcy f, and its derivatives wrt Re and Pr."""
676
+ phi, dphi = get_friction_factor(Re, rel_roughness)
677
+ f = phi / Re
678
+ df_dRe = (dphi - f) / Re
679
+
680
+ # Nu = k (Re - 1000) Pr / D, with k = f/8 and D = 1 + 12.7 sqrt(k) (Pr^(2/3) - 1)
681
+ k = f / 8.0
682
+ s = np.sqrt(k)
683
+ pr_term = Pr ** (2.0 / 3.0) - 1.0
684
+ D = 1.0 + 12.7 * s * pr_term
685
+ Nu = k * (Re - 1000.0) * Pr / D
686
+
687
+ # Quotient rule through k(Re) and Pr
688
+ dk_dRe = df_dRe / 8.0
689
+ dD_dRe = 12.7 * pr_term * dk_dRe / (2.0 * s)
690
+ dNu_dRe = ((dk_dRe * (Re - 1000.0) + k) * Pr - Nu * dD_dRe) / D
691
+ dD_dPr = 12.7 * s * (2.0 / 3.0) * Pr ** (-1.0 / 3.0)
692
+ dNu_dPr = (k * (Re - 1000.0) - Nu * dD_dPr) / D
693
+ return Nu, dNu_dRe, dNu_dPr
694
+
695
+
696
+ def get_nusselt_number(
697
+ Re: npt.NDArray[np.float64],
698
+ Pr: npt.NDArray[np.float64],
699
+ rel_roughness: float,
700
+ *,
701
+ parallel_plates: bool,
702
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64]]:
703
+ """Nusselt number and its derivatives wrt Re and Pr, for pipes or parallel plates.
704
+
705
+ Constant laminar Nu below Re = 2000, Gnielinski above Re = 2300, and log-interpolated between.
706
+ Re and Pr are clipped to Gnielinski's range of validity (`_RE_MAX`, `_PR_MIN`-`_PR_MAX`).
707
+ """
708
+ Re = np.asarray(Re, dtype=np.float64)
709
+ Pr_in = np.asarray(Pr, dtype=np.float64)
710
+ Nu_lam = _NU_LAM_PLATES if parallel_plates else _NU_LAM_PIPE
711
+
712
+ # Pr clipped into Gnielinski's range of validity; Nu is constant in Pr outside it
713
+ Pr = np.clip(Pr_in, _PR_MIN, _PR_MAX)
714
+ pr_inside = (Pr_in > _PR_MIN) & (Pr_in < _PR_MAX)
715
+
716
+ # Turbulent: Gnielinski, evaluated with Re clipped into its range of validity
717
+ Nu_turb, dturb_dRe, dturb_dPr = _gnielinski_values(np.clip(Re, _RE_TURBULENT, _RE_MAX), Pr, rel_roughness)
718
+ dturb_dRe = np.where(Re > _RE_MAX, 0.0, dturb_dRe)
719
+
720
+ # Transition: log-interpolate from Nu_lam at Re = 2000 to Gnielinski at Re = 2300
721
+ Nu_2300, _, d2300_dPr = _gnielinski_values(np.full_like(Re, _RE_TURBULENT), Pr, rel_roughness)
722
+ log_span = np.log(_RE_TURBULENT / _RE_LAMINAR)
723
+ w = np.log(np.clip(Re, _RE_LAMINAR, _RE_TURBULENT) / _RE_LAMINAR) / log_span
724
+ Nu_trans = Nu_lam ** (1.0 - w) * Nu_2300**w
725
+ dtrans_dRe = Nu_trans * np.log(Nu_2300 / Nu_lam) / (np.maximum(Re, _RE_MIN) * log_span)
726
+ dtrans_dPr = Nu_trans * w * d2300_dPr / Nu_2300
727
+
728
+ # Select the regime
729
+ laminar = Re <= _RE_LAMINAR
730
+ turbulent = Re >= _RE_TURBULENT
731
+ Nu = np.where(laminar, Nu_lam, np.where(turbulent, Nu_turb, Nu_trans))
732
+ dNu_dRe = np.where(laminar, 0.0, np.where(turbulent, dturb_dRe, dtrans_dRe))
733
+ dNu_dPr = np.where(laminar | ~pr_inside, 0.0, np.where(turbulent, dturb_dPr, dtrans_dPr))
734
+ return Nu, dNu_dRe, dNu_dPr