Source code for openairbearing.core.gas

"""Gas property models for the film and porous-flow equations.

The solvers never assume a particular equation of state. They use the gas
through four functions of absolute pressure (Pa) at the (isothermal) gas
temperature, and the derivatives that the Newton iteration needs (``Gas``):

    rho(p)   density, kg/m³
    mu(p)    dynamic viscosity, Pa·s
    phi(p)   flow potential, the integral of rho/mu over pressure, kg/(m³·s)
    p_from_phi(phi)   its inverse

Pressure-driven mass flux in a thin film and Darcy mass flux in a porous
body are both proportional to rho/mu times the pressure gradient, which is
the gradient of phi. For an ideal gas with constant viscosity,
phi = p² / (2 R T mu), which recovers the usual p² formulation. A non-ideal
gas only has to supply the same functions.

Three ways to get a gas, and ``gas_at`` to pick among them by name:

- the presets AIR, NITROGEN, HYDROGEN, HELIUM: ideal gases at 20 °C;
- ``ideal_gas(name, T)``: an ideal gas at any temperature, with its
  viscosity at that temperature (the gases of ``FLUIDS``: those four, argon
  and carbon dioxide);
- ``real_gas(name, T, p_max)``: density and viscosity as functions of
  pressure from the gas's equation of state, tabulated at temperature T
  (the same six gases).

The last two take their properties from the CoolProp library (the "gas"
extra: pip install "openairbearing[gas]"); ``TabulatedGas`` takes a table
from any other source. The film is isothermal at the gas temperature given,
which is the temperature of the gas entering the bearing when the bearing
has that temperature too.
"""

from __future__ import annotations

from dataclasses import dataclass, replace
from typing import Protocol, runtime_checkable

import numpy as np
from scipy.interpolate import CubicSpline, PchipInterpolator

from .params import param

__all__ = [
    "AIR",
    "FLUIDS",
    "HELIUM",
    "HYDROGEN",
    "NITROGEN",
    "PRESETS",
    "Gas",
    "IdealGas",
    "TabulatedGas",
    "gas_at",
    "ideal_gas",
    "real_gas",
]


[docs] @runtime_checkable class Gas(Protocol): """What a gas model must provide. All pressures are absolute, in Pa. Every function takes a number or an array and returns the same shape. rho(p), drho_dp(p) density, kg/m³, and its slope in p mu(p) dynamic viscosity, Pa·s phi(p) flow potential, kg/(m³·s) dphi_dp(p), d2phi_dp2(p) rho/mu and its slope in p p_from_phi(phi) pressure at a flow potential, Pa """ name: str
[docs] def rho(self, p): ...
[docs] def drho_dp(self, p): ...
[docs] def mu(self, p): ...
[docs] def phi(self, p): ...
[docs] def dphi_dp(self, p): ...
[docs] def d2phi_dp2(self, p): ...
[docs] def p_from_phi(self, phi): ...
[docs] @dataclass(frozen=True) class IdealGas: """Isothermal ideal gas with pressure-independent viscosity. rho = p/(R T) and phi = p²/(2 R T mu0). The functions are those of ``Gas``. """ name: str = param("air", "Gas") mu0: float = param(1.81e-5, "Viscosity", "Pa·s", "µPa·s", 1e6, minimum=1e-7) R: float = param(287.05, "Specific gas constant", "J/(kg·K)", minimum=1.0) T: float = param(293.15, "Temperature", "K", minimum=1.0)
[docs] def rho(self, p): return np.asarray(p) / (self.R * self.T)
[docs] def drho_dp(self, p): return np.ones_like(np.asarray(p, dtype=float)) / (self.R * self.T)
[docs] def mu(self, p): return self.mu0 * np.ones_like(np.asarray(p, dtype=float))
[docs] def phi(self, p): return np.asarray(p) ** 2 / (2.0 * self.R * self.T * self.mu0)
[docs] def dphi_dp(self, p): return np.asarray(p) / (self.R * self.T * self.mu0)
[docs] def d2phi_dp2(self, p): return np.ones_like(np.asarray(p, dtype=float)) / (self.R * self.T * self.mu0)
[docs] def p_from_phi(self, phi): return np.sqrt(2.0 * self.R * self.T * self.mu0 * np.asarray(phi))
[docs] def at(self, T: float, mu0: float | None = None) -> IdealGas: """Same gas at another temperature T (K). mu0 is the viscosity at that temperature, Pa·s; left out, the viscosity stays what it was. """ return replace(self, T=T, mu0=self.mu0 if mu0 is None else mu0)
# Ideal-gas presets at 20 °C. Viscosities are rounded handbook values. AIR = IdealGas("air", mu0=1.81e-5, R=287.05) NITROGEN = IdealGas("nitrogen", mu0=1.76e-5, R=296.80) HYDROGEN = IdealGas("hydrogen", mu0=0.88e-5, R=4124.2) HELIUM = IdealGas("helium", mu0=1.96e-5, R=2077.1) PRESETS = {gas.name: gas for gas in (AIR, NITROGEN, HYDROGEN, HELIUM)}
[docs] class TabulatedGas: """A gas given by its density and viscosity on a grid of pressures. The flow potential is integrated from the table, and everything is interpolated with cubic splines, so the derivatives the solver needs are smooth. Use it up to the highest tabulated pressure only; below the lowest one the gas is continued as an ideal gas with the viscosity of that pressure. The functions are those of ``Gas``. name: name of the gas. T: temperature of the table, K. p: absolute pressures, Pa: at least 8, increasing (ValueError otherwise). rho, mu: density in kg/m³ and dynamic viscosity in Pa·s at those pressures. """ def __init__(self, name: str, T: float, p, rho, mu): p, rho, mu = (np.asarray(v, dtype=float) for v in (p, rho, mu)) if p.ndim != 1 or p.size < 8 or np.any(np.diff(p) <= 0.0): raise ValueError("Need at least 8 increasing pressures.") self.name, self.T = name, float(T) self.p_min, self.p_max = float(p[0]), float(p[-1]) self._rho = CubicSpline(p, rho) self._mu = CubicSpline(p, mu) ratio = CubicSpline(p, rho / mu) # ideal gas below the table: rho/mu is proportional to p there phi_min = 0.5 * rho[0] / mu[0] * p[0] self._phi = ratio.antiderivative() self._phi_min = phi_min - float(self._phi(p[0])) self._ratio = ratio self._slope = rho[0] / mu[0] / p[0] # (rho/mu) / p below the table self._inverse = PchipInterpolator(self.phi(p), p) def _low(self, p): return np.asarray(p) < self.p_min
[docs] def rho(self, p): p = np.asarray(p, dtype=float) return np.where( self._low(p), self._rho(self.p_min) * p / self.p_min, self._rho(p) )
[docs] def drho_dp(self, p): p = np.asarray(p, dtype=float) return np.where( self._low(p), self._rho(self.p_min) / self.p_min, self._rho(p, 1) )
[docs] def mu(self, p): return self._mu(np.clip(np.asarray(p, dtype=float), self.p_min, None))
[docs] def phi(self, p): p = np.asarray(p, dtype=float) return np.where( self._low(p), 0.5 * self._slope * p**2, self._phi(p) + self._phi_min )
[docs] def dphi_dp(self, p): p = np.asarray(p, dtype=float) return np.where(self._low(p), self._slope * p, self._ratio(p))
[docs] def d2phi_dp2(self, p): p = np.asarray(p, dtype=float) return np.where(self._low(p), self._slope, self._ratio(p, 1))
[docs] def p_from_phi(self, phi): phi = np.asarray(phi, dtype=float) low = phi < 0.5 * self._slope * self.p_min**2 p = np.where(low, np.sqrt(2.0 * np.abs(phi) / self._slope), self._inverse(phi)) for _ in range(3): # polish the monotone interpolant p = p - (self.phi(p) - phi) / self.dphi_dp(p) return p
def __repr__(self): return ( f"TabulatedGas({self.name!r}, T={self.T:g} K, " f"{self.p_min:g}-{self.p_max:g} Pa)" )
# name used here -> name of the fluid in CoolProp FLUIDS = { "air": "Air", "nitrogen": "Nitrogen", "hydrogen": "Hydrogen", "helium": "Helium", "argon": "Argon", "carbon dioxide": "CarbonDioxide", } _R_UNIVERSAL = 8.314462618 # J/(mol·K) def _coolprop(name: str): if name not in FLUIDS: raise ValueError(f"Unknown gas {name!r}; known: {sorted(FLUIDS)}") try: from CoolProp.CoolProp import PropsSI except ModuleNotFoundError as exc: raise ModuleNotFoundError( "Gas properties at other temperatures and real-gas properties need " 'the CoolProp library: pip install "openairbearing[gas]"' ) from exc return PropsSI, FLUIDS[name]
[docs] def ideal_gas(name: str, T: float = 293.15) -> IdealGas: """Ideal gas at temperature T (K), with its viscosity at T and 1 atm. name is one of ``FLUIDS``. Needs the CoolProp library. """ props, fluid = _coolprop(name) R = _R_UNIVERSAL / props("M", fluid) mu0 = float(props("V", "T", T, "P", 101325.0, fluid)) return IdealGas(name, mu0=mu0, R=R, T=T)
[docs] def real_gas( name: str, T: float = 293.15, p_max: float = 2e6, p_min: float = 2e3, n: int = 200 ) -> TabulatedGas: """Real gas at temperature T (K), tabulated from p_min to p_max (Pa). Density and viscosity come from the gas's equation of state and transport correlations (CoolProp), at n pressures in geometric progression. name is one of ``FLUIDS``. p_max must cover the supply pressure. """ props, fluid = _coolprop(name) p = np.geomspace(p_min, p_max, n) rho = np.array([props("D", "T", T, "P", pk, fluid) for pk in p]) mu = np.array([props("V", "T", T, "P", pk, fluid) for pk in p]) return TabulatedGas(name, T, p, rho, mu)
[docs] def gas_at(name: str, T: float = 293.15, real: bool = False, p_max: float = 2e6) -> Gas: """The gas model for a name, a temperature and a choice of ideal or real. name is one of ``FLUIDS`` (ValueError otherwise), T in K. real=True gives ``real_gas`` tabulated up to p_max (Pa), which must cover the supply pressure; otherwise the gas is ideal. The presets (ideal, 20 °C) are returned as they are, so that the common case needs no property library. """ if name not in FLUIDS: raise ValueError(f"Unknown gas {name!r}; known: {sorted(FLUIDS)}") if real: return real_gas(name, T, p_max=p_max) if name in PRESETS and abs(T - PRESETS[name].T) < 1e-9: return PRESETS[name] return ideal_gas(name, T)