Source code for tmhp.compressor_efficiency

"""Compressor efficiency: the three quantities, the default maps and the scale factors on them.

A heat-pump model describes its compressor by three quantities, each defined
from the states and flows around the compressor:

``eta_v`` -- volumetric efficiency
    ``eta_v = m_dot / (rho_1 V N)``: the delivered fraction of the swept
    volume. It sets the mass flow.
``eta_ov`` -- overall efficiency
    ``eta_ov = m_dot (h_2s - h_1) / E_cmp``: the isentropic enthalpy rise of
    the flow over the electrical input at the **inverter input** (grid side;
    the drive is not modelled apart from the compressor). It sets the power.
``f_loss`` -- heat-loss share
    ``f_loss = Q_cmp_loss / E_cmp``: the share of the electrical input that
    leaves the compressor as heat instead of reaching the gas.

The cycle closes the compressor with these three alone (#274)::

    m_dot      = rho_1 V N eta_v
    E_cmp      = m_dot (h_2s - h_1) / eta_ov
    Q_cmp_loss = f_loss E_cmp
    h_2        = h_1 + (E_cmp - Q_cmp_loss) / m_dot

so the discharge enthalpy follows from the energy balance and has no
efficiency of its own (:func:`discharge_enthalpy`). No isentropic or
electromechanical efficiency is defined: with heat leaving the shell, the
irreversibility of the compression cannot be told apart from the mechanical
and electrical losses by what is measured outside the compressor. ``h_2`` may
lie below ``h_2s`` when the heat loss is large (``f_loss > 1 - eta_ov``).

Default maps
------------
Three maps of one compressor, fitted to the 134 measured points of a 46 cm3
R290 scroll (Ossorio's thesis, Appendix 1; the same tests as Compressor A of
Ossorio & Navarro-Peris 2023) with the electrical input as compressor plus
inverter (#217, #218), where each quantity is computed from the measured
states as defined above (``h_2`` from the measured discharge temperature).
Each is a polynomial in the pressure ratio ``PR``, the speed ``N`` in rev/s
and, for ``eta_v`` and ``eta_ov``, the evaporating saturation temperature
``T_e`` in degrees C, both as they are (#247)::

    eta_v  = c . [1, PR, PR^2, N, N^2, PR N, T_e]
    f_loss = c . [1, PR, PR^2, N, N^2, PR N]
    eta_ov = c . [1, l, l^2, l^3, N, N^2, l N, T_e]        l = ln PR

``eta_ov`` is cubic in ``ln PR`` because the measured efficiency rises steeply
at low pressure ratios and falls slowly at high ones; ``eta_v`` and ``f_loss``
need no logarithm. Which basis a map uses is recorded with its coefficients
(``MAP_TERMS``). The evaporating temperature is there because the measured
``eta_ov`` and ``eta_v`` differ at one pressure ratio and speed: at PR 3 and
70 rev/s the map's ``eta_ov`` rises from 0.62 to 0.69 between T_e = -10 and
15 degrees C. ``f_loss`` does not (a T_e term leaves its error unchanged). The
same maps serve every refrigerant and every machine. The fit, its data and its
scores are archived in ``validation/coefficients/<COEFFICIENT_VERSION>/``
(README there); the constants between the ``GENERATED`` markers below are
emitted from that archive by ``validation/compressor_maps/ossorio_te/emit.py``.

Scale factors
-------------
A model does not take efficiencies of its own: the maps are the same for
every machine, and a target machine is followed by scaling them
(:class:`CompressorMapScale`, constructor argument ``compressor_scale``). The
level factors scale each quantity; the shape factors move and stretch the
``eta_ov`` map about its peak::

    eta_v'        = k_v eta_v(PR, N, T_e)
    f_loss'       = k_f f_loss(PR, N)
    1/eta_ov' - 1 = k_ov (1/eta_ov(PR~, N~, T_e) - 1)
    N~  = N* + (N - N* - delta_N) / w_N
    PR~ = PR* ((PR - delta_r) / PR*) ** (1 / w_r)

with ``N* = 70 rev/s`` and ``PR* = 3.79``, the peak of the default ``eta_ov``
map (rounded; :data:`ETA_OV_PEAK_RPS`, :data:`ETA_OV_PEAK_PR`). The peak moves
by ``delta_N`` in speed and by ``delta_r`` in pressure ratio (either may be
negative); ``w_N`` and ``w_r`` stretch the map about the moved peak (``w > 1``
wider). ``w_r`` stretches the ratio to the peak, which is a uniform stretch
in ``ln PR``, the coordinate of the ``eta_ov`` map. The defaults (all level
factors 1, shifts 0, widths 1) give the maps as they are.

Outside their data the maps are followed as they are -- nothing is held or
clamped there; the range rule below is the only bound.

Rules
-----
* Range (:func:`check_efficiencies`): ``eta_v > 0`` (finite, no upper bound),
  ``0 < eta_ov <= 1`` and ``0 <= f_loss < 1``. A value outside makes the
  operating point infeasible (:class:`InvalidCompressorEfficiency`); nothing
  is clipped.
* Data domain: the maps carry the domain of their fitting data
  (:class:`MapDomain`): the speeds 30-110 rev/s and the convex (PR, T_e) hull
  of the measured points. It feeds the ``efficiency_extrapolated`` flag of a
  result and nothing else (:meth:`CompressorMapScale.extrapolated`); the
  ``eta_ov`` map is checked at its transformed coordinates.
"""

from __future__ import annotations

import math
from collections.abc import Callable
from dataclasses import dataclass, fields
from functools import wraps
from typing import Any, NamedTuple, TypeVar, cast

# --- BEGIN GENERATED Ossorio map coefficients ---
# Emitted by ``python -m validation.compressor_maps.ossorio_te.emit`` from
# validation/coefficients/ossorio-r290-2026-11-30/coefficients.json.
COEFFICIENT_VERSION = "ossorio-r290-2026-11-30"
MAP_TERMS: dict[str, tuple[str, ...]] = {
    "eta_ov": ("1", "ln PR", "(ln PR)^2", "(ln PR)^3", "N", "N^2", "N ln PR", "T_e"),
    "eta_v": ("1", "PR", "PR^2", "N", "N^2", "N PR", "T_e"),
    "f_loss": ("1", "PR", "PR^2", "N", "N^2", "N PR"),
}
MAP_COEFFICIENTS: dict[str, tuple[float, ...]] = {
    "eta_ov": (
        0.08905261072268404,
        0.901955328983883,
        -0.5552874938098128,
        0.09515212021536011,
        0.0023641528670562267,
        -2.645860394145938e-05,
        0.0010081316041961295,
        0.002869564011673403,
    ),
    "eta_v": (
        0.9234128012358083,
        -0.014353038441887952,
        6.372018420399103e-05,
        0.001908677741734932,
        -1.2320343860275015e-05,
        6.0803586946354266e-05,
        0.001313709397835127,
    ),
    "f_loss": (
        0.12734828741090917,
        0.017281932102947296,
        8.119406704140209e-05,
        -0.0012593190760719322,
        1.0395861625440983e-05,
        -0.00017572178731773466,
    ),
}
MAP_DOMAIN: dict[str, Any] = {
    "N_rps": (30.0, 110.0),
    "hull_PR_Te": (
        (8.226673213867404, -30.22),
        (12.667054686847852, -30.11),
        (2.22284856625581, 25.0),
        (1.796478696296018, 25.05),
        (1.440381993403251, 24.99),
        (1.439120643473566, 24.97),
        (1.7587340092509858, 0.01),
        (3.402611370202053, -19.91),
        (3.4247891359756553, -20.01),
    ),
}
# --- END GENERATED Ossorio map coefficients ---

#: The three quantities, in the order :class:`CompressorEfficiencies` holds them.
QUANTITIES = ("eta_v", "eta_ov", "f_loss")

#: Speed [rev/s] and pressure ratio of the peak of the default ``eta_ov`` map,
#: rounded (the exact grid peak is PR 3.786, 70.04 rev/s, the same at every
#: T_e because T_e enters the map as a plain additive term): the centre of the
#: shape factors of :class:`CompressorMapScale`.
ETA_OV_PEAK_RPS = 70.0
ETA_OV_PEAK_PR = 3.79


[docs] class InvalidCompressorEfficiency(ValueError): """An evaluated compressor quantity lies outside its range, or a map has no value at the point."""
[docs] @dataclass(frozen=True) class HullDomain: """Convex polygon in a plane, vertices counter-clockwise (used for the data domain).""" vertices: tuple[tuple[float, float], ...]
[docs] def contains(self, x: float, y: float, rtol: float = 0.0) -> bool: """Whether (x, y) lies inside (``rtol``: also accept a point that far outside, relatively).""" if self._inside(x, y): return True if rtol <= 0.0: return False return any( self._inside(x * (1.0 + a * rtol), y * (1.0 + b * rtol)) for a, b in ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)) )
def _inside(self, x: float, y: float) -> bool: if not (math.isfinite(x) and math.isfinite(y)): return False v = self.vertices sign = 0.0 for (x1, y1), (x2, y2) in zip(v, v[1:] + v[:1], strict=True): cross = (x2 - x1) * (y - y1) - (y2 - y1) * (x - x1) if cross == 0.0: continue if sign == 0.0: sign = cross elif (cross > 0.0) != (sign > 0.0): return False return True
def _hull(vertices: tuple[tuple[float, float], ...]) -> HullDomain: """Hull with counter-clockwise vertices (the archive writes scipy ConvexHull order).""" area = sum(x1 * y2 - x2 * y1 for (x1, y1), (x2, y2) in zip(vertices, vertices[1:] + vertices[:1], strict=True)) return HullDomain(tuple(vertices) if area > 0 else tuple(reversed(vertices)))
[docs] @dataclass(frozen=True) class MapDomain: """Data domain of the default maps: a speed range and the convex (PR, T_e) hull of the measured points. Used for the ``efficiency_extrapolated`` flag only: outside it the maps are followed as they are (no hold, no clamp). """ hull_PR_Te: HullDomain rps_range: tuple[float, float]
[docs] def contains(self, pressure_ratio: float, rps: float, T_evap_C: float | None = None, rtol: float = 0.0) -> bool: """Whether (PR, N[, T_e]) lies inside; without ``T_evap_C`` only the speed range is checked.""" lo, hi = self.rps_range if not (math.isfinite(rps) and lo * (1.0 - rtol) <= rps <= hi * (1.0 + rtol)): return False if T_evap_C is None: return True return self.hull_PR_Te.contains(pressure_ratio, T_evap_C, rtol=rtol)
DOMAIN = MapDomain(_hull(MAP_DOMAIN["hull_PR_Te"]), MAP_DOMAIN["N_rps"]) def _pr_terms(pressure_ratio: float, rps: float) -> tuple[float, ...]: return (1.0, pressure_ratio, pressure_ratio * pressure_ratio, rps, rps * rps, pressure_ratio * rps) def _ln_pr_terms(pressure_ratio: float, rps: float) -> tuple[float, ...]: log_pr = math.log(pressure_ratio) return (1.0, log_pr, log_pr * log_pr, log_pr**3, rps, rps * rps, log_pr * rps) #: The two pressure-ratio bases, by the term names the archive records (``MAP_TERMS``). _BASES: dict[tuple[str, ...], Callable[[float, float], tuple[float, ...]]] = { ("1", "PR", "PR^2", "N", "N^2", "N PR"): _pr_terms, ("1", "ln PR", "(ln PR)^2", "(ln PR)^3", "N", "N^2", "N ln PR"): _ln_pr_terms, } def _basis_of(quantity: str) -> Callable[[float, float], tuple[float, ...]]: names = tuple(MAP_TERMS[quantity]) if names[-1] == "T_e": names = names[:-1] return _BASES[names] _MAP_BASIS = {quantity: _basis_of(quantity) for quantity in MAP_TERMS} def _terms(quantity: str, pressure_ratio: float, rps: float) -> tuple[float, ...]: if not (math.isfinite(pressure_ratio) and pressure_ratio > 0.0 and math.isfinite(rps)): raise InvalidCompressorEfficiency(f"no map value at PR={pressure_ratio!r}, rps={rps!r}") return _MAP_BASIS[quantity](pressure_ratio, rps) def _dot(coefficients: tuple[float, ...], terms: tuple[float, ...]) -> float: return math.fsum(c * x for c, x in zip(coefficients, terms, strict=True))
[docs] def map_eta_v(pressure_ratio: float, rps: float, T_evap_C: float) -> float: """Volumetric efficiency ``m_dot / (rho_1 V N)`` of the default map (T_e evaporating saturation temperature [C]).""" return _dot(MAP_COEFFICIENTS["eta_v"], (*_terms("eta_v", pressure_ratio, rps), T_evap_C))
[docs] def map_eta_ov(pressure_ratio: float, rps: float, T_evap_C: float) -> float: """Overall efficiency ``m_dot (h_2s - h_1) / E_cmp`` of the default map, E_cmp the compressor + inverter input.""" return _dot(MAP_COEFFICIENTS["eta_ov"], (*_terms("eta_ov", pressure_ratio, rps), T_evap_C))
[docs] def map_f_loss(pressure_ratio: float, rps: float) -> float: """Heat-loss share ``Q_cmp_loss / E_cmp`` of the default map.""" return _dot(MAP_COEFFICIENTS["f_loss"], _terms("f_loss", pressure_ratio, rps))
[docs] class CompressorEfficiencies(NamedTuple): """The three compressor quantities at one operating point (:data:`QUANTITIES`).""" eta_v: float eta_ov: float f_loss: float
[docs] def check_efficiencies(eta_v: float, eta_ov: float, f_loss: float) -> CompressorEfficiencies: """The three quantities if each lies in its range, else :class:`InvalidCompressorEfficiency`. * ``eta_v > 0`` and finite, with no upper bound: it is a measured ratio, ``m_dot / (rho_1 V N)`` with ``rho_1`` at the suction port, and the measured points of the default map reach 1.01 at a low pressure ratio and a warm evaporator (the map 1.018), so a value above one is an operating point, not an error. * ``0 < eta_ov <= 1``: no flow is compressed for nothing, and the hermetic compressors the maps describe take at least the isentropic work; a value above one is a map or scale outside what the model represents. * ``0 <= f_loss < 1``: zero is an adiabatic compressor; a negative share would be heat gained through the shell, which runs hotter than its surroundings, and a share of one or more leaves nothing for the gas. """ if not (math.isfinite(eta_v) and eta_v > 0.0): raise InvalidCompressorEfficiency(f"eta_v must be finite and positive, got {eta_v!r}") if not (math.isfinite(eta_ov) and 0.0 < eta_ov <= 1.0): raise InvalidCompressorEfficiency(f"eta_ov must lie in (0, 1], got {eta_ov!r}") if not (math.isfinite(f_loss) and 0.0 <= f_loss < 1.0): raise InvalidCompressorEfficiency(f"f_loss must lie in [0, 1), got {f_loss!r}") return CompressorEfficiencies(eta_v, eta_ov, f_loss)
[docs] def discharge_enthalpy(h_suction: float, h_isentropic: float, eta_ov: float, f_loss: float) -> float: """Discharge enthalpy ``h_2 = h_1 + (E_cmp - Q_cmp_loss) / m_dot`` [J/kg]. With ``E_cmp = m_dot (h_2s - h_1) / eta_ov`` and ``Q_cmp_loss = f_loss E_cmp`` this is ``h_1 + (1 - f_loss) (h_2s - h_1) / eta_ov``; it lies below ``h_2s`` when ``f_loss > 1 - eta_ov``. """ return h_suction + (1.0 - f_loss) * (h_isentropic - h_suction) / eta_ov
[docs] def compressor_power(m_dot: float, h_suction: float, h_isentropic: float, eta_ov: float) -> float: """Electrical input ``E_cmp = m_dot (h_2s - h_1) / eta_ov`` [W].""" return m_dot * (h_isentropic - h_suction) / eta_ov
[docs] def restate_compressor_loss(result: dict[str, Any], power_key: str = "E_cmp [W]") -> None: """Set ``Q_cmp_loss [W]`` of a result row to ``f_loss [-]`` times its compressor input, in place. For a row whose compressor input has been averaged after the cycle was solved (on/off cycling, frost and defrost): the shell loss is reported as the heat-loss share of the input the row reports. A row without the two keys, or with a non-finite share (an off row), is left as it is. """ if "Q_cmp_loss [W]" not in result: return share = result.get("f_loss [-]") power = result.get(power_key) if isinstance(share, (int, float)) and isinstance(power, (int, float)) and math.isfinite(share): result["Q_cmp_loss [W]"] = float(share) * float(power)
_SCALE_FIELDS = ("k_v", "k_ov", "k_f", "delta_N", "w_N", "delta_r", "w_r")
[docs] @dataclass(frozen=True) class CompressorMapScale: """Scale factors on the default compressor maps -- the only way to change a model's compressor. ``k_v``, ``k_ov`` and ``k_f`` scale the level of ``eta_v``, ``eta_ov`` and ``f_loss``; ``delta_N`` [rev/s] and ``delta_r`` [-] move the peak of the ``eta_ov`` map (either may be negative) and ``w_N`` and ``w_r`` stretch it about the moved peak (see the module docstring for the formulas). The defaults give the maps as they are. ``k_v``, ``k_ov``, ``w_N`` and ``w_r`` must be positive and ``k_f`` nonnegative (``ValueError`` otherwise); a factor that puts a quantity outside its range at an operating point makes that point infeasible (:func:`check_efficiencies`). """ k_v: float = 1.0 k_ov: float = 1.0 k_f: float = 1.0 delta_N: float = 0.0 w_N: float = 1.0 delta_r: float = 0.0 w_r: float = 1.0 def __post_init__(self) -> None: for name in _SCALE_FIELDS: value = getattr(self, name) if isinstance(value, bool) or not isinstance(value, (int, float)): raise TypeError(f"{name} must be a real number, got {value!r}") value = float(value) if not math.isfinite(value): raise ValueError(f"{name} must be finite, got {value!r}") object.__setattr__(self, name, value) for name in ("k_v", "k_ov", "w_N", "w_r"): if not getattr(self, name) > 0.0: raise ValueError(f"{name} must be positive, got {getattr(self, name)!r}") if not self.k_f >= 0.0: raise ValueError(f"k_f must be nonnegative, got {self.k_f!r}") @property def is_identity(self) -> bool: """Whether the scale leaves the default maps as they are.""" return self == CompressorMapScale()
[docs] def as_dict(self) -> dict[str, float]: """The seven factors by name.""" return {f.name: getattr(self, f.name) for f in fields(self)}
[docs] def eta_ov_coordinates(self, pressure_ratio: float, rps: float) -> tuple[float, float]: """``(PR~, N~)``: where the default ``eta_ov`` map is read for the point ``(PR, N)``. Raises :class:`InvalidCompressorEfficiency` when ``PR - delta_r <= 0``. """ if self.delta_N == 0.0 and self.w_N == 1.0: rps_map = rps else: rps_map = ETA_OV_PEAK_RPS + (rps - ETA_OV_PEAK_RPS - self.delta_N) / self.w_N if self.delta_r == 0.0 and self.w_r == 1.0: pr_map = pressure_ratio else: shifted = pressure_ratio - self.delta_r if not (math.isfinite(shifted) and shifted > 0.0): raise InvalidCompressorEfficiency( f"pressure ratio {pressure_ratio!r} minus delta_r {self.delta_r!r} is not positive" ) pr_map = ETA_OV_PEAK_PR * (shifted / ETA_OV_PEAK_PR) ** (1.0 / self.w_r) return pr_map, rps_map
[docs] def eta_v(self, pressure_ratio: float, rps: float, T_evap_C: float) -> float: """Scaled volumetric efficiency (no range check).""" value = map_eta_v(pressure_ratio, rps, T_evap_C) return value if self.k_v == 1.0 else self.k_v * value
[docs] def eta_ov(self, pressure_ratio: float, rps: float, T_evap_C: float) -> float: """Scaled overall efficiency (no range check).""" pr_map, rps_map = self.eta_ov_coordinates(pressure_ratio, rps) value = map_eta_ov(pr_map, rps_map, T_evap_C) if self.k_ov == 1.0 or not value > 0.0: return value # 1/eta' - 1 = k (1/eta - 1), written without the reciprocals return value / (value + self.k_ov * (1.0 - value))
[docs] def f_loss(self, pressure_ratio: float, rps: float) -> float: """Scaled heat-loss share (no range check).""" value = map_f_loss(pressure_ratio, rps) return value if self.k_f == 1.0 else self.k_f * value
[docs] def evaluate(self, pressure_ratio: float, rps: float, T_evap_K: float) -> CompressorEfficiencies: """The three quantities at ``(PR, N, T_e)``, range-checked (:func:`check_efficiencies`).""" T_evap_C = T_evap_K - 273.15 return check_efficiencies( self.eta_v(pressure_ratio, rps, T_evap_C), self.eta_ov(pressure_ratio, rps, T_evap_C), self.f_loss(pressure_ratio, rps), )
[docs] def extrapolated(self, pressure_ratio: float, rps: float, T_evap_C: float | None = None, rtol: float = 0.0) -> bool: """Whether any of the three maps is read outside its fitting data at ``(PR, N[, T_e])``. ``eta_v`` and ``f_loss`` are read at the point itself, ``eta_ov`` at its transformed coordinates (:meth:`eta_ov_coordinates`). Without ``T_evap_C`` only the speed range is checked. ``rtol`` accepts a point that far outside, relatively. """ if not DOMAIN.contains(pressure_ratio, rps, T_evap_C, rtol=rtol): return True try: pr_map, rps_map = self.eta_ov_coordinates(pressure_ratio, rps) except InvalidCompressorEfficiency: return True if (pr_map, rps_map) == (pressure_ratio, rps): return False return not DOMAIN.contains(pr_map, rps_map, T_evap_C, rtol=rtol)
#: The default maps as they are. IDENTITY_SCALE = CompressorMapScale()
[docs] def resolve_scale(scale: CompressorMapScale | None) -> CompressorMapScale: """``scale``, or the identity for ``None``; ``TypeError`` for anything else, a subclass included.""" if scale is None: return IDENTITY_SCALE # exactly the class: a subclass could replace the maps, which no model takes (#274) if type(scale) is not CompressorMapScale: raise TypeError(f"compressor_scale must be a CompressorMapScale or None, got {type(scale).__name__}") return scale
[docs] def efficiency_extrapolated( scale: CompressorMapScale | None, pressure_ratio: float, rps: float, T_evap_C: float | None = None ) -> bool: """Whether the (scaled) maps are evaluated outside their fitting data at (PR, N[, T_e]). For a result row use ``PR = P_ref_cmp_out / P_ref_cmp_in``, ``N = cmp_rpm / 60`` and ``T_e = T_ref_evap_sat``. """ return resolve_scale(scale).extrapolated(pressure_ratio, rps, T_evap_C)
_F = TypeVar("_F", bound=Callable)
[docs] def reject_invalid_efficiency(function: _F) -> _F: """Return an infeasible state (``None``) where a compressor quantity is out of range.""" @wraps(function) def wrapped(*args, **kwargs): try: return function(*args, **kwargs) except InvalidCompressorEfficiency: return None return cast(_F, wrapped)