"""Air source heat pump — physics-based cycle model with indoor unit.
Resolves a vapour-compression refrigerant cycle coupled to
an outdoor-air heat exchanger and an indoor-air heat exchanger.
Supports both **cooling** (``Q_r_iu > 0``) and **heating** (``Q_r_iu < 0``)
modes. The indoor load ``Q_r_iu`` is imposed externally each timestep.
At each time step the model finds the minimum-power operating point
(compressor + indoor fan + outdoor fan) via bounded 2-D optimisation
over the evaporator and condenser approach temperature differences.
Architecture mirrors ``AirSourceHeatPumpBoiler`` — uses the same
shared utility functions (``calc_ref_state``, ``calc_HX_perf_for_target_heat``,
``calc_fan_power_from_dV_fan``) and the same ``postprocess_exergy()``
pattern, but replaces the tank energy balance with direct air-side
heat exchange at the indoor unit.
"""
import contextlib
import math
import numbers
from collections.abc import Callable, Iterable, Iterator, Mapping
from typing import Any, Literal
import numpy as np
import pandas as pd
from scipy.optimize import OptimizeResult, brentq, minimize, minimize_scalar
from tqdm import tqdm
from . import _opt_utils
from . import calc_util as cu
from ._boiler_results import fill_missing, report_condenser_dew_point
from ._opt_utils import specific_energy_objective
from ._validation import validate_ctor, validate_dynamic, validate_steady
from .air_properties import air_heat_capacity_rate
from .compressor_efficiency import (
CompressorMapScale,
compressor_power,
discharge_enthalpy,
reject_invalid_efficiency,
)
from .compressor_envelope import (
BINDING_CONDENSING,
BINDING_CYCLE,
BINDING_DISCHARGE,
BINDING_PRESSURE_RATIO,
CONDENSING_TEMP_ABOVE_MAX,
CYCLE_KEY,
DISCHARGE_TEMP_ABOVE_MAX,
PR_ABOVE_MAX,
PR_CYCLE_MAX_SINGLE_STAGE,
RATED_SPEED_SEARCH_MAX,
check_pr_envelope,
discharge_controlled,
resolve_condensing_temp_max,
resolve_discharge_temp_max,
resolve_x_suction_min,
steady_envelope,
)
from .compressor_plots import CompressorMapPlotMixin
from .compressor_speed import (
CAPACITY_CLAMPED_MAX,
CAPACITY_CLAMPED_MIN,
solve_compressor_speed,
)
from .cycling import (
CD_AIR_DEFAULT,
CONTINUOUS,
MIN_CAPACITY_KEY,
OFF,
CyclingDegradation,
apply_cycling,
continuous_keys,
resolve_cycling,
)
from .default_inputs import kept_hx_UA
from .defrost import (
LOAD_RATIO_ATOL,
NO_FROST,
DefrostModel,
FrostState,
apply_defrost,
frost_free_keys,
humidity_ratio,
resolve_defrost,
)
from .enex_functions import (
calc_energy_flow,
calc_fan_power_from_dV_fan,
calc_HX_perf_for_target_heat,
)
from .heat_exchanger import AirCoilSide, resolve_fan_flow_limits, resolve_fan_rated_power, wet_coil_latent_difference
from .hx_fan import SINGLE_ZONE_VAV_COEFFICIENTS, is_generic_fan_curve
from .operating_limits import dynamic_notice, note_refusal, steady_notice
from .reference_state import RATING_STANDARDS, HXSide, RatingCondition, ReferenceStateMixin
from .refrigerant import (
_props,
calc_ref_state,
calc_ref_state_without_discharge,
props_si,
reportable_state,
with_discharge_state,
)
from .standard_conditions import StandardCondition
from .standard_conditions import operating_range as _operating_range
# Objective bands for the operating-point search in ``_optimize_operation``.
#
# The search ranks candidate operating points lexicographically, best first:
#
# 1. points that meet the requested duty -> ranked by total power [W],
# which is O(1e2..1e5) and therefore always below the sentinels below;
# 2. points that are capacity limited -> ranked by how much of the duty
# they do deliver, so that a capacity-limited result is recognised as
# one and never traded for a cheaper part-load point. The ceiling itself
# is not read off this ranking: it is solved (`max_capacity`), because
# the largest delivered heat is not where a unit runs flat out;
# 3. points the cycle cannot reach at all -> rejected.
#
# The bands must stay ordered and far enough apart that no power figure or
# shortfall can cross from one band into the next.
#: Objective floor for a capacity-limited operating point (valid operation).
OBJ_CAPACITY_LIMITED = 1.0e9
#: Objective value for an operating point the cycle cannot reach (invalid).
OBJ_INFEASIBLE = 1.0e12
#: A fan whose largest flow is at most this multiple of its smallest is
#: searched by :class:`_NarrowFanSearch`. At a fixed approach temperature a
#: coil's capacity grows roughly as flow^0.7, so a flow ratio of 2 leaves a band
#: of approach temperatures about +/-25 % wide -- at a 3 K approach that is
#: narrower than the spacing of the finest lattice the grid search falls back
#: on (1.3 K), and a constant-speed fan leaves a single point.
NARROW_FAN_FLOW_RATIO = 2.0
class _NarrowFanSearch:
"""Operating-point search for a fan with little or no flow range.
A coil whose fan can modulate carries a given duty over a band of approach
temperatures: a small approach at the largest airflow, a large one at the
smallest. With a constant-speed fan the band is one point, and the unit
meets a duty only where the refrigerant side and that one airflow agree.
A grid or a simplex over the two approach temperatures cannot land on a set
of zero width, so the band is solved instead, from the signed capacity
margins of the coil at its two flow limits
(:func:`~tmhp._opt_utils.margin_feasible_interval`) -- the way the
ground-source and the water-heating models treat their fans.
The two approaches are nested. The coil with the narrower fan is the
*inner* one: for every outer approach its own approach is solved as the
middle of its band (a single point for a constant-speed fan). The other
coil's approach is the *outer* one: its band is solved from that coil's
margins at the inner solution, and candidates inside it are ranked on the
same three-band objective as the grid search
(:func:`~tmhp._opt_utils.operating_point_objective`).
With ``accept`` the search stops at the first candidate state it accepts
and keeps it in ``accepted`` (for a caller that asks only whether some
approach pair meets a duty exactly).
"""
class _Accepted(Exception):
"""Raised from :meth:`entry` to leave the root finders at an accepted state."""
#: Root tolerance on a band edge [K]. A constant-speed coil is converged
#: only within 1e-5 of its duty, i.e. a few 1e-5 K of approach.
_EDGE_XTOL_K = 1e-7
#: Root tolerance on the outer band of a fan that can still modulate [K]:
#: the interior is minimised afterwards, the edge only bounds it.
_OUTER_BAND_XTOL_K = 1e-3
#: Inward step from a solved band edge before the interior is minimised [K].
_EDGE_STEP_K = 1e-4
def __init__(
self,
model: "AirSourceHeatPump",
Q_r_iu: float,
T0: float,
T_a_room: float,
accept: Callable[[dict | None], bool] | None = None,
) -> None:
self.model = model
self.Q_r_iu, self.T0, self.T_a_room = Q_r_iu, T0, T_a_room
self.accept = accept
#: ``((dT_ref_evap, dT_ref_cond), state)`` of the accepted candidate.
self.accepted: tuple[tuple[float, float], dict] | None = None
self.heating = Q_r_iu < 0
ratio_iu, ratio_ou = model._fan_flow_ratios()
#: The narrower fan is solved, the other searched.
self.inner_is_iu = ratio_iu <= ratio_ou
self.inner_fixed = min(ratio_iu, ratio_ou) == 1.0
self.outer_fixed = max(ratio_iu, ratio_ou) == 1.0
#: (indoor approach, outdoor approach) -> (objective, state, coil margins)
self.rows: dict[tuple[float, float], tuple[float, dict | None, tuple[float, float, float, float] | None]] = {}
self._inner_points: dict[float, float | None] = {}
self._inner_hint: float | None = None
# -- candidates ---------------------------------------------------------
def approaches(self, x_iu: float, x_ou: float) -> tuple[float, float]:
"""``(dT_ref_evap, dT_ref_cond)`` for an indoor/outdoor approach pair."""
return (x_ou, x_iu) if self.heating else (x_iu, x_ou)
def entry(self, x_iu: float, x_ou: float) -> tuple[float, dict | None, tuple[float, float, float, float] | None]:
key = (float(x_iu), float(x_ou))
if key not in self.rows:
model = self.model
de, dc = self.approaches(*key)
perf = model._calc_state(
dT_ref_evap=de, dT_ref_cond=dc, Q_r_iu=self.Q_r_iu, T0=self.T0, T_a_room=self.T_a_room
)
value = OBJ_INFEASIBLE
if perf is not None and perf.get("converged", False):
value = _opt_utils.operating_point_objective(
float(perf.get("E_tot [W]", math.nan)),
float(perf.get("Q_ref_iu [W]", math.nan)),
self.Q_r_iu,
perf.get("capacity_clamped"),
) * model._cycling_cost_factor(perf, self.Q_r_iu)
self.rows[key] = (value, perf, model._coil_margins(perf))
if self.accept is not None and perf is not None and self.accept(perf):
self.accepted = (self.approaches(*key), perf)
raise self._Accepted
return self.rows[key]
def _pair(self, outer: float, inner: float) -> tuple[float, float]:
return (outer, inner) if not self.inner_is_iu else (inner, outer)
def _side_margins(self, outer: float, inner: float, indoor: bool) -> tuple[float, float] | None:
"""(margin at the largest flow, margin at the smallest flow) of one coil [W]."""
margins = self.entry(*self._pair(outer, inner))[2]
if margins is None:
return None
iu_min, iu_max, ou_min, ou_max = margins
return (iu_max, iu_min) if indoor else (ou_max, ou_min)
# -- inner coil: solved -------------------------------------------------
def inner(self, outer: float) -> float | None:
"""Inner approach at which the inner fan carries its duty, or ``None``."""
outer = float(outer)
if outer not in self._inner_points:
lo, hi = self.model.dT_approach_bounds
band = _opt_utils.margin_band_on_valid_range(
lambda x: self._side_margins(outer, x, self.inner_is_iu),
lo,
hi,
xtol=self._EDGE_XTOL_K,
hint=self._inner_hint,
)
point = None
if band is not None:
# The middle of the band: the one point of a constant-speed
# fan, mid-range airflow of a fan that can still modulate.
point = 0.5 * (band[0] + band[1])
self._inner_hint = point
self._inner_points[outer] = point
return self._inner_points[outer]
def _outer_margins(self, outer: float) -> tuple[float, float] | None:
inner = self.inner(outer)
if inner is None:
return None
return self._side_margins(outer, inner, not self.inner_is_iu)
def value(self, outer: float) -> float:
inner = self.inner(outer)
if inner is None:
return OBJ_INFEASIBLE
return self.entry(*self._pair(float(outer), inner))[0]
# -- outer coil: band, then minimum -------------------------------------
def run(self) -> None:
with contextlib.suppress(self._Accepted):
self._run()
def _run(self) -> None:
lo, hi = self.model.dT_approach_bounds
band = _opt_utils.margin_band_on_valid_range(
self._outer_margins,
lo,
hi,
xtol=self._EDGE_XTOL_K if self.outer_fixed else self._OUTER_BAND_XTOL_K,
)
if band is None:
return
a, b = band
step = self._EDGE_STEP_K
if self.outer_fixed or b - a <= 2.0 * step:
for x in (0.5 * (a + b), a, b):
if self.value(x) < OBJ_INFEASIBLE:
return
return
a, b = a + step, b - step
points = sorted({a, b, *(x for x in self._inner_points if a < x < b)})
values = [self.value(x) for x in points]
k = min(range(len(points)), key=values.__getitem__)
left, right = points[max(k - 1, 0)], points[min(k + 1, len(points) - 1)]
if values[k] < OBJ_INFEASIBLE and right > left:
minimize_scalar(
self.value,
bounds=(left, right),
method="bounded",
options={"xatol": min(1e-2, (right - left) / 20.0), "maxiter": 25},
)
def best(self) -> tuple[float, tuple[float, float] | None, dict | None]:
"""Least objective found: ``(value, (dT_ref_evap, dT_ref_cond), state)``."""
if not self.rows:
return OBJ_INFEASIBLE, None, None
key = min(self.rows, key=lambda k: self.rows[k][0])
value, perf, _ = self.rows[key]
return value, self.approaches(*key), perf
#: Exergy columns left NaN on a row whose indoor coil removes water: the
#: indoor coil's destruction and the two efficiencies that presuppose its
#: complete balance (``AirSourceHeatPump.postprocess_exergy``).
_NO_MOIST_AIR_BALANCE: tuple[str, ...] = ("Xc_iu_hx [W]", "X_eff_iu_hx [-]", "X_eff_sys [-]")
class _NotARow(Exception):
"""A steady result that :func:`_exergy_row` leaves to the frame form of the post-processing."""
def _boxed(value: Any) -> Any:
"""A cell of a one-row frame as ``DataFrame.iloc[0].to_dict()`` hands it back.
Only the types a steady result holds are decided here; any other goes
through the frame.
"""
kind = type(value)
if value is None or kind in (float, str, bool, int):
return value
if kind is np.float64:
return float(value)
if kind is np.bool_:
return bool(value)
if kind is np.int64:
return int(value)
raise _NotARow(kind)
def _exergy_row(result: dict, ref: str) -> dict:
"""The exergy variables of one steady result: ``AirSourceHeatPump.postprocess_exergy`` on scalars.
Every line is the corresponding line of ``postprocess_exergy`` and of the
helpers it calls (``calc_refrigerant_exergy``, ``convert_electricity_to_exergy``,
``calc_exergy_flow``), with the operations in the same order, so a one-row
frame and this give the same bits. Arithmetic is on ``np.float64``: a zero
divisor gives ``inf``/``nan`` as in a frame, not ``ZeroDivisionError``.
Raises :class:`_NotARow` where the frame would not behave as written
(a number held as anything but a float, a string where a frame holds a
number); a missing key raises ``KeyError`` where the frame does.
"""
row = {key: _boxed(value) for key, value in result.items()}
if "T0 [°C]" not in row or "h_ref_cmp_in [J/kg]" not in row:
raise _NotARow("no refrigerant state: the frame returns the row unchanged")
def num(key: str) -> np.float64:
value = row[key]
if type(value) is not float and type(value) is not np.float64:
raise _NotARow(key)
return np.float64(value)
def filled(key: str) -> np.float64:
"""``fillna(0)`` of a number column."""
value = num(key)
return np.float64(0.0) if value != value else value
def divided(numerator: np.float64, denominator: np.float64) -> np.float64:
"""``numerator / denominator.replace(0, nan)``."""
return numerator / (np.float64(np.nan) if denominator == 0 else denominator)
def exergy_flow(G: np.float64, T: np.float64, T0: np.float64) -> np.float64:
"""``calc_exergy_flow`` on a one-row series: zero where a temperature is not positive."""
invalid = T <= 0 or T0 <= 0
T_safe = np.float64(1.0) if T <= 0 else T
T0_safe = np.float64(1.0) if T0 <= 0 else T0
# np.log of a one-element array: the loop a frame's column goes through.
log = np.log(np.array([T_safe / T0_safe]))[0]
return np.float64(0.0) if invalid else G * ((T_safe - T0_safe) - T0_safe * log)
with np.errstate(all="ignore"):
T0_K = cu.C2K(num("T0 [°C]"))
# ── 1. Refrigerant exergy ────────────────────────
h0 = s0 = np.float64(np.nan)
if T0_K == T0_K:
try:
h0, s0 = (np.float64(v) for v in _props("HS", "T", float(T0_K), "P", 101325, ref))
except Exception:
h0 = s0 = np.float64(np.nan)
m_dot = num("m_dot_ref [kg/s]") if "m_dot_ref [kg/s]" in row else np.float64(np.nan)
for name in ("cmp_in", "cmp_out", "exp_in", "exp_out"):
h_key, s_key = f"h_ref_{name} [J/kg]", f"s_ref_{name} [J/(kg·K)]"
if h_key not in row or s_key not in row:
continue
x_val = (num(h_key) - h0) - T0_K * (num(s_key) - s0)
row[f"x_ref_{name} [J/kg]"] = x_val
row[f"X_ref_{name} [W]"] = m_dot * x_val
# ── 2. Electricity = exergy ─────────────────────
for key in list(row):
if key.startswith("E_") and key.endswith(" [W]"):
row["X_" + key[2:]] = row[key]
if "E_iu_fan [W]" in row:
row["X_iu_fan [W]"] = row["E_iu_fan [W]"]
# ── 3. Air exergy (outdoor unit, indoor unit) ───
for side in ("ou", "iu"):
if f"dV_{side}_a [m3/s]" in row and f"T_{side}_a_in [°C]" in row:
T_in_C = num(f"T_{side}_a_in [°C]")
G = air_heat_capacity_rate(np.array([filled(f"dV_{side}_a [m3/s]")]), np.array([T_in_C]))[0]
T_in, T_mid = cu.C2K(T_in_C), cu.C2K(num(f"T_{side}_a_mid [°C]"))
T_out = cu.C2K(num(f"T_{side}_a_out [°C]")) if f"T_{side}_a_out [°C]" in row else T_in
row[f"X_a_{side}_in [W]"] = exergy_flow(G, T_in, T0_K)
row[f"X_a_{side}_out [W]"] = exergy_flow(G, T_out, T0_K)
row[f"X_a_{side}_mid [W]"] = exergy_flow(G, T_mid, T0_K)
# ── 4. HX Carnot exergy (mode-aware IU/OU) ─────
mode = row.get("mode")
if mode is not None and type(mode) is not str:
raise _NotARow("mode")
# The bubble point, as in ``postprocess_exergy`` (``T_ref_cond_sat_v`` is a zeotrope's dew point).
if "T_ref_cond_sat_l [°C]" in row and "T_ref_evap_sat [°C]" in row and "mode" in row:
heating = mode == "heating"
cond, evap = num("T_ref_cond_sat_l [°C]"), num("T_ref_evap_sat [°C]")
T_iu_sat_K = cu.C2K(cond if heating else evap)
T_ou_sat_K = cu.C2K(evap if heating else cond)
row["X_ref_iu [W]"] = num("Q_ref_iu [W]") * (1 - T0_K / T_iu_sat_K)
row["X_ref_ou [W]"] = num("Q_ref_ou [W]") * (1 - T0_K / T_ou_sat_K)
# ── 5. Total exergy input ───────────────────────
X_tot = num("E_cmp [W]") + filled("E_ou_fan [W]") + filled("E_iu_fan [W]")
row["X_tot [W]"] = X_tot
# ── 6. Component exergy destruction (IU/OU naming) ──
def air(key: str) -> np.float64:
return filled(key) if key in row else np.float64(0.0)
X_a_ou_in, X_a_ou_mid, X_a_ou_out = air("X_a_ou_in [W]"), air("X_a_ou_mid [W]"), air("X_a_ou_out [W]")
X_a_iu_in, X_a_iu_mid, X_a_iu_out = air("X_a_iu_in [W]"), air("X_a_iu_mid [W]"), air("X_a_iu_out [W]")
if "X_cmp [W]" not in row:
return {key: _boxed(value) for key, value in row.items()}
heating, cooling = row["mode"] == "heating", row["mode"] == "cooling"
X_ref_cmp_in, X_ref_cmp_out = num("X_ref_cmp_in [W]"), num("X_ref_cmp_out [W]")
X_ref_exp_in, X_ref_exp_out = num("X_ref_exp_in [W]"), num("X_ref_exp_out [W]")
# ── 6a. Compressor ──
row["X_in_cmp [W]"] = X_in_cmp = num("X_cmp [W]") + X_ref_cmp_in
row["X_out_cmp [W]"] = X_ref_cmp_out
row["Xc_cmp [W]"] = Xc_cmp = X_in_cmp - X_ref_cmp_out
# ── 6b. Expansion valve ──
row["X_in_exp [W]"] = X_ref_exp_in
row["X_out_exp [W]"] = X_ref_exp_out
row["Xc_exp [W]"] = Xc_exp = X_ref_exp_in - X_ref_exp_out
# ── 6c / 6d. Indoor and outdoor unit HX (a mode that is neither leaves zeros) ──
X_in_iu = X_out_iu = X_in_ou = X_out_ou = np.float64(0.0)
if heating:
X_in_iu, X_out_iu = X_ref_cmp_out + X_a_iu_in, X_ref_exp_in + X_a_iu_mid
X_in_ou, X_out_ou = X_ref_exp_out + X_a_ou_in, X_ref_cmp_in + X_a_ou_mid
elif cooling:
X_in_iu, X_out_iu = X_ref_exp_out + X_a_iu_in, X_ref_cmp_in + X_a_iu_mid
X_in_ou, X_out_ou = X_ref_cmp_out + X_a_ou_in, X_ref_exp_in + X_a_ou_mid
row["X_in_iu_hx [W]"], row["X_out_iu_hx [W]"] = X_in_iu, X_out_iu
row["Xc_iu_hx [W]"] = Xc_iu_hx = X_in_iu - X_out_iu
row["X_in_ou_hx [W]"], row["X_out_ou_hx [W]"] = X_in_ou, X_out_ou
row["Xc_ou_hx [W]"] = Xc_ou_hx = X_in_ou - X_out_ou
# ── 6e / 6f. Outdoor and indoor fan ──
X_in_ou_fan = filled("X_ou_fan [W]") + X_a_ou_mid
row["X_in_ou_fan [W]"], row["X_out_ou_fan [W]"] = X_in_ou_fan, X_a_ou_out
row["Xc_ou_fan [W]"] = Xc_ou_fan = X_in_ou_fan - X_a_ou_out
X_in_iu_fan = filled("X_iu_fan [W]") + X_a_iu_mid
row["X_in_iu_fan [W]"], row["X_out_iu_fan [W]"] = X_in_iu_fan, X_a_iu_out
row["Xc_iu_fan [W]"] = Xc_iu_fan = X_in_iu_fan - X_a_iu_out
# ── 7. Exergetic efficiency metrics ─────────────
row["X_eff_sys [-]"] = divided(X_a_iu_out - X_a_iu_in, X_tot)
row["X_eff_cmp [-]"] = 1 - divided(Xc_cmp, X_in_cmp)
row["X_eff_exp [-]"] = 1 - divided(Xc_exp, X_ref_exp_in)
row["X_eff_iu_hx [-]"] = 1 - divided(Xc_iu_hx, X_in_iu)
row["X_eff_ou_hx [-]"] = 1 - divided(Xc_ou_hx, X_in_ou)
row["X_eff_ou_fan [-]"] = 1 - divided(Xc_ou_fan, X_in_ou_fan)
row["X_eff_iu_fan [-]"] = 1 - divided(Xc_iu_fan, X_in_iu_fan)
# ── 8. A coil that removes water: no indoor-coil balance (see ``postprocess_exergy``) ──
if "Q_iu_latent [W]" in row and num("Q_iu_latent [W]") > 0:
for key in _NO_MOIST_AIR_BALANCE:
row[key] = np.float64(np.nan)
return {key: _boxed(value) for key, value in row.items()}
#: Indoor-unit classes with a catalogue airflow law (:func:`tmhp.default_inputs.estimate_max_airflow`).
#: Cassette and ducted units are not covered: give their ``dV_iu_fan_a_rated``.
INDOOR_UNIT_TYPES: tuple[str, ...] = ("wall_mounted", "floor_standing")
#: Default indoor-coil conductance per watt of nameplate [W/K per W]: the earlier rule, kept (provisional).
INDOOR_UA_PER_CAPACITY = 0.16
#: Why the indoor coil keeps that rule instead of an approach-temperature estimate (recorded in
#: ``default_input_estimates["UA_iu_rated"]``; archive ``validation/default_inputs/hx_approach``).
INDOOR_UA_KEPT_REASON = (
"kept at the previous rule. The archive's wall-mounted indoor-coil rows come from one manufacturer "
"(Mitsubishi Electric, 6 product lines): their leaving approach is 6.8 K on the declared duty but 3.6 K on "
"the printed discharge-air temperature, and a second manufacturer's pipe temperatures suggest about 3.3 K, so "
"the evidence does not settle the value and no estimate is issued (shipping gate: 2 manufacturers)."
)
def _check_room_humidity(value: float) -> float:
"""``RH_room`` as a float, or ``ValueError``: a real number in 0-1, not a boolean (as ``RH_out``)."""
if isinstance(value, bool) or not isinstance(value, numbers.Real) or not 0.0 <= value <= 1.0:
raise ValueError(f"Room relative humidity must be a fraction in [0, 1], got {value!r}")
return float(value)
def _room_humidity_of_step(value: Any, step: int) -> float:
"""The room humidity of a cooling step of a schedule (as ``RH_room``), or ``ValueError`` naming the step."""
try:
return _check_room_humidity(value)
except ValueError as error:
raise ValueError(f"{error} at step {step}") from None
#: ``request_basis``: the request is the refrigerant-side heat of the indoor
#: coil (``Q_ref_iu [W]``; in cooling its total heat, before the fan's heat).
REQUEST_BASIS_TOTAL = "total"
#: ``request_basis``: the request is the net sensible heat the room air gives
#: up or receives (``Q_room_sensible [W]``), a zone's sensible load.
REQUEST_BASIS_SENSIBLE = "sensible"
#: Result key naming the basis of ``Q_request [W]`` and ``Q_unmet [W]``.
REQUEST_BASIS_KEY = "request_basis"
#: Result key of a row asked on the room's net sensible heat, and of no other:
#: the total-basis solves the search of the request took.
REQUEST_SOLVES_KEY = "request_solves [-]"
def _check_request_basis(value: Any) -> str:
"""``request_basis`` as given, or ``ValueError``: one of the two names."""
if isinstance(value, str) and value in (REQUEST_BASIS_TOTAL, REQUEST_BASIS_SENSIBLE):
return value
raise ValueError(f"request_basis must be {REQUEST_BASIS_TOTAL!r} or {REQUEST_BASIS_SENSIBLE!r}, got {value!r}")
[docs]
class AirSourceHeatPump(ReferenceStateMixin, CompressorMapPlotMixin):
"""Air source heat pump with indoor-unit air heat exchange.
The refrigerant cycle is resolved via CoolProp with
user-specified superheat / subcool margins. A bounded
2-D optimiser minimises total electrical input
(``E_cmp + E_iu_fan + E_ou_fan``) over the evaporator
and condenser approach temperatures.
When the requested duty has no operating point -- the compressor runs
out of speed, or the compressor envelope or a coil binds first -- the unit
runs at its ceiling: flat out (``rps_max``, both fans at their largest
airflow), or at the largest duty the envelope admits (:meth:`max_capacity`).
Such an hour is reported with ``capacity_clamped == "max"``, a
``Q_ref_iu [W]`` below the request and ``capacity_binding`` naming the
limit; the difference is unmet load (``Q_unmet [W]``), not a solver failure.
When the request is below what the unit delivers at its minimum compressor
speed, the compressor cycles on and off. Such an hour is reported with
``capacity_clamped == "min"`` as the mean over the cycling period: the
delivered heat equals the request, the electrical input carries the EN
14825 degradation (``Cd_cycling``), and ``runtime_fraction [-]`` is the
share of the time the compressor runs (:mod:`tmhp.cycling`). The same
holds where the envelope ends continuous operation above the minimum
speed: at a large lift the overall efficiency falls towards low
speed, the discharge runs above its limit there
(``discharge_temp_above_max``), and a request below the smallest duty that
stays inside is met by cycling at that duty (``Q_min [W]``), not answered
with the unit switched off.
The indoor coil is dry unless the room humidity is given. With
``RH_room`` (``analyze_steady``, ``max_capacity``; ``RH_room_schedule`` in
``analyze_dynamic``) a cooling coil whose surface -- taken at the
evaporating temperature -- is below the room air's dew point also
condenses water: ``Q_ref_iu [W]`` is then sensible plus latent heat
(``Q_iu_sensible [W]``, ``Q_iu_latent [W]``, ``SHR_iu [-]``,
``m_dot_iu_condensate [kg/s]``), by the apparatus-dew-point / bypass-factor
model of :func:`tmhp.heat_exchanger.calc_HX_perf_for_target_heat`. Above
the dew point, in heating and without ``RH_room`` the coil is the dry one.
The rated state and the default inputs are those of the dry coil.
A request is the heat of the indoor coil unless ``request_basis`` says
otherwise. With ``request_basis="sensible"`` (``analyze_steady``,
``analyze_dynamic``) it is the net sensible heat the room air gives up or
receives -- a zone's sensible load -- and the model finds the coil duty
whose ``Q_room_sensible [W]`` equals it: more than the request in cooling
(the indoor fan's heat, and the latent heat of a wet coil), less in
heating. ``Q_request [W]`` and ``Q_unmet [W]`` are then on that basis, and
every row names its basis (``request_basis``). Such a row also says how
many total-basis solves its search took (``request_solves [-]``).
"""
#: Heat and flow rates averaged with the capacity ratio while cycling.
_CYCLING_RATE_KEYS: tuple[str, ...] = (
"Q_ref_iu [W]",
"Q_ref_ou [W]",
"Q_a_iu_in [W]",
"Q_a_iu_out [W]",
"m_dot_ref [kg/s]",
"dV_iu_a [m3/s]",
"dV_ou_a [m3/s]",
"Q_iu_sensible [W]",
"Q_iu_latent [W]",
"m_dot_iu_condensate [kg/s]",
"Q_room_sensible [W]",
)
#: Electrical powers averaged with the runtime fraction while cycling. The
#: indoor fan is not among them: it moves the delivered heat and is
#: averaged with it (``E_iu_fan [W]`` times the capacity ratio).
_CYCLING_POWER_KEYS: tuple[str, ...] = ("E_cmp [W]", "E_ou_fan [W]")
#: Heat and flow rates averaged with the delivered-heat factor under frost.
_FROST_RATE_KEYS: tuple[str, ...] = (
"Q_ref_iu [W]",
"Q_ref_ou [W]",
"Q_a_iu_in [W]",
"Q_a_iu_out [W]",
"m_dot_ref [kg/s]",
"dV_iu_a [m3/s]",
"dV_ou_a [m3/s]",
"Q_iu_sensible [W]",
"Q_iu_latent [W]",
"m_dot_iu_condensate [kg/s]",
"Q_room_sensible [W]",
)
#: Delivered heat and electrical input of the frost-free cycle a row was solved at [W].
_FROST_FREE_HEAT_KEY = "Q_ref_iu_frost_free [W]"
_FROST_FREE_POWER_KEY = "E_tot_frost_free [W]"
#: EnergyPlus / DOE-2.1E frost adjustment in heating (None: frost-free
#: steady state). Set by the constructor.
defrost: DefrostModel | None = None
#: Room relative humidity of the cooling point being solved [-], and the
#: humidity ratio it gives at the room temperature [kg water / kg dry air].
#: ``None`` outside such a solve, in heating and where no ``RH_room`` was
#: given: the indoor coil is then dry (:meth:`_solving_with_room_humidity`).
_RH_room: float | None = None
_w_room: float | None = None
_RATING_FAMILY = "ASHP"
_RATING_DEFAULT_MODE = "cooling"
[docs]
def __init__(
self,
# 1. Refrigerant / cycle / compressor -----------
ref: str = "R32",
V_cmp_ref: float | None = None,
dT_superheat: float = 3.0,
dT_subcool: float = 3.0,
# 2. Heat exchanger UA ---------------------------
UA_ou_rated: float | None = None,
UA_iu_rated: float | None = None,
n_ou: float = 0.65,
n_iu: float = 0.65,
# 3. Outdoor unit fan ----------------------------
dV_ou_fan_a_rated: float | None = None,
dP_ou_fan_rated: float | None = None,
A_cross_ou: float | None = None,
eta_ou_fan_rated: float | None = None,
# 4. Indoor unit fan -----------------------
dV_iu_fan_a_rated: float | None = None,
dP_iu_fan_rated: float | None = None,
A_cross_iu: float | None = None,
eta_iu_fan_rated: float | None = None,
# 5. System capacity / room ----------------------
hp_capacity: float = 4000.0,
T_a_room: float = 27.0,
# 6. Cycle guard ---------------------------------
dT_hx_min: float = 0.5,
# Compressor pressure-ratio envelope (PR = P_cond / P_evap)
PR_cycle_min: float = 1.5,
# 5.0 rejected ordinary cold-weather heating: a split unit lifting from
# -15 degC outdoor air to a 27 degC room runs at a pressure ratio near
# 7, and Daikin publishes performance down to -20 degC. The guard is a
# sanity bound, not a performance model, so it is set at the AC-scroll
# self-unload limit cited in `compressor_envelope` (~11:1) rather than
# below the equipment's own published envelope. Every family uses it.
PR_cycle_max: float = PR_CYCLE_MAX_SINGLE_STAGE,
# Compressor speed bounds [rev/s]; rps_max=None -> default_rps_max(rps_rated)
rps_min: float = 15.0,
rps_max: float | None = None,
# Approach-temperature search bounds [K]: how far the refrigerant
# saturation temperature may stand from the inlet air on either side.
# The upper bound is a modelling limit, not a component limit: a coil
# at its largest airflow and the widest approach is reported as the
# ceiling (``capacity_binding == "cycle"``).
#
# 30 K is the box the catalogue parity runs have always used, and the
# one a default machine needs. The coils are dry, so the nameplate is
# all sensible heat, and at the largest airflow indoor units publish
# (150-160 m3/h per kW from 9 kW up, tmhp.default_inputs) the room air
# changes by about 20 K at nameplate capacity. With an upper bound of
# 20 K the bound itself was the limit at the rating point: a default
# 15 kW unit delivered 89 % of its nameplate at 35/27 degC and 76 % at
# -7/20 degC. At 30 K every default unit from 1.5 to 50 kW, of either
# indoor class and either rated duty, delivers its nameplate at both
# rating points (ISO 5151 T1 and H1).
dT_approach_bounds: tuple[float, float] = (1.0, 30.0),
# ASHRAE 90.1-2022 VSD coefficients
vsd_coeffs_ou: dict | None = None,
vsd_coeffs_iu: dict | None = None,
# Deprecated:
V_disp_cmp: float | None = None,
UA_cond_rated: float | None = None,
UA_evap_rated: float | None = None,
n_cond: float | None = None,
n_evap: float | None = None,
UA_cond_design: float | None = None,
UA_evap_design: float | None = None,
dV_ou_fan_a_design: float | None = None,
dP_ou_fan_design: float | None = None,
eta_ou_fan_design: float | None = None,
dV_iu_fan_a_design: float | None = None,
dP_iu_fan_design: float | None = None,
eta_iu_fan_design: float | None = None,
*,
compressor_scale: CompressorMapScale | None = None,
rps_rated: float | None = None,
m_dot_ref_rated: float | None = None,
rated_condition: Mapping[str, Any] | RatingCondition | None = None,
# Effective outdoor-coil conductance as an evaporator (heating) [W/K];
# None: the approach-temperature default, or UA_ou_rated when that is given.
UA_ou_evap_rated: float | None = None,
dV_ou_fan_a_ref: float | None = None,
dV_ou_fan_a_min: float | None = None,
dV_ou_fan_a_max: float | None = None,
dV_iu_fan_a_ref: float | None = None,
dV_iu_fan_a_min: float | None = None,
dV_iu_fan_a_max: float | None = None,
# Electric power of each fan at its rated (largest) air flow [W], e.g. a
# catalogue fan power; None: rated flow x dP_*_fan_rated / eta_*_fan_rated.
E_ou_fan_rated: float | None = None,
E_iu_fan_rated: float | None = None,
# On/off cycling below the minimum continuous capacity: EN 14825
# degradation coefficient Cd (None: no cycling, the unit over-delivers).
Cd_cycling: CyclingDegradation | float | None = CD_AIR_DEFAULT,
# Frost on the outdoor coil and its defrost, heating only (None / False: off).
defrost: DefrostModel | bool | None = True,
T_dis_max: float | Literal["auto"] | None = "auto",
x_suction_min: float | Literal["auto"] | None = "auto",
T_cond_max: float | Literal["auto"] | None = "auto",
# Indoor-unit class whose catalogue airflow stands in for an omitted
# dV_iu_fan_a_rated: "wall_mounted" or "floor_standing".
indoor_unit_type: str = "wall_mounted",
):
validate_ctor("ASHP", locals())
import warnings
if dV_ou_fan_a_ref is not None:
dV_ou_fan_a_rated = dV_ou_fan_a_ref
if dV_iu_fan_a_ref is not None:
dV_iu_fan_a_rated = dV_iu_fan_a_ref
# Resolve deprecated mapping
if V_cmp_ref is None:
# No displacement given: the one a compressor catalogue gives for this capacity
# and refrigerant (tmhp.default_inputs), recorded in default_input_estimates.
V_cmp_ref = V_disp_cmp if V_disp_cmp is not None else self._default_displacement(hp_capacity, ref)
# UA_cond/evap_design → UA_cond/evap_rated (oldest names, two hops)
if UA_cond_rated is None:
UA_cond_rated = UA_cond_design
if UA_evap_rated is None:
UA_evap_rated = UA_evap_design
# UA_cond/evap_rated → UA_ou/iu_rated (rename from cycle role to physical unit)
if UA_cond_rated is not None or UA_evap_rated is not None:
warnings.warn(
"UA_cond_rated/UA_evap_rated are deprecated and will be removed in a future"
" release. Use UA_ou_rated/UA_iu_rated (physical unit identity).",
DeprecationWarning,
stacklevel=2,
)
if UA_ou_rated is None:
UA_ou_rated = UA_cond_rated
if UA_iu_rated is None:
UA_iu_rated = UA_evap_rated
if n_cond is not None or n_evap is not None:
warnings.warn(
"n_cond/n_evap are deprecated and will be removed in a future release. Use n_ou/n_iu.",
DeprecationWarning,
stacklevel=2,
)
if n_cond is not None:
n_ou = n_cond
if n_evap is not None:
n_iu = n_evap
if dV_ou_fan_a_rated is None:
dV_ou_fan_a_rated = dV_ou_fan_a_design
if dP_ou_fan_rated is None:
dP_ou_fan_rated = dP_ou_fan_design
if eta_ou_fan_rated is None:
eta_ou_fan_rated = eta_ou_fan_design
if dV_iu_fan_a_rated is None:
dV_iu_fan_a_rated = dV_iu_fan_a_design
if dP_iu_fan_rated is None:
dP_iu_fan_rated = dP_iu_fan_design
if eta_iu_fan_rated is None:
eta_iu_fan_rated = eta_iu_fan_design
if not vsd_coeffs_ou:
vsd_coeffs_ou = SINGLE_ZONE_VAV_COEFFICIENTS.copy()
if not vsd_coeffs_iu:
vsd_coeffs_iu = SINGLE_ZONE_VAV_COEFFICIENTS.copy()
# --- 1. Refrigerant / cycle / compressor ---
self.ref: str = ref
import CoolProp.CoolProp as CP
#: Critical temperature of the refrigerant [K]. The cycle this model
#: solves is subcritical, so it bounds every saturation temperature the
#: operating-point search may propose.
self._T_crit_K: float = float(CP.PropsSI("Tcrit", ref))
self.V_cmp_ref: float = V_cmp_ref
self.dT_superheat: float = dT_superheat
self.dT_subcool: float = dT_subcool
self.dT_hx_min: float = dT_hx_min
# Compressor pressure-ratio envelope (floor -> clamp, ceiling -> reject)
self.PR_cycle_min: float = PR_cycle_min
self.PR_cycle_max: float = PR_cycle_max
# Compressor speed search bounds [rev/s]
self.rps_min: float = rps_min
# rps_max=None: searched up to RATED_SPEED_SEARCH_MAX for the rated
# speed, then replaced by default_rps_max(rps_rated) (reference_state).
self._rps_max_derived: bool = rps_max is None
self.rps_max: float = RATED_SPEED_SEARCH_MAX if rps_max is None else rps_max
# Discharge-temperature limit [degC] ("auto": refrigerant default; None: off)
self.T_dis_max: float | None = resolve_discharge_temp_max(T_dis_max, ref)
# Maximum condensing temperature [degC] ("auto": refrigerant default; None: off)
self.T_cond_max: float | None = resolve_condensing_temp_max(T_cond_max, ref)
# Discharge-temperature control: lowest suction quality (None: no control)
self.x_suction_min: float | None = resolve_x_suction_min(x_suction_min, ref)
#: Suction quality of the cycle being evaluated (< 1 only inside the control).
self._x_suction: float = 1.0
self.dT_approach_bounds: tuple[float, float] = (
float(dT_approach_bounds[0]),
float(dT_approach_bounds[1]),
)
# Records the PR-envelope event of the most recent _calc_state call
# (None | ("pr_below_min", pr, bound) | ("pr_above_max", pr, bound)).
self._last_pr_event: tuple[str, float, float] | None = None
self.hp_capacity: float = hp_capacity
self.n_ou: float = n_ou
self.n_iu: float = n_iu
# --- 3. Outdoor unit fan ---
# The rated airflow is the unit's largest: with none given it is the
# largest fan step single-split outdoor units of this capacity publish
# (tmhp.default_inputs), for the duty the nameplate names. The fan
# modulates below it; UA_ou_rated and the fan power are stated at it.
rating_mode = self._rating_mode(rated_condition)
if dV_ou_fan_a_rated is None:
self.dV_ou_fan_a_rated = self._default_max_airflow(
"dV_ou_fan_a_rated", hp_capacity, side="outdoor", product="single_split", mode=rating_mode
)
else:
self.dV_ou_fan_a_rated = dV_ou_fan_a_rated
self.dV_ou_fan_a_ref = self.dV_ou_fan_a_rated
self.dV_ou_fan_a_min, self.dV_ou_fan_a_max = resolve_fan_flow_limits(
self.dV_ou_fan_a_ref,
dV_ou_fan_a_min,
dV_ou_fan_a_max,
custom_curve=not is_generic_fan_curve(vsd_coeffs_ou),
)
# Rated fan power: given, or rated flow x pressure / efficiency (None when the power is given).
self.E_ou_fan_rated: float
self.dP_ou_fan_rated: float | None
self.eta_ou_fan_rated: float | None
self.E_ou_fan_rated, self.dP_ou_fan_rated, self.eta_ou_fan_rated = resolve_fan_rated_power(
self.dV_ou_fan_a_rated,
E_ou_fan_rated,
dP_ou_fan_rated,
eta_ou_fan_rated,
names=("E_ou_fan_rated", "dP_ou_fan_rated", "eta_ou_fan_rated"),
)
if A_cross_ou is None:
self.A_cross_ou = self.dV_ou_fan_a_rated / 2.0
else:
self.A_cross_ou = A_cross_ou
self.vsd_coeffs_ou: dict = vsd_coeffs_ou
self.fan_params_ou: dict = {
"fan_min_flow_rate": self.dV_ou_fan_a_min,
"fan_max_flow_rate": self.dV_ou_fan_a_max,
"fan_ref_flow_rate": self.dV_ou_fan_a_rated,
"fan_rated_flow_rate": self.dV_ou_fan_a_rated,
"fan_ref_power": self.E_ou_fan_rated,
"fan_rated_power": self.E_ou_fan_rated,
}
# --- 4. Indoor unit fan ---
# The indoor airflow sets the condensing (heating) and evaporating
# (cooling) temperatures through the coil's approach, so it decides
# the supply-air temperature and most of the lift. With none given it
# is the largest fan step indoor units of this class and capacity
# publish (tmhp.default_inputs).
self.indoor_unit_type: str = indoor_unit_type
if dV_iu_fan_a_rated is None:
if indoor_unit_type not in INDOOR_UNIT_TYPES:
raise ValueError(
f"indoor_unit_type={indoor_unit_type!r} has no catalogue airflow: use one of "
f"{', '.join(INDOOR_UNIT_TYPES)}, or give the unit's own dV_iu_fan_a_rated"
)
self.dV_iu_fan_a_rated = self._default_max_airflow(
"dV_iu_fan_a_rated", hp_capacity, side="indoor", product=indoor_unit_type, mode=rating_mode
)
else:
self.dV_iu_fan_a_rated = dV_iu_fan_a_rated
self.dV_iu_fan_a_ref = self.dV_iu_fan_a_rated
self.dV_iu_fan_a_min, self.dV_iu_fan_a_max = resolve_fan_flow_limits(
self.dV_iu_fan_a_ref,
dV_iu_fan_a_min,
dV_iu_fan_a_max,
custom_curve=not is_generic_fan_curve(vsd_coeffs_iu),
)
self.E_iu_fan_rated: float
self.dP_iu_fan_rated: float | None
self.eta_iu_fan_rated: float | None
self.E_iu_fan_rated, self.dP_iu_fan_rated, self.eta_iu_fan_rated = resolve_fan_rated_power(
self.dV_iu_fan_a_rated,
E_iu_fan_rated,
dP_iu_fan_rated,
eta_iu_fan_rated,
names=("E_iu_fan_rated", "dP_iu_fan_rated", "eta_iu_fan_rated"),
)
if A_cross_iu is None:
self.A_cross_iu = self.dV_iu_fan_a_rated / 2.0
else:
self.A_cross_iu = A_cross_iu
self.vsd_coeffs_iu: dict = vsd_coeffs_iu
self.fan_params_iu: dict = {
"fan_min_flow_rate": self.dV_iu_fan_a_min,
"fan_max_flow_rate": self.dV_iu_fan_a_max,
"fan_ref_flow_rate": self.dV_iu_fan_a_rated,
"fan_rated_flow_rate": self.dV_iu_fan_a_rated,
"fan_ref_power": self.E_iu_fan_rated,
"fan_rated_power": self.E_iu_fan_rated,
}
# --- 2. Heat exchanger UA ---
# Stated at the rated (largest) airflows resolved above. A default is the
# effective conductance that reproduces the saturation temperature real
# machines print at their rating point (tmhp.default_inputs.estimate_hx_UA,
# leaving-end approach law), sized for the coil's own duty -- the outdoor
# coil rejects the nameplate plus the compressor work as a condenser and
# absorbs less than the nameplate as an evaporator
# (hx_duty_per_nameplate). The same coil therefore has one value as a
# condenser (cooling) and another as an evaporator (heating). A value
# the caller gives is used as given; a given UA_ou_rated without
# UA_ou_evap_rated serves both roles.
outdoor_condensing = "outdoor_coil|fin_tube|condensing"
outdoor_evaporating = "outdoor_coil|fin_tube|evaporating"
rating_temperatures = RATING_STANDARDS[self._RATING_FAMILY]
if UA_ou_rated is None:
# Air at the ISO 5151 T1 outdoor dry bulb (35 degC).
self.UA_ou_rated = self._default_hx_UA(
"UA_ou_rated",
outdoor_condensing,
nameplate=hp_capacity,
nameplate_mode=rating_mode,
heat_capacity_rate=air_heat_capacity_rate(
self.dV_ou_fan_a_rated, rating_temperatures["cooling"].source_T_C
),
)
else:
self.UA_ou_rated = UA_ou_rated
if UA_ou_evap_rated is not None:
self.UA_ou_evap_rated = UA_ou_evap_rated
elif UA_ou_rated is not None:
# A coil value the caller gave is not silently split into two roles.
self.UA_ou_evap_rated = self.UA_ou_rated
else:
# Air at the ISO 5151 H1 outdoor dry bulb (7 degC).
self.UA_ou_evap_rated = self._default_hx_UA(
"UA_ou_evap_rated",
outdoor_evaporating,
nameplate=hp_capacity,
nameplate_mode=rating_mode,
heat_capacity_rate=air_heat_capacity_rate(
self.dV_ou_fan_a_rated, rating_temperatures["heating"].source_T_C
),
)
# The indoor coil keeps its earlier rule, 0.16 W/K per watt of nameplate,
# no longer tied to the outdoor coil: the archive issues no value for
# wall-mounted indoor coils (see INDOOR_UA_KEPT_REASON).
if UA_iu_rated is None:
self.UA_iu_rated = self._use_default_input(
"UA_iu_rated",
kept_hx_UA(
"indoor_coil|wall_mounted|fin_tube|condensing",
INDOOR_UA_PER_CAPACITY * hp_capacity,
duty=hp_capacity,
rule=f"UA_iu_rated = {INDOOR_UA_PER_CAPACITY:g} W/K per W of nameplate, the earlier rule, kept.",
reason=INDOOR_UA_KEPT_REASON,
),
)
else:
self.UA_iu_rated = UA_iu_rated
# --- 5. Room temperature ---
self.T_a_room: float = T_a_room
# --- 5b. Part load below the minimum continuous capacity ---
#: EN 14825 cycling degradation (None: continuous at minimum speed).
self.cycling: CyclingDegradation | None = resolve_cycling(Cd_cycling, "air")
# --- 5c. Frost on the outdoor coil and its defrost (heating) ---
self.defrost = resolve_defrost(defrost)
# --- 6. Compressor reference state (rated speed, rated mass flow) ---
self._initialize_reference_state(
rps_rated=rps_rated,
m_dot_ref_rated=m_dot_ref_rated,
compressor_scale=compressor_scale,
rated_condition=rated_condition,
)
def _rating_side(self, role: str, mode: str, T_in_C: float) -> HXSide:
"""Outdoor coil is the source side, indoor coil the load side, in either mode."""
if role == "source":
return AirCoilSide("air", T_in_C, self._UA_ou_rated_for(mode), self.dV_ou_fan_a_ref)
return AirCoilSide("air", T_in_C, self.UA_iu_rated, self.dV_iu_fan_a_ref)
def _UA_ou_rated_for(self, mode: str) -> float:
"""Rated outdoor-coil conductance in ``mode`` [W/K]: a condenser in cooling, an evaporator in heating."""
return self.UA_ou_evap_rated if mode == "heating" else self.UA_ou_rated
# =============================================================
# Room humidity (wet indoor coil in cooling)
# =============================================================
@contextlib.contextmanager
def _solving_with_room_humidity(self, RH_room: float | None, T_a_room: float, cooling: bool) -> Iterator[None]:
"""Solve the block's operating points with the indoor coil of a room at ``RH_room``.
In cooling with ``RH_room`` given (a fraction, 0-1) the indoor coil
is the wet coil for room air of that humidity at ``T_a_room`` [°C]
and one standard atmosphere
(:func:`tmhp.defrost.humidity_ratio`). Otherwise -- no ``RH_room``,
heating, off -- it is the dry coil, also for a solve nested in a wet
one (the frost balance of a heating point). The state before the
block is restored on the way out.
"""
outer = (self._RH_room, self._w_room)
if cooling and RH_room is not None:
self._RH_room, self._w_room = RH_room, humidity_ratio(T_a_room, RH_room)
else:
self._RH_room = self._w_room = None
try:
with contextlib.ExitStack() as stack:
if self._coil_may_be_wet:
# The searches of one wet solve share what they find of its condition.
stack.enter_context(self._sharing_wet_points())
yield
finally:
self._RH_room, self._w_room = outer
#: What the searches of a cooling condition solved with a room humidity
#: have found, while a solve or a dynamic run is in progress (``None``
#: outside one): the ordinary search of a duty, the low-load point and
#: the ceiling, each by ``(kind, T0, T_a_room, room humidity ratio, ...)``.
#: Every entry is what solving it again gives -- the searches are
#: functions of the condition and the duty -- so the memory saves time
#: and changes no result (:meth:`_sharing_wet_points`).
_wet_points: dict[tuple, Any] | None = None
@contextlib.contextmanager
def _sharing_wet_points(self) -> Iterator[None]:
"""Keep what the wet coil's searches find while the block runs (:attr:`_wet_points`).
A wet cooling condition is searched three ways: the operating point
of a request (:meth:`_optimize_operation`), the smallest continuous
duty above a request refused from below
(:meth:`_smallest_continuous_operating_point`) and the ceiling
(:meth:`max_capacity`). Where one finds nothing it takes the point
another has verified (:meth:`_point_of_another_search`,
:meth:`_largest_duty_above_low_load_point`), so the same search can
be asked for several times in one solve. Inside the block each is
made once per condition. The memory ends with the outermost block --
one :meth:`analyze_steady` or :meth:`max_capacity` call, or one
:meth:`analyze_dynamic` run -- and nothing in it is read as anything
but what the same search would return again: a result does not
depend on what was solved before it.
"""
outer = self._wet_points
if outer is None:
self._wet_points = {}
try:
yield
finally:
self._wet_points = outer
def _wet_point_key(self, kind: str, T0: float, T_a_room: float, *more: float) -> tuple:
"""Key of an entry of :attr:`_wet_points` for the condition being solved."""
return (kind, float(T0), float(T_a_room), self._w_room, *more)
@property
def _coil_may_be_wet(self) -> bool:
"""Whether the point being solved is a cooling point whose room air holds water vapour.
Only then do the searches differ from the dry coil's
(:meth:`_largest_airflow_approaches`, :meth:`_largest_deliverable_wet_duty`,
:attr:`_MIN_AIRFLOW`). Room air with no water vapour (``RH_room = 0``)
is solved as the dry coil is, step for step.
"""
return self._w_room is not None and self._w_room > 0.0
def _wet_coil_drive(self, approach: float, T_a_room: float) -> float:
"""Driving temperature difference of the wet indoor coil at ``approach`` [K].
The approach (room air minus evaporating temperature) plus the latent
part at that evaporating temperature
(:func:`~tmhp.heat_exchanger.wet_coil_latent_difference`); the
approach itself where the coil is above the room's dew point.
"""
assert self._w_room is not None
return approach + wet_coil_latent_difference(self._w_room, cu.C2K(T_a_room) - approach)
def _wet_coil_approach(self, approach: float, duty: float, capacity: float, T_a_room: float) -> float:
"""Approach at which the wet indoor coil carries ``duty`` where it carries ``capacity`` at ``approach`` [K].
A dry coil's capacity at a fixed airflow is proportional to its
approach, so the answer there is ``approach * duty / capacity``. A wet coil's
is proportional to its driving difference (:meth:`_wet_coil_drive`),
which grows faster than the approach once water condenses, so the
approach is solved from it.
The answer is wanted inside the approach bounds only (the caller cuts
it to them), and the driving difference is evaluated nowhere else: a
coil far short of its duty asks for a difference many times the
present one, and the approach that scales to is below any state of
humid air (a duty four times the capacity at a 30 K approach: 120 K,
an evaporating temperature of -93 degC). The driving difference is
continuous and increasing in the approach, so the wanted one is
compared with those at the two bounds first: at or beyond one of them
the answer is that bound, and only a root between them is solved.
With no water vapour in the room air (``RH_room = 0``) the coil is
dry at every approach and the dry expression is returned as it is.
"""
assert self._w_room is not None
scaled = approach * duty / capacity
if not self._w_room > 0.0:
return scaled
lo, hi = self.dT_approach_bounds
present = self._wet_coil_drive(approach, T_a_room)
goal = present * duty / capacity
if not (math.isfinite(goal) and goal > 0.0):
return scaled
if present == approach:
inside = min(max(scaled, lo), hi)
if self._wet_coil_drive(inside, T_a_room) == inside:
return scaled # dry before and after
if goal <= self._wet_coil_drive(lo, T_a_room):
return lo
if goal >= self._wet_coil_drive(hi, T_a_room):
return hi
return float(
brentq(
lambda x: self._wet_coil_drive(x, T_a_room) - goal,
lo,
hi,
xtol=1e-13,
rtol=4.0 * np.finfo(float).eps,
)
)
# =============================================================
# Refrigerant cycle physics
# =============================================================
@discharge_controlled(reject=True)
@reject_invalid_efficiency
def _calc_state(
self,
dT_ref_evap: float,
dT_ref_cond: float,
Q_r_iu: float,
T0: float,
T_a_room: float,
) -> dict | None:
"""Evaluate refrigerant cycle at a given operating point.
Parameters
----------
dT_ref_evap : float
Evaporator approach ΔT [K].
dT_ref_cond : float
Condenser approach ΔT [K].
Q_r_iu : float
Indoor thermal load [W].
Positive = cooling (indoor unit is evaporator).
Negative = heating (indoor unit is condenser).
T0 : float
Dead-state / outdoor-air temperature [°C].
T_a_room : float
Room air temperature [°C].
Returns
-------
dict | None
Cycle performance dictionary; ``None`` if infeasible.
"""
T0_K: float = cu.C2K(T0)
T_a_room_K: float = cu.C2K(T_a_room)
is_active: bool = Q_r_iu != 0.0
if not is_active:
cs: dict = calc_ref_state(
T_evap_K=T0_K,
T_cond_K=T0_K,
refrigerant=self.ref,
eta_ov=1.0,
f_loss=0.0,
mode="off",
dT_superheat=self.dT_superheat,
dT_subcool=self.dT_subcool,
is_active=False,
)
result = reportable_state(cs)
result.update(
{
"hp_is_on": False,
"converged": True,
"converged_rps": True,
"capacity_clamped": None,
"ou_fan_flow_min_limit": False,
"ou_fan_flow_max_limit": False,
"iu_fan_flow_min_limit": False,
"iu_fan_flow_max_limit": False,
# Temperatures [°C]
"T_ou_a_in [°C]": T0,
"T_ou_a_mid [°C]": T0,
"T_ou_a_out [°C]": T0,
"T_iu_a_in [°C]": T_a_room,
"T_iu_a_mid [°C]": T_a_room,
"T_iu_a_out [°C]": T_a_room,
"T_a_room [°C]": T_a_room,
"T0 [°C]": T0,
# Volume flow rates [m3/s]
"dV_ou_a [m3/s]": 0.0,
"v_ou_a [m/s]": 0.0,
"dV_iu_a [m3/s]": 0.0,
"v_iu_a [m/s]": 0.0,
"m_dot_ref [kg/s]": 0.0,
"cmp_rpm [rpm]": 0.0,
# Energy rates [W]
"E_iu_fan [W]": 0.0,
"E_ou_fan [W]": 0.0,
# Heat duties by physical location (mode-independent labels)
"Q_ref_iu [W]": 0.0,
"Q_a_iu_in [W]": 0.0,
"Q_a_iu_out [W]": 0.0,
"indoor_heat_direction_valid": True,
"Q_ref_ou [W]": 0.0,
"E_cmp [W]": 0.0,
"Q_cmp_loss [W]": 0.0,
"E_tot [W]": 0.0,
# COP metrics
"cop_ref [-]": np.nan,
"cop_sys [-]": np.nan,
# Indoor coil split and room side: nothing crosses the coil.
"Q_iu_sensible [W]": 0.0,
"Q_iu_latent [W]": 0.0,
"SHR_iu [-]": np.nan,
"m_dot_iu_condensate [kg/s]": 0.0,
"Q_room_sensible [W]": 0.0,
**self._room_humidity_keys(None),
}
)
return result
if Q_r_iu > 0:
# Cooling mode: indoor = evaporator, outdoor = condenser
mode = "cooling"
T_evap_sat_K = T_a_room_K - dT_ref_evap # evap below room
T_cond_sat_K = T0_K + dT_ref_cond # cond above outdoor
else:
# Heating mode: indoor = condenser, outdoor = evaporator
mode = "heating"
T_evap_sat_K = T0_K - dT_ref_evap # evap below outdoor
T_cond_sat_K = T_a_room_K + dT_ref_cond # cond above room
# A saturation temperature at or above the critical point has no
# saturation pressure, so the subcritical cycle this model solves does
# not exist there. Reject it as an infeasible candidate rather than
# letting the property call raise: the search probes approach
# temperatures freely, and a wide enough upper bound will reach the
# critical temperature on a hot day (R410A: 71.3 degC).
if T_cond_sat_K >= self._T_crit_K or T_evap_sat_K >= self._T_crit_K:
return None
# Low-lift feasibility is enforced downstream by the compressor
# pressure-ratio floor (PR_cycle_min); a separate fixed minimum lift is
# redundant and non-transferable across refrigerants/operating levels.
actual_dT_subcool: float = min(self.dT_subcool, max(0.0, dT_ref_cond - self.dT_hx_min))
actual_dT_superheat: float = min(self.dT_superheat, max(0.0, dT_ref_evap - self.dT_hx_min))
# Same name (`cs`) is annotated up in the inactive branch (~L206);
# re-annotating here triggers mypy [no-redef] even though the
# inactive branch returns unconditionally. Use plain assignment.
#
# The cycle without its discharge state: pressures, suction state and
# isentropic discharge enthalpy are what the speed solve needs, and
# the discharge state follows from the efficiency at the solved speed.
try:
cs, h_ref_cmp_out_isen = calc_ref_state_without_discharge(
T_evap_sat_K,
T_cond_sat_K,
self.ref,
mode=mode,
dT_superheat=actual_dT_superheat,
x_suction=self._x_suction,
dT_subcool=actual_dT_subcool,
)
except ValueError:
# The fluid has no state at this candidate (a flash CoolProp cannot
# solve): no cycle here. The search treats it as infeasible instead
# of the whole solve raising.
return None
h_cmp_in: float = cs["h_ref_cmp_in [J/kg]"]
h_exp_in: float = cs["h_ref_exp_in [J/kg]"]
h_exp_out: float = cs["h_ref_exp_out [J/kg]"]
rho_in: float = cs["rho_ref_cmp_in [kg/m3]"]
P_evap = cs["P_ref_cmp_in [Pa]"]
P_cond = cs["P_ref_cmp_out [Pa]"]
ratio_P_cmp = P_cond / P_evap if P_evap > 0 else 1.0
# Compressor pressure-ratio envelope guard. PR is the physically primary
# limit (a fixed temperature lift maps to PR non-linearly per refrigerant
# and operating level). Ceiling -> reject (outside single-stage envelope);
# floor -> clamp the cycle onto PR_cycle_min (continuous low-lift
# transition) by holding P_evap and projecting P_cond. Both events are
# recorded on self._last_pr_event for the analyze_steady hint; no print
# here (this runs inside the optimiser loop).
self._last_pr_event = None
pr_event = check_pr_envelope(ratio_P_cmp, self.PR_cycle_min, self.PR_cycle_max)
if pr_event == "pr_above_max":
self._last_pr_event = ("pr_above_max", ratio_P_cmp, self.PR_cycle_max)
return None
if pr_event == "pr_below_min":
self._last_pr_event = ("pr_below_min", ratio_P_cmp, self.PR_cycle_min)
# Clamp: hold P_evap, project P_cond = PR_cycle_min * P_evap, invert
# the saturation curve for the constrained condensing temperature,
# then refresh the cycle state at the clamped condition.
P_cond = self.PR_cycle_min * P_evap
try:
T_cond_sat_K = props_si("T", "P", P_cond, "Q", 0, self.ref)
cs, h_ref_cmp_out_isen = calc_ref_state_without_discharge(
T_evap_sat_K,
T_cond_sat_K,
self.ref,
mode=mode,
dT_superheat=actual_dT_superheat,
x_suction=self._x_suction,
dT_subcool=actual_dT_subcool,
)
except ValueError:
# The floor pressure has no saturation state (above the
# critical pressure): no cycle at this candidate.
return None
h_cmp_in = cs["h_ref_cmp_in [J/kg]"]
h_exp_in = cs["h_ref_exp_in [J/kg]"]
h_exp_out = cs["h_ref_exp_out [J/kg]"]
rho_in = cs["rho_ref_cmp_in [kg/m3]"]
P_evap = cs["P_ref_cmp_in [Pa]"]
P_cond = cs["P_ref_cmp_out [Pa]"]
ratio_P_cmp = P_cond / P_evap if P_evap > 0 else self.PR_cycle_min
scale = self.compressor_scale
def _residual_rps(rps):
eta_r = scale.evaluate(ratio_P_cmp, rps, T_evap_sat_K)
h_cmp_out_local = discharge_enthalpy(h_cmp_in, h_ref_cmp_out_isen, eta_r.eta_ov, eta_r.f_loss)
dh_cond_local = h_cmp_out_local - h_exp_in
dh_evap_local = h_cmp_in - h_exp_out
m_dot = self.V_cmp_ref * rho_in * eta_r.eta_v * rps
if mode == "cooling":
return (m_dot * dh_evap_local) - abs(Q_r_iu)
else:
return (m_dot * dh_cond_local) - abs(Q_r_iu)
cmp_rps, converged_rps, capacity_clamped = solve_compressor_speed(_residual_rps, self.rps_min, self.rps_max)
eta = scale.evaluate(ratio_P_cmp, cmp_rps, T_evap_sat_K)
cs = with_discharge_state(cs, h_ref_cmp_out_isen, eta.eta_ov, eta.f_loss, self.ref)
h_cmp_out_final = cs["h_ref_cmp_out [J/kg]"]
m_dot_ref = self.V_cmp_ref * rho_in * eta.eta_v * cmp_rps
Q_ref_cond = m_dot_ref * (h_cmp_out_final - h_exp_in)
Q_ref_evap = m_dot_ref * (h_cmp_in - h_exp_out)
# Map refrigerant-role duties to physical-location duties for output.
# Heating: IU = condenser, OU = evaporator; cooling: roles swap.
Q_ref_iu = Q_ref_cond if mode == "heating" else Q_ref_evap
Q_ref_ou = Q_ref_evap if mode == "heating" else Q_ref_cond
E_cmp = compressor_power(m_dot_ref, h_cmp_in, h_ref_cmp_out_isen, eta.eta_ov)
Q_cmp_loss = eta.f_loss * E_cmp
# Reject negative compressor power (unphysical)
if E_cmp <= 0:
return None
# ── Outdoor unit HX ──
# In cooling the outdoor coil is the condenser (UA_ou_rated), in heating
# the evaporator (UA_ou_evap_rated): one coil, but its effective
# conductance differs by refrigerant role (see the constructor).
if mode == "cooling":
# Outdoor = condenser → ref rejects heat → air is heated
ou_hx = calc_HX_perf_for_target_heat(
Q_ref_target=Q_ref_cond,
T_a_in_C=T0,
T_ref_sat_K=T_cond_sat_K,
A_cross=self.A_cross_ou,
UA_rated=self._UA_ou_rated_for(mode),
dV_fan_ref=self.dV_ou_fan_a_ref,
dV_fan_min=self.dV_ou_fan_a_min,
dV_fan_max=self.dV_ou_fan_a_max,
custom_fan_curve=not is_generic_fan_curve(self.vsd_coeffs_ou),
is_active=True,
exponent=self.n_ou,
rho_air="inlet",
)
else:
# Outdoor = evaporator → ref absorbs heat → air is cooled
ou_hx = calc_HX_perf_for_target_heat(
Q_ref_target=Q_ref_evap,
T_a_in_C=T0,
T_ref_sat_K=T_evap_sat_K,
A_cross=self.A_cross_ou,
UA_rated=self._UA_ou_rated_for(mode),
dV_fan_ref=self.dV_ou_fan_a_ref,
dV_fan_min=self.dV_ou_fan_a_min,
dV_fan_max=self.dV_ou_fan_a_max,
custom_fan_curve=not is_generic_fan_curve(self.vsd_coeffs_ou),
is_active=True,
exponent=self.n_ou,
rho_air="inlet",
)
dV_ou_a: float = ou_hx["dV_fan"]
T_ou_a_mid: float = ou_hx["T_a_mid_C"]
E_ou_fan: float = calc_fan_power_from_dV_fan(
dV_fan=dV_ou_a,
fan_params=self.fan_params_ou,
vsd_coeffs=self.vsd_coeffs_ou,
is_active=True,
)
# The fan heat warms the same air mass the coil exchanged heat with:
# the fan's volume flow at the density of the air drawn in.
C_ou_a: float = air_heat_capacity_rate(dV_ou_a, T0)
T_ou_a_out: float = T_ou_a_mid + E_ou_fan / C_ou_a if dV_ou_a > 0 else T0
v_ou_a: float = dV_ou_a / self.A_cross_ou
# ── Indoor unit HX ──
# The indoor coil is always parameterised by UA_iu_rated regardless of mode.
if mode == "cooling":
# Indoor = evaporator → ref absorbs heat → air is cooled
iu_hx = calc_HX_perf_for_target_heat(
Q_ref_target=Q_ref_evap,
T_a_in_C=T_a_room,
T_ref_sat_K=T_evap_sat_K,
A_cross=self.A_cross_iu,
UA_rated=self.UA_iu_rated,
dV_fan_ref=self.dV_iu_fan_a_ref,
dV_fan_min=self.dV_iu_fan_a_min,
dV_fan_max=self.dV_iu_fan_a_max,
custom_fan_curve=not is_generic_fan_curve(self.vsd_coeffs_iu),
is_active=True,
exponent=self.n_iu,
rho_air="inlet",
# Room humidity ratio: the coil condenses water where the
# evaporating temperature is below the room's dew point.
# None (no RH_room): the dry coil.
w_a_in=self._w_room,
)
else:
# Indoor = condenser → ref rejects heat → air is heated
iu_hx = calc_HX_perf_for_target_heat(
Q_ref_target=Q_ref_cond,
T_a_in_C=T_a_room,
T_ref_sat_K=T_cond_sat_K,
A_cross=self.A_cross_iu,
UA_rated=self.UA_iu_rated,
dV_fan_ref=self.dV_iu_fan_a_ref,
dV_fan_min=self.dV_iu_fan_a_min,
dV_fan_max=self.dV_iu_fan_a_max,
custom_fan_curve=not is_generic_fan_curve(self.vsd_coeffs_iu),
is_active=True,
exponent=self.n_iu,
rho_air="inlet",
)
dV_iu_a: float = iu_hx["dV_fan"]
T_iu_a_mid: float = iu_hx["T_a_mid_C"]
E_iu_fan: float = calc_fan_power_from_dV_fan(
dV_fan=dV_iu_a,
fan_params=self.fan_params_iu,
vsd_coeffs=self.vsd_coeffs_iu,
is_active=True,
)
C_iu_a: float = air_heat_capacity_rate(dV_iu_a, T_a_room)
T_iu_a_out: float = T_iu_a_mid + E_iu_fan / C_iu_a if dV_iu_a > 0 else T_a_room
v_iu_a: float = dV_iu_a / self.A_cross_iu
# --- Check convergence for both HXs ---
if not (ou_hx.get("converged", True) and iu_hx.get("converged", True)):
return {
"converged": False,
"_ou_diag": ou_hx,
"_iu_diag": iu_hx,
# The cycle exists; only a coil does not carry it. The
# discharge-temperature control acts on it, so the coil margins
# the searches read are those of the controlled cycle -- the
# same cycle a candidate whose coils close is evaluated at.
CYCLE_KEY: reportable_state(cs),
"converged_rps": bool(converged_rps),
"capacity_clamped": capacity_clamped,
"ou_fan_flow_min_limit": ou_hx.get("min_limit", False),
"ou_fan_flow_max_limit": ou_hx.get("max_limit", False),
"iu_fan_flow_min_limit": iu_hx.get("min_limit", False),
"iu_fan_flow_max_limit": iu_hx.get("max_limit", False),
}
# Check overall convergence
is_converged = ou_hx.get("converged", True) and iu_hx.get("converged", True) and converged_rps
E_tot: float = E_cmp + E_ou_fan + E_iu_fan
# Final outlet already includes fan heat. Keep the coil-load residual
# and operating-point objective unchanged; only the reported COP changes.
G_iu_a = C_iu_a
Q_a_iu_in = calc_energy_flow(G_iu_a, T_a_room_K, T0_K)
Q_a_iu_out = calc_energy_flow(G_iu_a, cu.C2K(T_iu_a_out), T0_K)
Q_air = Q_a_iu_out - Q_a_iu_in
# Sensible and latent heat across the indoor coil (air side, before the
# fan). Latent heat is zero for a dry coil: no RH_room, a coil above
# the room's dew point, heating.
Q_iu_sensible = float(C_iu_a * abs(T_a_room - T_iu_a_mid))
Q_iu_latent = float(iu_hx.get("Q_latent", 0.0))
Q_iu_total = Q_iu_sensible + Q_iu_latent
# What the room air gives up (cooling: sensible net of the fan heat,
# plus the latent heat of the water it loses) or receives (heating).
Q_room = Q_iu_latent - Q_air if mode == "cooling" else Q_air
heat_direction_valid = bool(dV_iu_a > 0 and Q_room >= 0)
# Same name (`result`) is annotated up in the inactive branch (~L216);
# plain assignment to avoid the mypy [no-redef] false positive.
result = reportable_state(cs)
result.update(
{
"hp_is_on": True,
"mode": mode,
"converged": bool(is_converged),
"converged_rps": bool(converged_rps),
"capacity_clamped": capacity_clamped,
"ou_fan_flow_min_limit": ou_hx.get("min_limit", False),
"ou_fan_flow_max_limit": ou_hx.get("max_limit", False),
"iu_fan_flow_min_limit": iu_hx.get("min_limit", False),
"iu_fan_flow_max_limit": iu_hx.get("max_limit", False),
# Temperatures [°C]
"T_ou_a_in [°C]": T0,
"T_ou_a_mid [°C]": T_ou_a_mid,
"T_ou_a_out [°C]": T_ou_a_out,
"T_iu_a_in [°C]": T_a_room,
"T_iu_a_mid [°C]": T_iu_a_mid,
"T_iu_a_out [°C]": T_iu_a_out,
"T_a_room [°C]": T_a_room,
"T0 [°C]": T0,
# Volume flow rates [m3/s]
"dV_ou_a [m3/s]": dV_ou_a,
"v_ou_a [m/s]": v_ou_a,
"dV_iu_a [m3/s]": dV_iu_a,
"v_iu_a [m/s]": v_iu_a,
"m_dot_ref [kg/s]": m_dot_ref,
"cmp_rpm [rpm]": cmp_rps * 60,
"n_star [-]": cmp_rps / self.rps_rated,
"pr_cmp [-]": ratio_P_cmp,
"eta_v [-]": eta.eta_v,
"eta_ov [-]": eta.eta_ov,
"f_loss [-]": eta.f_loss,
# Energy rates [W]
"E_iu_fan [W]": E_iu_fan,
"E_ou_fan [W]": E_ou_fan,
# Heat duties by physical location (mode-mapped): in heating the
# indoor unit is the condenser and the outdoor unit the evaporator;
# in cooling the roles swap. Reported by location so the labels are
# mode-independent and the consumer never sees the cond/evap
# bookkeeping (the refrigerant-perspective cond/evap remain only in
# the refrigerant-state keys T/P/h/s_ref_*_sat and in refrigerant.py).
"Q_ref_iu [W]": Q_ref_iu,
"Q_a_iu_in [W]": Q_a_iu_in,
"Q_a_iu_out [W]": Q_a_iu_out,
"indoor_heat_direction_valid": heat_direction_valid,
"Q_ref_ou [W]": Q_ref_ou,
"E_cmp [W]": E_cmp,
"Q_cmp_loss [W]": Q_cmp_loss,
"E_tot [W]": E_tot,
# Refrigerant COP uses coil duty; system COP uses final air delivery
# (with a wet coil: sensible plus latent, less the indoor fan heat).
"cop_ref [-]": (Q_ref_iu / E_cmp if E_cmp > 0 else np.nan),
"cop_sys [-]": (Q_room / E_tot if E_tot > 0 and heat_direction_valid else np.nan),
# Indoor coil split (air side, before the fan) and the net
# sensible heat the room gives up (cooling) or receives
# (heating) once the fan heat is counted.
"Q_iu_sensible [W]": Q_iu_sensible,
"Q_iu_latent [W]": Q_iu_latent,
"SHR_iu [-]": (Q_iu_sensible / Q_iu_total if Q_iu_total > 0 else np.nan),
"m_dot_iu_condensate [kg/s]": float(iu_hx.get("m_dot_condensate", 0.0)),
"Q_room_sensible [W]": (Q_iu_sensible - E_iu_fan if mode == "cooling" else Q_iu_sensible + E_iu_fan),
**self._room_humidity_keys(iu_hx.get("w_a_mid") if mode == "cooling" else None),
}
)
return result
def _room_humidity_keys(self, w_coil_out: float | None) -> dict[str, float]:
"""Humidity keys of a row: the room humidity used and the air's humidity ratio in and out.
NaN where no room humidity applies (no ``RH_room``, heating, a row
not asked to cool). ``w_coil_out`` is the humidity ratio of the air
leaving the coil; ``None`` on a row whose coil does not run: the air
then leaves as it entered.
"""
if self._w_room is None or self._RH_room is None:
return {"RH_room [-]": math.nan, "w_iu_a_in [kg/kg]": math.nan, "w_iu_a_out [kg/kg]": math.nan}
return {
"RH_room [-]": float(self._RH_room),
"w_iu_a_in [kg/kg]": float(self._w_room),
"w_iu_a_out [kg/kg]": float(self._w_room if w_coil_out is None else w_coil_out),
}
def _optimize_operation(
self,
Q_r_iu: float,
T0: float,
T_a_room: float,
):
"""Find the operating point the unit would run at (2-D bounded search).
Normally that is the point of minimum total electric power that meets
the requested duty. The search starts from the best of a coarse set of
approach pairs and, where that leaves it above the cost of the
least-lift point (:meth:`_largest_airflow_point`) or finds nothing,
from the least-lift point as well. When the unit is short of the
request even there -- flat out -- the result is that point, in the
capacity-limited band (:data:`OBJ_CAPACITY_LIMITED`); the ceiling is
then the caller's to solve (:meth:`_capacity_limited_operating_point`).
``least_lift_reason`` on an infeasible result says why the least-lift
point of the request is not an operating point.
Parameters
----------
Q_r_iu : float
Indoor thermal load [W].
T0 : float
Dead-state temperature [°C].
T_a_room : float
Room air temperature [°C].
Returns
-------
scipy.optimize.OptimizeResult
"""
def _objective(params) -> float:
dT_ref_evap, dT_ref_cond = params
perf: dict | None = self._calc_state(
dT_ref_evap=dT_ref_evap,
dT_ref_cond=dT_ref_cond,
Q_r_iu=Q_r_iu,
T0=T0,
T_a_room=T_a_room,
)
if perf is None or not perf.get("converged", False):
return OBJ_INFEASIBLE
E_tot: float = float(perf.get("E_tot [W]", OBJ_INFEASIBLE))
if E_tot <= 0 or np.isnan(E_tot):
return OBJ_INFEASIBLE
delivered: float = abs(float(perf.get("Q_ref_iu [W]", 0.0)))
if perf.get("capacity_clamped") == CAPACITY_CLAMPED_MAX:
# The compressor is already at ``rps_max`` and still short of the
# request. Ranking these points by power would trade delivered
# capacity away for a few watts of fan saving, which is not what
# a real unit does: once it cannot meet the load it runs flat
# out. Rank by shortfall instead, so the reported operating point
# is the machine's maximum capacity at this condition -- the
# quantity a capacity-limited hour actually needs to report.
shortfall: float = max(abs(Q_r_iu) - delivered, 0.0)
return OBJ_CAPACITY_LIMITED + shortfall
# Everything below the capacity ceiling is ranked by specific energy
# rather than raw ``E_tot`` (see `_opt_utils`). At the *lower* clamp
# -- the compressor speed floor -- every candidate over-delivers, and
# raw power picks whichever starves the coil hardest: it delivers
# least, draws least, and looks best. Cost per unit of heat actually
# delivered does not have that hole. A room cannot store the surplus,
# but the choice *among* floor candidates is still made on that cost;
# capping the credit at the request would reduce the ranking to
# ``E_tot`` and pick the starved coil again. The over-delivery is
# reported (``capacity_clamped == "min"``, ``Q_ref_iu`` > request) so
# the caller can treat it as cycling capacity.
#
# ``penalty=OBJ_INFEASIBLE`` keeps this function inside the same
# three-band scale the rest of the search reads: ordinary points come
# back in watts, a capacity-limited point at ``OBJ_CAPACITY_LIMITED``,
# and anything the helper rejects at or above ``OBJ_INFEASIBLE``, so
# the lattice fallback and the warm-start guard still fire. Leaving
# the helper's own default here would return 1e6 for an unreachable
# point, which both guards would read as a perfectly good solution.
#
# A minimum-speed candidate is met by cycling, so its cost is the
# mean input for the *requested* heat: the specific energy divided
# by the part-load factor at this candidate's capacity ratio.
return specific_energy_objective(
E_tot,
delivered,
abs(Q_r_iu),
math.inf,
penalty=OBJ_INFEASIBLE,
) * self._cycling_cost_factor(perf, Q_r_iu)
# Phase 0: a constant-speed fan. The approaches it can serve are a
# single point, which no grid or simplex lands on, so the point is
# solved from the coil capacity margins (:class:`_NarrowFanSearch`).
# Nothing is left for the phases below to find or to refine.
if self._has_constant_speed_fan():
search = _NarrowFanSearch(self, Q_r_iu, T0, T_a_room)
search.run()
value, x, _ = search.best()
lo_b, hi_b = self.dT_approach_bounds
middle = 0.5 * (lo_b + hi_b)
result = OptimizeResult(
x=np.array(x if x is not None else (middle, middle), dtype=float),
fun=value,
success=value < OBJ_INFEASIBLE,
nfev=len(search.rows),
)
if value >= OBJ_INFEASIBLE and self._coil_may_be_wet and Q_r_iu > 0:
# A wet cooling point no approach pair carries. Where its
# least-lift point is refused by the fans' smallest airflows
# (:attr:`_MIN_AIRFLOW`) the request is refused from below,
# and the caller needs to know: its answer is the smallest
# continuous duty, as for a fan that modulates (below). No
# other verdict is passed on, and none for the dry coil,
# whose rows keep the reason they had. Solved to the full
# tolerance: the step a looser one takes into the flow range
# (:meth:`_largest_airflow_point`) is more than the coil of a
# fan with one airflow closes within, and reads as this
# verdict at every duty.
with contextlib.suppress(Exception):
reason = self._largest_airflow_point(Q_r_iu, T0, T_a_room)[2]
if reason == self._MIN_AIRFLOW:
result["least_lift_reason"] = reason
return result
# Phase 1 seed: the least-lift point (both coils at their largest
# airflow). It is the widest place of the feasible set -- whatever the
# envelope or the speed range leaves of it contains this point -- so a
# feasible set thinner than any fixed candidate spacing (about 1 K
# wide for the default unit at -25 degC) is still entered. A unit that is
# short of the request even here is flat out: there is nothing to
# search, and the ceiling is the caller's (:meth:`max_capacity`).
seed: tuple[float, float] | None = None
seed_reason: str | None = None
with contextlib.suppress(Exception):
seed, seed_state, seed_reason = self._largest_airflow_point(
Q_r_iu, T0, T_a_room, rtol=self._LEAST_LIFT_SEED_RTOL
)
flat_out = seed_state is not None and seed_state.get("capacity_clamped") == CAPACITY_CLAMPED_MAX
if seed is not None and seed_state is not None and flat_out:
shortfall = max(abs(Q_r_iu) - abs(float(seed_state["Q_ref_iu [W]"])), 0.0)
return OptimizeResult(
x=np.array(seed, dtype=float), fun=OBJ_CAPACITY_LIMITED + shortfall, success=True, nfev=0
)
# Phase 1: coarse grid pre-scan to find a converging starting point.
# A single fixed x0=(15,15) fails silently when the entire search space
# is a penalty region — Nelder-Mead cannot escape because all objective
# evaluations return the same sentinel. Scanning a coarse grid first
# finds a valid basin (if one exists) so Phase 2 refines from there.
_candidates = [
(3.0, 3.0),
(5.0, 5.0),
(8.0, 8.0),
(12.0, 12.0),
(15.0, 15.0),
(3.0, 8.0),
(8.0, 3.0),
(5.0, 12.0),
(12.0, 5.0),
(10.0, 10.0),
]
best_x0 = [15.0, 15.0]
best_val = OBJ_INFEASIBLE
for cand in _candidates:
val = _objective(cand)
if val < best_val:
best_val = val
best_x0 = list(cand)
# Phase 1a: a fan with a narrow flow range, paid only when the pre-scan
# found nothing. The band of approaches it can serve may be thinner
# than the spacing of the lattices below, so it is solved rather than
# sampled; the point found seeds Phase 2.
if best_val >= OBJ_INFEASIBLE and self._has_narrow_fan():
search = _NarrowFanSearch(self, Q_r_iu, T0, T_a_room)
search.run()
value, x, _ = search.best()
if value < OBJ_INFEASIBLE and x is not None:
best_val, best_x0 = value, list(x)
# Phase 1b: fallback lattice, paid only when Phase 1a found nothing.
#
# The candidates above cluster at small approach temperatures, which is
# where a comfortably-met load sits. A load near the machine's ceiling is
# feasible only in a narrow band at large approaches on both sides
# (measured for a 18 kW R410A unit at 2 degC: dT_evap 13-18 K with
# dT_cond 15-20 K, a few percent of the domain). The reason is the fan:
# at a small approach the coil must move the heat with a temperature
# difference it does not have, so the airflow search runs into its rated
# ceiling and the state is rejected. Every candidate above lies outside
# that band, so without this sweep a near-ceiling hour finds no feasible
# point, falls back to HP-off and reports zero output -- understating
# capacity exactly where capacity is the quantity of interest.
# A second, finer lattice runs only if the first finds nothing: with the
# discharge-temperature limit the feasible band can shrink to a few
# kelvin between the coil's airflow limit (small approaches) and
# T_dis_max (large ones) -- 2 x 2.5 K for Daikin RXM42A at -15 degC.
# Not paid either when the least-lift point is outside the envelope
# or beyond a coil: every other approach pair asks more of both.
beyond_reach = seed_reason in self._ENVELOPE_BINDING or seed_reason == self._AIR_SIDE
for rungs in (8, 16):
if best_val < OBJ_INFEASIBLE or beyond_reach:
break
lo_b, hi_b = self.dT_approach_bounds
lattice = tuple(float(v) for v in np.linspace(lo_b, hi_b, rungs))
for de in lattice:
for dc in lattice:
val = _objective((de, dc))
if val < best_val:
best_val = val
best_x0 = [de, dc]
# Phase 2: Nelder-Mead refinement from the best candidate found above.
#
# The iteration cap is a guard against a search that does not end, not
# a tolerance: a refinement stopped by it reports ``success=False`` and,
# unless the refinement from the least-lift point ends (below), the
# point is answered as ``optimizer_failed`` with the unit off.
# Where the least-power point is the least-lift point itself -- both
# fans at their largest airflow, a corner of the feasible set -- the
# simplex contracts against the infeasible side and needs 200 to 450
# iterations to reach ``xatol``; a cap of 200 switched such a unit off
# 5e-5 of its input away from the answer (Daikin RXM42A, 40/32 degC,
# 4.49 kW with the catalogue outdoor airflow). A refinement that ends
# inside the cap is not affected by its value.
def refine(x0) -> OptimizeResult:
return minimize(
_objective,
x0=x0,
bounds=[self.dT_approach_bounds, self.dT_approach_bounds],
method="Nelder-Mead",
options={"maxiter": self._REFINE_MAXITER, "xatol": 1e-3, "fatol": 1e-1},
)
seed_val = _objective(seed) if seed is not None else OBJ_INFEASIBLE
if best_val >= OBJ_INFEASIBLE:
# No candidate above runs; the least-lift point does if anything does.
result = refine(list(seed)) if seed is not None and seed_val < OBJ_INFEASIBLE else refine(best_x0)
# Why the least-lift point does not run is why the request does not.
result["least_lift_reason"] = seed_reason
return result
result = refine(best_x0)
if seed is not None and (seed_val < float(result.fun) or not result.success):
# The refinement stopped above the least-lift point's own cost: it
# sits on a flat stretch of the objective (the discharge-temperature
# control makes the input nearly independent of the outdoor
# approach) or in another basin. Refine from the least-lift point
# too and take it when it is materially cheaper -- by more than the
# two refinements differ when they end in the same place.
#
# Or it did not end at all. Towards the least-lift corner the
# iteration count has no bound a cap can be set by (1173 for a
# 5 kW unit at 46/32 degC), and a refinement the cap stops is a
# failed search however close it got. The refinement that starts
# on the corner ends in a few dozen iterations: where it ends and
# is not materially dearer, it is the answer. "Materially" is the
# same band as above, the spread of two refinements that end in the
# same place: the finished one commonly lies 1e-5 of the input
# above where the capped one happened to stop (0.01 to 0.05 W,
# under the refinement's own ``fatol``), and held to "no dearer at
# all" it was thrown away and the unit answered as switched off.
from_seed = refine(list(seed))
cheaper = float(from_seed.fun) < (1.0 - self._SEED_GAIN) * float(result.fun)
ended_instead = (
not result.success
and from_seed.success
and float(from_seed.fun) <= (1.0 + self._SEED_GAIN) * float(result.fun)
)
if cheaper or ended_instead:
result = from_seed
return result
# =============================================================
# Part load: cycling below the minimum capacity, unmet load above the maximum
# =============================================================
def _cycling_cost_factor(self, perf: dict, Q_r_iu: float) -> float:
"""Mean electrical input of a candidate relative to its continuous input (>= 1).
1.0 unless the candidate sits on the compressor's speed floor and
cycling is modelled; there ``1 / PLF`` at the candidate's capacity
ratio (:class:`~tmhp.cycling.CyclingDegradation`).
"""
if self.cycling is None or perf.get("capacity_clamped") != CAPACITY_CLAMPED_MIN:
return 1.0
delivered = abs(float(perf.get("Q_ref_iu [W]", math.nan)))
if not (math.isfinite(delivered) and delivered > 0.0):
return 1.0
return 1.0 / self.cycling.part_load_factor(min(1.0, abs(Q_r_iu) / delivered))
#: Keys every row carries whatever path the point took, with the value on
#: a row they do not apply to (``None``: a name, NaN: a number) -- the
#: convention of the boilers' rows (:mod:`tmhp._boiler_results`). A
#: dynamic frame is the union of its rows, so without them its columns
#: depend on what the run happened to do.
_ROW_DEFAULTS: Mapping[str, Any] = {
"capacity_binding": None,
"Q_max [W]": math.nan,
"n_star [-]": math.nan,
"pr_cmp [-]": math.nan,
"eta_v [-]": math.nan,
"eta_ov [-]": math.nan,
"f_loss [-]": math.nan,
"Q_iu_sensible [W]": math.nan,
"Q_iu_latent [W]": math.nan,
"SHR_iu [-]": math.nan,
"m_dot_iu_condensate [kg/s]": math.nan,
"Q_room_sensible [W]": math.nan,
"RH_room [-]": math.nan,
"w_iu_a_in [kg/kg]": math.nan,
"w_iu_a_out [kg/kg]": math.nan,
}
def _complete_row(self, result: dict) -> dict:
"""Give a finished row the keys every row has, and its condenser dew point (in place).
Adds what the row's path did not write (:attr:`_ROW_DEFAULTS`: the
ceiling keys of a row that is not at a ceiling, the compressor keys
of an off or failed row). ``T_ref_cond_sat_v [°C]`` becomes the dew
point of the condensing pressure for a zeotropic blend
(:func:`~tmhp._boiler_results.report_condenser_dew_point`); for a pure
refrigerant nothing changes. No cycle or control quantity is touched.
"""
fill_missing(result, self._ROW_DEFAULTS)
return report_condenser_dew_point(result, self.ref)
def _report_part_load(self, result: dict, Q_r_iu: float) -> None:
"""Write the part-load keys of a solved row and average a cycling one (in place).
Every row gets ``Q_request [W]`` (signed, as asked), ``Q_unmet [W]``
(how far the delivered heat falls short of the request, >= 0),
``request_basis`` (``"total"``: the two are coil heat) and the
cycling keys of :mod:`tmhp.cycling`. A row on the compressor's speed
floor is averaged over the cycling period; one at its ceiling gains
``Q_max [W]`` and ``capacity_binding`` when the search did not already
set them.
"""
request = abs(float(Q_r_iu))
running = bool(result.get("hp_is_on", False)) and result.get("failure_reason", "none") == "none"
delivered = abs(float(result.get("Q_ref_iu [W]", 0.0))) if running else 0.0
clamp = result.get("capacity_clamped") if running else None
if clamp == CAPACITY_CLAMPED_MIN and self.cycling is not None and 0.0 < request < delivered:
state = self.cycling.state(request, delivered)
apply_cycling(
result,
state,
delivered_key="Q_ref_iu [W]",
rate_keys=self._CYCLING_RATE_KEYS,
power_keys=self._CYCLING_POWER_KEYS,
delivery_power_keys=("E_iu_fan [W]",),
)
result["cop_ref [-]"] = result["Q_ref_iu [W]"] / result["E_cmp [W]"]
if math.isfinite(float(result["cop_sys [-]"])):
result["cop_sys [-]"] = abs(result["Q_a_iu_out [W]"] - result["Q_a_iu_in [W]"]) / result["E_tot [W]"]
latent = float(result.get("Q_iu_latent [W]", 0.0))
if latent > 0.0:
# A wet coil: the room also gives up the latent heat of the condensate.
sensible = result["Q_a_iu_in [W]"] - result["Q_a_iu_out [W]"]
result["cop_sys [-]"] = (sensible + latent) / result["E_tot [W]"]
delivered = abs(float(result["Q_ref_iu [W]"]))
else:
continuous_keys(
result,
CONTINUOUS if running else OFF,
delivered if clamp == CAPACITY_CLAMPED_MIN else math.nan,
)
result["Q_request [W]"] = float(Q_r_iu)
unmet = max(request - delivered, 0.0)
result["Q_unmet [W]"] = unmet if unmet > 1e-9 * request else 0.0
# A solved row is the row of a coil duty; a request on another basis
# is the caller's to write over these three (:meth:`_solve_room_sensible`).
result[REQUEST_BASIS_KEY] = REQUEST_BASIS_TOTAL
if clamp == CAPACITY_CLAMPED_MAX:
result.setdefault("Q_max [W]", delivered)
result.setdefault("capacity_binding", "compressor")
# =============================================================
# Fans with little or no flow range
# =============================================================
def _fan_flow_ratios(self) -> tuple[float, float]:
"""Largest over smallest airflow of the indoor and the outdoor fan (1.0: constant speed)."""
def ratio(low: float, high: float) -> float:
return high / low if low > 0 else math.inf
return (
ratio(self.dV_iu_fan_a_min, self.dV_iu_fan_a_max),
ratio(self.dV_ou_fan_a_min, self.dV_ou_fan_a_max),
)
def _has_narrow_fan(self) -> bool:
"""Whether either fan's flow range can be too narrow for the grid search."""
return min(self._fan_flow_ratios()) <= NARROW_FAN_FLOW_RATIO
def _has_constant_speed_fan(self) -> bool:
"""Whether either fan runs at one airflow only (``min == max``)."""
return min(self._fan_flow_ratios()) == 1.0
def _coil_margins(self, perf: dict | None) -> tuple[float, float, float, float] | None:
"""Signed capacity margins of both coils at their fan flow limits [W].
``(indoor at smallest flow, indoor at largest flow, outdoor at smallest
flow, outdoor at largest flow)`` for a state of :meth:`_calc_state`:
coil capacity at that airflow minus the refrigerant-side duty the
cycle asks of it. A coil carries its duty at some airflow within the
limits when the first of its pair is ``<= 0`` and the second ``>= 0``.
``None`` when the cycle itself does not exist.
"""
if perf is None:
return None
if "_iu_diag" in perf:
# A coil did not close: the coil solver reports the margins.
values = tuple(
float(perf[diag].get(key, math.nan))
for diag in ("_iu_diag", "_ou_diag")
for key in ("min_flow_capacity_margin_W", "max_flow_capacity_margin_W")
)
else:
# Both coils closed, so each temperature difference follows from
# the duty and the solved airflow.
def limits(
duty: float,
flow: float,
T_in: float,
UA_rated: float,
reference: float,
n: float,
low: float,
high: float,
):
def per_kelvin(dV: float) -> float:
C_air = float(air_heat_capacity_rate(dV, T_in))
return C_air * (1.0 - math.exp(-UA_rated * (dV / reference) ** n / C_air))
if not (duty > 0.0 and flow > 0.0):
return math.nan, math.nan
dT = duty / per_kelvin(flow)
return per_kelvin(low) * dT - duty, per_kelvin(high) * dT - duty
values = (
*limits(
abs(float(perf.get("Q_ref_iu [W]", math.nan))),
float(perf.get("dV_iu_a [m3/s]", math.nan)),
float(perf.get("T_iu_a_in [°C]", math.nan)),
self.UA_iu_rated,
self.dV_iu_fan_a_ref,
self.n_iu,
self.dV_iu_fan_a_min,
self.dV_iu_fan_a_max,
),
*limits(
abs(float(perf.get("Q_ref_ou [W]", math.nan))),
float(perf.get("dV_ou_a [m3/s]", math.nan)),
float(perf.get("T_ou_a_in [°C]", math.nan)),
self._UA_ou_rated_for(perf["mode"]),
self.dV_ou_fan_a_ref,
self.n_ou,
self.dV_ou_fan_a_min,
self.dV_ou_fan_a_max,
),
)
if not all(math.isfinite(v) for v in values):
return None
return values # type: ignore[return-value]
# =============================================================
# Frost on the outdoor coil and its defrost
# =============================================================
def _frost_state(self, Q_r_iu: float, T0: float, RH_out: float | None) -> FrostState:
"""Frost correction for this request (:data:`~tmhp.defrost.NO_FROST` outside heating).
With a load-weighted frost model the coil is estimated at the load
ratio of the request (:meth:`~tmhp.defrost.DefrostModel.frost_state_at_duty`).
Without load weighting it is ``frost_state(T0, RH_out)``.
"""
if self.defrost is None or not Q_r_iu < 0:
return NO_FROST
return self.defrost.frost_state_at_duty(T0, RH_out, abs(Q_r_iu), self.hp_capacity)
def _frost_state_at_load(self, duty: float, T0: float, RH_out: float | None) -> FrostState:
"""Frost correction of the unit running the frost-free heating ``duty`` [W].
The coil is loaded by what the machine absorbs: with a load-weighted
frost model the state is that of the load ratio of ``duty``
(:meth:`~tmhp.defrost.DefrostModel.load_ratio`), the rated-load state
where the unit delivers what the coil-temperature correlation's unit
does or more. Without load weighting it is ``frost_state(T0, RH_out)``.
"""
if self.defrost is None:
return NO_FROST
ratio = self.defrost.load_ratio(duty, self.hp_capacity, T0)
return self.defrost.frost_state(T0, RH_out, load_ratio=ratio)
def _frost_state_at_ceiling(self, result: dict, frost: FrostState, request: float, T0: float) -> FrostState:
"""Frost state of a request whose frost-free solve was held at a capacity ceiling.
``frost`` is the state of the request: its load ratio is that of the
duty the request needs. A row with ``capacity_clamped == "max"`` runs
at another duty -- the compressor at its speed ceiling, or the
largest duty an envelope limit or a coil admits -- and the coil is loaded by
that duty, whatever was asked: the state is that of the ceiling duty
(``frost_state`` at its load ratio), so that the frost of a row above
the ceiling does not depend on the request.
The same state (the same object) is returned where nothing changes: a
frost model without load weighting, a row that is not held at a
ceiling, and a ceiling at the load the state was taken at
(:data:`~tmhp.defrost.LOAD_RATIO_ATOL`). It is also kept where the
ceiling's state would deliver the request or more. That cannot
happen while the mean a duty delivers rises with the duty, as it
does with the default frost model: the request's state was found
because a larger duty than the ceiling's is needed. It can where the
fixed losses come in over a small range of load (a frost-point band
of zero, or none, in air that barely frosts the rated-load coil):
the mean then falls again past that range, and a row must not
report more than was asked. Such a request keeps its own state.
"""
model = self.defrost
running = bool(result.get("hp_is_on", False)) and result.get("failure_reason", "none") == "none"
if model is None or not model.load_weighted or not running or not frost.active:
return frost
if result.get("capacity_clamped") != CAPACITY_CLAMPED_MAX:
return frost
q_ceiling = abs(float(result.get("Q_ref_iu [W]", math.nan)))
if not (math.isfinite(q_ceiling) and q_ceiling > 0.0):
return frost
ratio = model.load_ratio(q_ceiling, self.hp_capacity, T0)
if abs(ratio - frost.load_ratio) <= LOAD_RATIO_ATOL:
return frost
at_ceiling = model.frost_state(T0, frost.RH_out, load_ratio=ratio)
delivered = at_ceiling.capacity_multiplier * q_ceiling - model.defrost_load(at_ceiling, T0, self.hp_capacity)
return at_ceiling if delivered < abs(request) else frost
def _frost_state_of_running(self, result: dict, frost: FrostState, T0: float) -> FrostState:
"""Frost state of the machine a frost-free row runs, given the state of its request.
The same state, unless the frost model is load-weighted and the row
sits on the compressor's speed floor: the machine then runs at
``Q_min [W]``, more than the duty the load ratio was taken from, and
the coil is loaded by what the running machine absorbs. A request too
small to frost by its own ratio is frosted there if ``Q_min`` is.
"""
model = self.defrost
running = bool(result.get("hp_is_on", False)) and result.get("failure_reason", "none") == "none"
if model is None or not model.load_weighted or not running:
return frost
if result.get("capacity_clamped") != CAPACITY_CLAMPED_MIN:
return frost
q_min = abs(float(result.get(MIN_CAPACITY_KEY, math.nan)))
if not (math.isfinite(q_min) and q_min > 0.0):
return frost
ratio = model.load_ratio(q_min, self.hp_capacity, T0)
if ratio <= frost.load_ratio:
return frost
return model.frost_state(T0, frost.RH_out, load_ratio=ratio)
def _write_frost_free(self, result: dict, frost: FrostState) -> None:
"""Frost keys of a row the correction left alone (in place)."""
frost_free_keys(result, frost)
result[self._FROST_FREE_HEAT_KEY] = float(result.get("Q_ref_iu [W]", 0.0))
result[self._FROST_FREE_POWER_KEY] = float(result.get("E_tot [W]", 0.0))
def _average_over_frost(self, result: dict, frost: FrostState, T0: float, runtime_share: float = 1.0) -> float:
"""Turn a running frost-free row into the mean over frosting and defrost (in place).
Returns the mean delivered heat [W]: the frost-free heat times the
capacity multiplier, less what a reverse-cycle defrost takes from the
room. The indoor fan moves the delivered heat and is averaged with it.
``runtime_share`` is the fraction of the time the compressor runs: a
cycling unit defrosts only while it runs, so the heat its defrosts
take from the room is that share of the continuous-operation figure.
"""
model = self.defrost
assert model is not None
q_defrost = runtime_share * model.defrost_load(frost, T0, self.hp_capacity)
heat_frost_free = abs(float(result["Q_ref_iu [W]"]))
power_frost_free = float(result["E_tot [W]"])
delivered = max(frost.capacity_multiplier * heat_frost_free - q_defrost, 0.0)
apply_defrost(
result,
frost,
heat_factor=delivered / heat_frost_free,
Q_defrost=q_defrost,
rate_keys=self._FROST_RATE_KEYS,
outdoor_power_keys=("E_ou_fan [W]",),
delivery_power_keys=("E_iu_fan [W]",),
)
result[self._FROST_FREE_HEAT_KEY] = heat_frost_free
result[self._FROST_FREE_POWER_KEY] = power_frost_free
result["cop_ref [-]"] = result["Q_ref_iu [W]"] / result["E_cmp [W]"] if result["E_cmp [W]"] > 0 else np.nan
if math.isfinite(float(result.get("cop_sys [-]", np.nan))) and result["E_tot [W]"] > 0:
result["cop_sys [-]"] = abs(result["Q_a_iu_out [W]"] - result["Q_a_iu_in [W]"]) / result["E_tot [W]"]
return delivered
def _analyze_steady_frosted(
self,
frost: FrostState,
Q_r_iu: float,
T0: float,
T_a_room: float,
*,
postprocess: bool,
verbose: bool,
) -> dict:
"""Heating with a frosting outdoor coil: the mean over frosting and defrost.
The frost-free cycle is solved at the duty whose mean is the request,
``(|Q_r_iu| + Q_defrost) / capacity multiplier``, with everything that
applies to a frost-free solve (speed limits, cycling, the capacity
ceiling), and the row is then averaged (:func:`~tmhp.defrost.apply_defrost`).
The frost is that of the duty the machine runs: on its speed floor
and at a capacity ceiling that is not the duty the request needs
(:meth:`_frost_state_of_running`, :meth:`_frost_state_at_ceiling`).
"""
model = self.defrost
assert model is not None
request = abs(float(Q_r_iu))
q_defrost = model.defrost_load(frost, T0, self.hp_capacity)
gross = model.gross_duty(frost, Q_r_iu, q_defrost)
def frost_free(duty: float) -> dict:
self.defrost = None
try:
solved = self.analyze_steady(
Q_r_iu=-duty, T0=T0, T_a_room=T_a_room, return_dict=True, postprocess=False, verbose=verbose
)
finally:
self.defrost = model
assert isinstance(solved, dict)
return solved
result = frost_free(gross)
# On its speed floor the machine runs at Q_min, more than the duty the
# load ratio was taken from (`_frost_state_of_running`): the frost is
# that of Q_min, and the row is solved again with it.
on_floor = self._frost_state_of_running(result, frost, T0)
if on_floor is not frost:
frost = on_floor
q_defrost = model.defrost_load(frost, T0, self.hp_capacity)
gross = model.gross_duty(frost, Q_r_iu, q_defrost)
result = frost_free(gross)
# At a capacity ceiling it runs at less than that duty: the frost is
# that of the ceiling duty, whatever was asked, and the row -- the
# ceiling's operating point -- stands (`_frost_state_at_ceiling`).
frost = self._frost_state_at_ceiling(result, frost, request, T0)
q_defrost = model.defrost_load(frost, T0, self.hp_capacity)
running = bool(result.get("hp_is_on", False)) and result.get("failure_reason", "none") == "none"
# Below the minimum continuous capacity the unit cycles, and it
# defrosts only while it runs: the defrost heat loss is the runtime
# fraction of the continuous-operation figure, not all of it. The
# frost-free duty g then satisfies
# capacity multiplier * g - Q_defrost * runtime(g / Q_min) = request,
# a scalar balance (no cycle solve) once Q_min is known. Without it a
# vanishing request would still pay the whole defrost loss.
runtime_share = 1.0
cycling = self.cycling
if (
running
and cycling is not None
and q_defrost > 0.0
and result.get("capacity_clamped") == CAPACITY_CLAMPED_MIN
):
multiplier = frost.capacity_multiplier
low = request / multiplier
q_min_used = math.nan
# Q_min moves a little with the duty (the fans' optimum follows the
# cycling cost), so the balance is re-solved with the Q_min of the
# row it produced until the two agree; two passes settle it.
for _ in range(4):
q_min = float(result.get(MIN_CAPACITY_KEY, math.nan))
if not (running and math.isfinite(q_min) and q_min > 0.0):
break
if math.isfinite(q_min_used) and abs(q_min - q_min_used) <= 1e-9 * q_min:
break
def balance(duty: float, q_min: float = q_min) -> float:
return multiplier * duty - q_defrost * cycling.runtime_fraction(duty / q_min) - request
if not (low < gross and balance(low) < 0.0 < balance(gross)):
break
duty = float(brentq(balance, low, gross, xtol=1e-12 * max(gross, 1.0), rtol=1e-13))
q_min_used = q_min
runtime_share = cycling.runtime_fraction(duty / q_min)
result = frost_free(duty)
running = bool(result.get("hp_is_on", False)) and result.get("failure_reason", "none") == "none"
delivered = 0.0
if running and frost.active:
delivered = self._average_over_frost(result, frost, T0, runtime_share)
if result.get("capacity_clamped") == CAPACITY_CLAMPED_MAX and "Q_max [W]" in result:
result["Q_max [W]"] = delivered
else:
# Not running, or held at a ceiling duty that leaves the coil
# without frost: the frost-free row, as a request below it gets.
self._write_frost_free(result, frost)
if running:
delivered = abs(float(result["Q_ref_iu [W]"]))
# The request and its shortfall are the caller's, not the frost-free solve's.
if "Q_request [W]" in result:
result["Q_request [W]"] = float(Q_r_iu)
if "Q_unmet [W]" in result:
unmet = max(request - delivered, 0.0)
result["Q_unmet [W]"] = unmet if unmet > 1e-9 * request else 0.0
if postprocess:
result = self._exergy_of_row(result)
return result
# =============================================================
# Capacity envelope
# =============================================================
#: A request of this many nameplates pins the compressor at its speed ceiling.
_FLAT_OUT_FACTOR = 1.0e3
#: Relative step at which the approaches of :meth:`_largest_airflow_point` are converged.
_LEAST_LIFT_RTOL = 1e-9
#: Least gain in specific energy for which the refinement from the least-lift
#: point replaces the one from the pre-scan (the refinements stop at 0.1 W,
#: about 2e-4 of a typical input).
_SEED_GAIN = 1e-3
#: Iteration cap of the Nelder-Mead refinement in :meth:`_optimize_operation`.
_REFINE_MAXITER = 1000
#: Starting approaches of :meth:`_largest_airflow_point`, as fractions of the bounds' span.
_LEAST_LIFT_STARTS: tuple[float, ...] = (0.0, 0.1, 0.2, 0.35, 0.55)
#: The same for the least-lift point used as a starting point of the search.
_LEAST_LIFT_SEED_RTOL = 1e-6
#: Relative step from the converged approaches into the fans' flow range.
_LEAST_LIFT_INSIDE = 1e-7
#: Iterations of :meth:`_largest_airflow_point` (it contracts by 0.1 to 0.5 a step).
_LEAST_LIFT_MAX_ITER = 80
#: Smallest fraction a step of :meth:`_largest_airflow_point` is cut to before
#: the point is taken to lie outside the compressor envelope.
_LEAST_LIFT_MIN_STEP = 1.0 / 16.0
#: ``capacity_binding`` of a ceiling set by a compressor-envelope limit
#: (the names the water-heating models use).
_ENVELOPE_BINDING: Mapping[str, str] = {
PR_ABOVE_MAX: BINDING_PRESSURE_RATIO,
CONDENSING_TEMP_ABOVE_MAX: BINDING_CONDENSING,
DISCHARGE_TEMP_ABOVE_MAX: BINDING_DISCHARGE,
}
#: Why :meth:`_largest_airflow_point` has no state although the cycle exists:
#: a coil cannot carry its duty inside the approach bounds.
_AIR_SIDE = "air_side"
#: Why :meth:`_largest_airflow_point` has no state at a cooling point
#: solved with a room humidity: a coil carries more than its duty at its
#: fan's smallest airflow. On the pressure-ratio floor the condensing
#: temperature is held above the outdoor air, and a wet indoor coil's
#: latent heat grows as the evaporating temperature is lowered to make
#: room for it, so no approach pair may carry a small duty continuously.
#: Larger duties run: the request is refused from below
#: (:meth:`_smallest_continuous_operating_point`). The dry search reports
#: the same state as ``"cycle_invalid"``, as before.
_MIN_AIRFLOW = "min_airflow"
#: Why a duty has no operating point where the ordinary search of it
#: ends with the compressor flat out, short of the duty
#: (:meth:`_searched_point`). Unlike ``"compressor"`` of the least-lift
#: point -- the point of the largest capacity, above which no duty runs
#: -- this is what one search found: a larger duty can run at other
#: approaches (a 10 kW unit whose outdoor fan runs at no less than 90 %
#: of its largest flow, outdoor -10 degC, room 21 degC saturated: 17.4 to
#: 20.5 kW end so at the widest indoor approach, and 22.5 kW runs at a
#: narrower one). It names no limit of the machine
#: (:attr:`_LIMIT_REASONS`), so the ceiling search looks above it before
#: it settles; the binding of a ceiling it does settle under is the
#: compressor's (:meth:`_binding_of`).
_SEARCH_FLAT_OUT = "compressor_where_searched"
#: Reasons of :meth:`_largest_airflow_point` that name a limit of the
#: machine. Any other (``"cycle_invalid"``, or none) may be the search
#: itself not finding the point.
_LIMIT_REASONS = frozenset(
{"compressor", _AIR_SIDE, PR_ABOVE_MAX, CONDENSING_TEMP_ABOVE_MAX, DISCHARGE_TEMP_ABOVE_MAX}
)
#: Fractions of the approach range a wet ceiling search starts from when
#: a duty's least-lift point is not found from its neighbours' approaches.
_CEILING_RESTARTS: tuple[float, ...] = (0.35, 0.55, 0.8)
#: Duties tried between a ceiling the wet search could not confirm and
#: the limit above it, as fractions of the gap, from the top.
_CEILING_PROBES: tuple[float, ...] = (0.8, 0.6, 0.4, 0.2)
#: Fractions of a duty tried, from the top, when that duty has no operating point.
_CEILING_LADDER: tuple[float, ...] = (0.8, 0.6, 0.45, 0.3, 0.2, 0.12, 0.06)
#: Relative width at which the bisection for a refused request stops.
_REDUCTION_REL_TOL = 1e-3
#: Relative width the ceiling a wet cooling request is answered from is
#: searched to: the ``rel_tol`` of :meth:`max_capacity` (its default). The
#: search does not tell duties that close apart, so a request the unit
#: does not deliver that is under the ceiling by no more than this is the
#: ceiling's (:meth:`_capacity_limited_operating_point`). A search step,
#: not a physical constant.
_CEILING_REL_TOL = 1e-3
def _largest_airflow_approaches(
self, x_iu: float, x_ou: float, perf: dict, wet: tuple[float, float] | None = None
) -> tuple[float, float] | None:
"""Approaches at which each coil would carry this state's duty at its largest airflow [K].
``(indoor, outdoor)``, kept inside the approach bounds. At a fixed
airflow a coil's capacity is proportional to its temperature
difference, so the approach that closes the coil at its largest
airflow is the present one times duty over capacity there. ``perf`` is
a state of :meth:`_calc_state` whose cycle exists; its coils need not
have closed. ``None`` when a duty or a capacity is not a positive
number.
``wet`` is ``(T_a_room, T0)`` [°C] of a cooling point solved with a
room humidity. The indoor coil's capacity is then proportional to its
driving difference, sensible plus latent, and its approach is solved
from that (:meth:`_wet_coil_approach`). And the outdoor coil's
approach is taken where the cycle condenses, not where it was asked
to: on the pressure-ratio floor the condensing temperature is held
above the outdoor air by more than the approach asked for (room 35
°C, outdoor 20 °C: 21.4 K whatever approach below it is asked), so a
coil that is short there -- by 3.9 % for a 10 kW unit at 22.7 kW --
needs that difference times duty over capacity, 22.3 K. Scaling the
approach asked for instead moves it by that shortfall a step from
wherever the search started, which need not arrive (it did not at
the 0.8 % a step of the efficiency models before #223). Without
``wet`` (the dry coil, heating) the approach asked for is scaled, as
before: the dry search is left as it is (issue #168).
"""
if "_iu_diag" in perf:
pairs = []
for diag in (perf["_iu_diag"], perf["_ou_diag"]):
margin = float(diag.get("max_flow_capacity_margin_W", math.nan))
duty = float(diag.get("Q_air", math.nan)) - float(diag.get("capacity_margin_W", math.nan))
pairs.append((duty, margin))
else:
# Both coils closed, so each temperature difference follows from
# the duty and the solved airflow (as in :meth:`_coil_margins`,
# which also needs the smallest airflow -- zero for a fan that
# can stop).
def at_largest_airflow(
duty: float, flow: float, T_in: float, UA_rated: float, reference: float, n: float, high: float
):
def per_kelvin(dV: float) -> float:
C_air = float(air_heat_capacity_rate(dV, T_in))
return C_air * (1.0 - math.exp(-UA_rated * (dV / reference) ** n / C_air))
if not (duty > 0.0 and flow > 0.0):
return math.nan, math.nan
return duty, per_kelvin(high) * duty / per_kelvin(flow) - duty
pairs = [
at_largest_airflow(
abs(float(perf.get("Q_ref_iu [W]", math.nan))),
float(perf.get("dV_iu_a [m3/s]", math.nan)),
float(perf.get("T_iu_a_in [°C]", math.nan)),
self.UA_iu_rated,
self.dV_iu_fan_a_ref,
self.n_iu,
self.dV_iu_fan_a_max,
),
at_largest_airflow(
abs(float(perf.get("Q_ref_ou [W]", math.nan))),
float(perf.get("dV_ou_a [m3/s]", math.nan)),
float(perf.get("T_ou_a_in [°C]", math.nan)),
self._UA_ou_rated_for(perf["mode"]),
self.dV_ou_fan_a_ref,
self.n_ou,
self.dV_ou_fan_a_max,
),
]
lo, hi = self.dT_approach_bounds
target = []
for indoor, x, (duty, margin) in zip((True, False), (x_iu, x_ou), pairs, strict=True):
capacity = duty + margin
if not (math.isfinite(duty) and math.isfinite(capacity) and duty > 0.0 and capacity > 0.0):
return None
if indoor and wet is not None:
closing = self._wet_coil_approach(x, duty, capacity, wet[0])
else:
if wet is not None and duty > capacity:
# The condenser of a wet cooling point, short of its duty:
# its temperature difference is the one the cycle has.
# Only where the scaled approach would still lie under the
# held one, and so change nothing: any other step is the
# dry search's.
held = float(perf.get(CYCLE_KEY, perf).get("T_ref_cond_sat_l [°C]", math.nan)) - wet[1]
if x * duty / capacity < held:
x = held
closing = x * duty / capacity
target.append(min(max(closing, lo), hi))
return target[0], target[1]
def _largest_airflow_point(
self,
Q_r_iu: float,
T0: float,
T_a_room: float,
start: tuple[float, float] | None = None,
rtol: float | None = None,
) -> tuple[tuple[float, float] | None, dict | None, str | None]:
"""The operating point with both coils at their largest airflow: the least lift for a duty.
A coil carries a duty with the smallest temperature difference at its
largest airflow, so this is the point of the highest evaporating and
the lowest condensing temperature at which the unit delivers
``Q_r_iu`` -- the smallest pressure ratio, the coolest discharge and
the slowest compressor of all the approach pairs that deliver it. If
this point is outside the compressor envelope, or needs more speed
than ``rps_max``, so is every other. That makes it the test of whether
a duty is deliverable at all, the state of a unit running flat out
(a request the compressor cannot reach: speed at ``rps_max``, both
fans at full flow), and a starting point for the least-power search
that is inside the feasible set whenever there is one.
Solved as a fixed point: each approach is replaced by the one at which
its coil carries the cycle's duty at its largest airflow
(:meth:`_largest_airflow_approaches`) until both stand still. An
approach the bounds do not admit stays on the bound; on the lower one
the fan simply runs below its largest airflow. A step into a state the
cycle does not have is halved, and the point is outside the envelope
when the cut reaches :attr:`_LEAST_LIFT_MIN_STEP`.
``start`` is ``(dT_ref_evap, dT_ref_cond)`` of a neighbouring solution.
``rtol`` is the relative step at which the approaches are converged
(:attr:`_LEAST_LIFT_RTOL` by default; a search that only wants a
starting point passes a looser one).
Returns ``((dT_ref_evap, dT_ref_cond), state, reason)``. ``state`` is
the closed state of :meth:`_calc_state` (``capacity_clamped`` tells
whether the compressor met the duty) and ``reason`` is ``None``; or
``state`` is ``None`` and ``reason`` says why: the envelope limit the
cycle ran into (``"pr_above_max"``, ``"discharge_temp_above_max"``,
``"condensing_temp_above_max"``), :attr:`_AIR_SIDE` when a coil cannot
carry its duty inside the approach bounds, :attr:`_MIN_AIRFLOW` (a
cooling point solved with a room humidity only) when a coil carries
more than its duty at its smallest airflow, or ``"cycle_invalid"``.
"""
lo, hi = self.dT_approach_bounds
heating = Q_r_iu < 0
# A cooling point solved with a room humidity: the indoor coil may be wet.
wet = (T_a_room, T0) if self._coil_may_be_wet and not heating else None
rtol = self._LEAST_LIFT_RTOL if rtol is None else rtol
# Far enough inside to be clear of what the convergence left open.
step_inside = max(self._LEAST_LIFT_INSIDE, 100.0 * rtol)
def approaches(x: tuple[float, float]) -> tuple[float, float]:
return (x[1], x[0]) if heating else (x[0], x[1])
def evaluate(x: tuple[float, float]) -> dict | None:
de, dc = approaches(x)
return self._calc_state(dT_ref_evap=de, dT_ref_cond=dc, Q_r_iu=Q_r_iu, T0=T0, T_a_room=T_a_room)
def missing() -> str:
event = self._last_pr_event
return event[0] if event is not None and event[0] != "pr_below_min" else "cycle_invalid"
# Where to start: a neighbouring solution, else the smallest approaches
# (the least lift the search admits). A fluid can lack a state at one
# candidate (a flash CoolProp cannot solve), so a few larger approaches
# are tried before the cycle is taken not to exist.
starts: list[tuple[float, float]] = []
if start is not None:
starts.append(approaches((min(max(start[0], lo), hi), min(max(start[1], lo), hi))))
starts.extend((lo + f * (hi - lo),) * 2 for f in self._LEAST_LIFT_STARTS)
x: tuple[float, float] = starts[0]
perf = None
first_reason: str | None = None
for x in starts:
perf = evaluate(x)
if perf is not None:
break
first_reason = first_reason or missing()
if perf is None:
return None, None, first_reason
def step_towards(
x: tuple[float, float], target: tuple[float, float], step: float
) -> tuple[tuple[float, float], dict] | str:
"""The state a step from ``x`` towards ``target`` reaches, halved until a cycle exists; else why not."""
while True:
trial = (x[0] + step * (target[0] - x[0]), x[1] + step * (target[1] - x[1]))
trial_perf = evaluate(trial)
if trial_perf is not None:
return trial, trial_perf
reason = missing()
step *= 0.5
if step < self._LEAST_LIFT_MIN_STEP:
return reason
def at_fixed_point(x: tuple[float, float], target: tuple[float, float]) -> bool:
return all(abs(t - v) <= rtol * v for t, v in zip(target, x, strict=True))
flat_out = False
for _ in range(self._LEAST_LIFT_MAX_ITER):
flat_out = flat_out or perf.get("capacity_clamped") == CAPACITY_CLAMPED_MAX
target = self._largest_airflow_approaches(x[0], x[1], perf, wet)
if target is None:
return None, None, "cycle_invalid"
if at_fixed_point(x, target):
break
moved = step_towards(x, target, 1.0)
if isinstance(moved, str):
return None, None, moved
x, perf = moved
else:
# Out of iterations. A duty above what the compressor delivers flat
# out is one way to get here: the delivered heat, and with it each
# coil's approach, then moves with the approaches themselves, and
# the full step overshoots from one side of the fixed point to the
# other (cooling at 40/24 degC closes a fifth of the gap per pair
# of steps). Half steps contract there, so the same fixed point is
# iterated on with them. Only a state that meets the same
# criterion is a result; anything else stays what it was, a point
# the solve could not find.
if not flat_out:
return None, None, "cycle_invalid"
for _ in range(self._LEAST_LIFT_MAX_ITER):
target = self._largest_airflow_approaches(x[0], x[1], perf, wet)
if target is None:
return None, None, "cycle_invalid"
if at_fixed_point(x, target):
break
moved = step_towards(x, target, 0.5)
if isinstance(moved, str):
return None, None, moved
x, perf = moved
else:
return None, None, "cycle_invalid"
# The fixed point puts each coil exactly on its largest airflow, where
# the coil solve closes or not by the sign of a rounding error (a fan
# with its own power curve is closed with no tolerance). A step inside
# -- far below any tolerance of the cycle -- makes the closure definite.
inside = (min(x[0] * (1.0 + step_inside), hi), min(x[1] * (1.0 + step_inside), hi))
closed = evaluate(inside)
if closed is None:
return None, None, missing()
if not closed.get("converged", False):
# Short of its duty at its largest airflow: the coil is beyond its
# reach inside the approach bounds, and so is every approach pair.
# A coil that still carries too much at its *smallest* airflow is
# another matter -- the pressure-ratio floor has lifted the
# condensing temperature off the approach -- and says nothing
# about the other pairs.
diags = (closed.get("_iu_diag", {}), closed.get("_ou_diag", {}))
short = any(
not diag.get("converged", True) and float(diag.get("max_flow_capacity_margin_W", 0.0)) < 0.0
for diag in diags
)
if short:
return approaches(inside), None, self._AIR_SIDE
excess = any(
not diag.get("converged", True) and float(diag.get("min_flow_capacity_margin_W", 0.0)) > 0.0
for diag in diags
)
# Named for the wet coil only; the dry search keeps its label.
return approaches(inside), None, self._MIN_AIRFLOW if wet is not None and excess else "cycle_invalid"
return approaches(inside), closed, None
def _indoor_coil_limit(self, T_a_room: float) -> float:
"""Largest duty the indoor coil carries inside the approach bounds [W].
Its largest airflow, of room air at ``T_a_room`` [°C], at the widest
approach the search admits. The
request is the indoor coil's duty in either mode, so no larger request
has an operating point, whatever the compressor can do. The value is
a hair inside the limit (2e-7 of it), so that the coil closes there by
more than a rounding error (see :meth:`_largest_airflow_point`).
A cooling point solved with a room humidity carries the latent heat
of the wet coil at that approach as well (:meth:`_wet_coil_drive`).
"""
dV = self.dV_iu_fan_a_max
C_air = float(air_heat_capacity_rate(dV, T_a_room))
UA = self.UA_iu_rated * (dV / self.dV_iu_fan_a_ref) ** self.n_iu
drive = self.dT_approach_bounds[1]
if self._w_room is not None:
drive = self._wet_coil_drive(drive, T_a_room)
limit = C_air * (1.0 - math.exp(-UA / C_air)) * drive
return limit / (1.0 + 2.0 * self._LEAST_LIFT_INSIDE)
def _largest_deliverable_duty(
self, sign: float, q_top: float, T0: float, T_a_room: float, rel_tol: float
) -> tuple[tuple[float, float] | None, dict | None, str | None]:
"""Largest duty not above ``q_top`` whose least-lift point is an operating point.
A unit asked for more than a limit allows does not stop; its
controller holds the compressor back until the limit holds. ``q_top``
itself is tried first; otherwise a ladder of smaller duties finds one
that runs and a bisection closes on the limit above it (to
``rel_tol`` of the duty). The limits are not monotone in the duty --
at low speed the efficiency falls and the discharge runs hotter -- so
this is the boundary nearest ``q_top``, as in
:func:`~tmhp.compressor_envelope.reduce_duty_within_envelope`.
Returns ``((dT_ref_evap, dT_ref_cond), state, reason)``. ``reason`` is
``None`` when ``q_top`` is deliverable, else why the next larger duty
is not (see :meth:`_largest_airflow_point`; ``"compressor"`` for the
speed range). ``(None, None, reason)`` when no duty runs.
A cooling point solved with a room humidity is searched by
:meth:`_largest_deliverable_wet_duty`, which does not take a duty
whose point it failed to find for the ceiling. Its trial of a duty
is the least-lift point too, except for a unit with a narrow fan
range (:meth:`_has_narrow_fan`) where the fans' smallest airflows
refuse that point: the duty is then solved the ordinary way
(:meth:`_searched_point`). Where that search finds no duty -- and
some duty it tried was refused otherwise than from below -- the
point the low-load search of the condition ends on is one that
runs, and the largest duty is searched upwards from it
(:meth:`_largest_duty_above_low_load_point`). The search below --
the dry coil's, and heating's -- is as it was.
"""
def trial(q: float, start: tuple[float, float] | None = None):
x, perf, reason = self._largest_airflow_point(sign * q, T0, T_a_room, start=start)
if perf is not None and perf.get("capacity_clamped") == CAPACITY_CLAMPED_MAX:
return x, None, "compressor"
return x, perf, reason
searched: dict[float, tuple[Any, Any, Any] | None] = {}
# What the searches that ended flat out, short of their duty, delivered [W].
delivered: dict[float, float] = {}
def wet_trial(q: float, start: tuple[float, float] | None = None):
x, perf, reason = trial(q, start)
if reason == self._MIN_AIRFLOW and self._has_narrow_fan():
# Refused where both fans run at their largest airflow, which
# a fan with a narrow flow range may not be able to leave:
# the duty is solved the ordinary way, once.
if q not in searched:
found = self._searched_point(sign * q, T0, T_a_room)
if found is not None and found[1] is not None and found[2] == self._SEARCH_FLAT_OUT:
delivered[q] = abs(float(found[1]["Q_ref_iu [W]"]))
found = (found[0], None, found[2])
searched[q] = found
return searched[q] or (x, perf, reason)
return x, perf, reason
if self._coil_may_be_wet and sign > 0:
found = self._largest_deliverable_wet_duty(wet_trial, q_top, rel_tol, delivered.get)
if found[1] is None and found[2] != self._MIN_AIRFLOW:
# No duty found, and not because every duty tried is refused
# from below (nothing runs then, as far as the samples go).
# The point the low-load search of this condition ends on,
# if it has one, is a duty that runs.
above = self._largest_duty_above_low_load_point(q_top, T0, T_a_room, rel_tol, trial)
if above is not None:
return above
return found
x, perf, reason_hi = trial(q_top)
if x is not None and perf is not None:
return x, perf, None
q_hi = q_top
q_lo = 0.0
x_lo: tuple[float, float] | None = None
perf_lo: dict | None = None
for fraction in self._CEILING_LADDER:
q = fraction * q_top
x, perf, reason = trial(q)
if x is not None and perf is not None:
q_lo, x_lo, perf_lo = q, x, perf
break
q_hi, reason_hi = q, reason
if x_lo is None or perf_lo is None:
return None, None, reason_hi
while q_hi - q_lo > rel_tol * q_hi:
mid = 0.5 * (q_lo + q_hi)
x, perf, reason = trial(mid, start=x_lo)
if x is not None and perf is not None:
q_lo, x_lo, perf_lo = mid, x, perf
else:
q_hi, reason_hi = mid, reason
return x_lo, perf_lo, reason_hi
def _low_load_point(self, T0: float, T_a_room: float) -> tuple[tuple[float, float], dict] | None:
"""The continuous operating point the smallest request of the low-load ladder leads to (wet cooling).
A point of the condition, not of a request: the smallest rung of
:attr:`_FLOOR_LADDER` (5 % of the nameplate) is solved the way
:meth:`analyze_steady` solves a request. Where it runs -- as asked,
or on the compressor's speed floor, delivering more -- the point is
that state; where the fans' smallest airflows refuse it
(:attr:`_MIN_AIRFLOW`) it is the smallest continuous duty the climb
from it finds (:meth:`_climb_to_continuous_duty`). It is the same
whichever request, and whichever search, asks for it, which is what
lets another search of the condition use it as a candidate: the
ceiling search, where it found no duty
(:meth:`_largest_duty_above_low_load_point`).
Returns ``((dT_ref_evap, dT_ref_cond), state)``; the state delivers
its own ``Q_ref_iu [W]`` in continuous operation at those approaches.
``None`` when the rung neither runs nor is refused from below, or no
larger duty is found to run.
"""
memo, key = self._wet_points, self._wet_point_key("low_load", T0, T_a_room)
if memo is not None and key in memo:
known = memo[key]
return None if known is None else (known[0], dict(known[1]))
point: tuple[tuple[float, float], dict] | None = None
q0 = self._FLOOR_LADDER[0] * self.hp_capacity
with contextlib.suppress(Exception):
opt = self._optimize_operation(Q_r_iu=q0, T0=T0, T_a_room=T_a_room)
if bool(getattr(opt, "success", False)) and float(opt.fun) < OBJ_CAPACITY_LIMITED:
x = (float(opt.x[0]), float(opt.x[1]))
state = self._calc_state(dT_ref_evap=x[0], dT_ref_cond=x[1], Q_r_iu=q0, T0=T0, T_a_room=T_a_room)
running = state is not None and state.get("converged", False)
if running and state is not None and state.get("capacity_clamped") != CAPACITY_CLAMPED_MAX:
point = (x, state)
elif getattr(opt, "least_lift_reason", None) == self._MIN_AIRFLOW:
point = self._climb_to_continuous_duty(q0, T0, T_a_room)[0]
if memo is not None:
memo[key] = None if point is None else (point[0], dict(point[1]))
return point
def _largest_duty_above_low_load_point(
self,
q_top: float,
T0: float,
T_a_room: float,
rel_tol: float,
least_lift: Callable[[float], tuple[Any, Any, Any]],
) -> tuple[tuple[float, float], dict, str | None] | None:
"""The ceiling of a wet cooling condition, searched upwards from its low-load point.
Used where the ceiling search found no duty that runs
(:meth:`_largest_deliverable_wet_duty`). That search samples the
duty from the top; the low-load search samples it from the bottom,
with the ordinary search at every trial, and can end on a duty that
runs where the other found none -- both fans held at one flow on
the pressure-ratio floor leave a window of duties a fraction of a
percent wide (4 kW unit, outdoor 8 degC, room 35 degC saturated:
14.31 to 14.35 kW). That point (:meth:`_low_load_point`) is a
duty that runs, so the ceiling is not below it: the duties between
it and ``q_top`` are bisected with the ordinary search
(:meth:`_searched_point`) to ``rel_tol``, as the dry search bisects
above a rung that runs.
Returns what :meth:`_largest_deliverable_duty` returns for a duty
that runs -- the approaches, the state and why the next larger duty
tried has no operating point: :attr:`_SEARCH_FLAT_OUT` where its
search ended flat out, else the verdict of its least-lift point
(``least_lift(q)``, the caller's trial), ``"cycle_invalid"`` when
that names nothing. ``None`` when the condition has no low-load
point, or one above ``q_top``.
"""
point = self._low_load_point(T0, T_a_room)
if point is None:
return None
x_lo, perf_lo = point
q_lo = abs(float(perf_lo["Q_ref_iu [W]"]))
if not (math.isfinite(q_lo) and 0.0 < q_lo <= q_top):
return None
q_hi, reason_hi = q_top, None
while q_hi - q_lo > rel_tol * q_hi:
mid = 0.5 * (q_lo + q_hi)
found = self._searched_point(mid, T0, T_a_room)
if found is not None and found[1] is not None and found[2] is None:
q_lo, x_lo, perf_lo = mid, found[0], found[1]
else:
q_hi, reason_hi = mid, None if found is None else found[2]
if reason_hi is None:
reason_hi = least_lift(q_hi)[2] or "cycle_invalid"
return x_lo, perf_lo, reason_hi
def _flat_out_point_on_the_floor(
self, x: tuple[float, float], state: dict, T0: float, T_a_room: float
) -> tuple[tuple[float, float], dict]:
"""The flat-out state of a wet cooling condition with a fan held at one flow, on the pressure-ratio floor.
The flat-out ceiling is the least-lift point of a request the
compressor cannot reach (:meth:`max_capacity`). On the
pressure-ratio floor the condensing temperature is held above the
outdoor air whatever approach is asked for, and the outdoor approach
of the least-lift point ends on its lower bound. The approach asked
for still sets the subcooling the cycle is solved with (it is cut to
the approach less ``dT_hx_min``), so at a wider one the same
compressor speed delivers more -- 1 to 1.5 % for the default units.
With a fan held at one flow the ordinary search of a request
(:class:`_NarrowFanSearch`) finds those states, and a request
between the two is delivered in full (10 kW unit with its indoor fan
held, outdoor -10 degC, room 35 degC saturated: 34.99 kW at the
least-lift point, 35.38 kW delivered on request). The ceiling is
therefore what that search delivers flat out, where it is more and
the state is one :meth:`_calc_state` reproduces as a request
(:meth:`_delivering_state`).
Only on the floor: off it the approach asked for is the condensing
temperature, and the least-lift point is the state of the largest
capacity (the search finds the same state there, or a smaller one).
Only for a fan held at one flow: with fans that modulate the
ordinary search of a request above the ceiling returns the
least-lift point itself (:meth:`_optimize_operation`, phase 1), so
no request is delivered above it.
Returns ``(x, state)`` unchanged where none of this applies.
"""
on_the_floor = float(state.get("pr_cmp [-]", math.inf)) <= self.PR_cycle_min * (1.0 + 1e-9)
if not (on_the_floor and self._has_constant_speed_fan()):
return x, state
request = self._FLAT_OUT_FACTOR * self.hp_capacity
found = self._searched_point(request, T0, T_a_room)
if found is None or found[1] is None or found[2] != self._SEARCH_FLAT_OUT:
return x, state
larger = abs(float(found[1]["Q_ref_iu [W]"]))
if not larger > abs(float(state["Q_ref_iu [W]"])):
return x, state
if self._delivering_state(found[0], larger, T0, T_a_room) is None:
return x, state
return found[0], found[1]
def _delivering_state(self, x: tuple[float, float], Q_r_iu: float, T0: float, T_a_room: float) -> dict | None:
"""The state at approaches ``x`` when ``Q_r_iu`` is asked of it, if it delivers exactly that.
A point another search hands over is used only when
:meth:`_calc_state` reproduces it: both coils close, the delivered
heat is the duty and the cycle's work is the difference of the two
coils' heat, each within 1e-9 of the duty. ``None`` otherwise.
"""
duty = abs(float(Q_r_iu))
state = self._calc_state(dT_ref_evap=x[0], dT_ref_cond=x[1], Q_r_iu=Q_r_iu, T0=T0, T_a_room=T_a_room)
if state is None or not state.get("converged", False):
return None
delivered = float(state["Q_ref_iu [W]"])
other = float(state["Q_ref_ou [W]"])
# the gas's enthalpy rise: the compressor input less its shell loss
work = float(state["E_cmp [W]"]) - float(state["Q_cmp_loss [W]"])
cycle_work = (other - delivered) if Q_r_iu > 0 else (delivered - other)
residuals = (abs(delivered - duty), abs(cycle_work - work))
if not all(math.isfinite(value) and value <= 1e-9 * duty for value in residuals):
return None
return state
def _searched_point(
self, Q_r_iu: float, T0: float, T_a_room: float
) -> tuple[tuple[float, float], dict | None, str | None] | None:
"""A duty whose least-lift point the fans' smallest airflows refuse, solved the ordinary way.
The least-lift point puts both coils at their largest airflow. On
the pressure-ratio floor the condensing temperature is held above
the approach asked for, and a coil whose fan has little or no range
below its largest airflow then carries more than its duty there
(:attr:`_MIN_AIRFLOW`). That refuses the least-lift point, not the
duty: the unit carries it with the other coil's approach moved -- a
lower evaporating temperature takes the cycle off the floor -- and
that point is what the ordinary search finds
(:meth:`_optimize_operation`, which solves both coils' flow limits
together for such fans: :class:`_NarrowFanSearch`). Default 4 kW
unit with its outdoor fan held at its largest flow, outdoor 15 degC,
room 35 degC saturated: the least-lift point exists between 12.2 and
13.7 kW only, while every duty from 3.93 kW up runs.
Returns what a trial of the ceiling search returns
(:meth:`_largest_deliverable_duty`): the approaches and the state
that delivers ``Q_r_iu`` [W], with no reason; or the approaches,
the state and :attr:`_SEARCH_FLAT_OUT` when the search ends with the
compressor flat out, short of the duty -- which is not a limit of
the machine, as a flat-out least-lift point is; the state says what
the unit delivers there. ``None`` when it finds no point, or one
that delivers more than the duty (the compressor's speed floor) --
the least-lift verdict then stands.
"""
with contextlib.suppress(Exception):
opt = self._optimize_operation(Q_r_iu=Q_r_iu, T0=T0, T_a_room=T_a_room)
if not (bool(getattr(opt, "success", False)) and float(opt.fun) < OBJ_INFEASIBLE):
return None
x = (float(opt.x[0]), float(opt.x[1]))
state = self._calc_state(dT_ref_evap=x[0], dT_ref_cond=x[1], Q_r_iu=Q_r_iu, T0=T0, T_a_room=T_a_room)
if state is None or not state.get("converged", False):
return None
if state.get("capacity_clamped") == CAPACITY_CLAMPED_MAX:
return x, state, self._SEARCH_FLAT_OUT
if state.get("capacity_clamped") is None:
return x, state, None
return None
def _largest_deliverable_wet_duty(
self,
trial: Callable[..., tuple[Any, Any, Any]],
q_top: float,
rel_tol: float,
lead: Callable[[float], float | None] | None = None,
) -> tuple[tuple[float, float] | None, dict | None, str | None]:
""":meth:`_largest_deliverable_duty` for a cooling point solved with a room humidity.
The ladder and the bisection are those of the dry search, with one
difference: a duty is taken for refused only when its least-lift
point names a limit of the machine (:attr:`_LIMIT_REASONS`: the
speed range, the envelope, a coil at its largest airflow and widest
approach). ``"cycle_invalid"`` names none. It is what a condensing
temperature at the critical point gives, and also what the
fixed-point iteration gives when it does not arrive -- and with a wet
coil, whose capacity is not proportional to its approach, there are
more ways not to arrive. Taken for the ceiling, such a duty hides
everything above it that runs (10 kW unit, outdoor 20 degC, room 35
degC saturated, on the efficiency models before #223: 22.6 kW
reported, 29.7 kW delivered on request).
So a trial that names no limit is repeated from other starting
approaches -- those of the neighbouring duties already solved, then
fractions of the approach range (:attr:`_CEILING_RESTARTS`). A rung of
the ladder that still names none is passed over without lowering the
upper end of the bracket. If the bisection then ends below a duty
that names no limit, the loads between it and the limit above are
tried (:attr:`_CEILING_PROBES`), and the bisection is repeated from
the first that runs. What is left unexplained after that is reported
as it is, ``"cycle_invalid"``.
A rung may also be refused from below, by the fans' smallest
airflows (:attr:`_MIN_AIRFLOW`), which is no limit above it either.
And a trial may end with the compressor flat out where the duty was
searched the ordinary way (:attr:`_SEARCH_FLAT_OUT`): that names no
limit either, and is looked above like a duty that was not found.
Where no rung runs, the gaps between the rungs are looked into from
the top -- bisected above a duty refused from below, tried at
:attr:`_CEILING_PROBES` where the lower rung gives no side, and
above a bisection step that names no limit -- and the search goes
on from the first duty that runs.
The search samples the duty; it does not enumerate it. A band of
duties narrower than ``rel_tol``, or one narrower than a fifth of a
gap between two refused duties of which neither is refused from
below, can be missed, and the ceiling is then the top of the
highest band that was found (0 W when none was).
``lead(q)``, when given, is the duty a refused trial of ``q`` points
to, or ``None``: what the ordinary search of ``q`` delivered when it
ended with the compressor flat out. The duties that run can be two
bands with a gap between them in which the compressor is flat out at
the widest indoor approach (a 7 kW unit whose outdoor fan runs at no
less than 85 % of its largest flow, outdoor -10 degC, room 21 degC
saturated: 9.1 to 12.2 kW and 14.3 to 16.2 kW), and the ladder finds
the lower one. The search that ends short of the top is flat out in
the upper one -- 16.16 kW there -- so that duty, a hair under it, is
tried as well where it lies above what the search found, and the
bisection is repeated from it. It is one more duty to try: the
ceiling is never below the one found without it.
``trial(q, start)`` is the caller's: the least-lift point of the duty
``q``, with a flat-out compressor read as the reason ``"compressor"``.
"""
lo_b, hi_b = self.dT_approach_bounds
restarts = [(lo_b + f * (hi_b - lo_b),) * 2 for f in self._CEILING_RESTARTS]
def settled(q: float, *starts: tuple[float, float] | None):
"""``trial`` from the first start; a refusal that names no limit retried from the others."""
first, *others = starts or (None,)
x, perf, reason = trial(q, first)
if perf is not None or reason in self._LIMIT_REASONS:
return x, perf, reason
for start in (*others, *restarts):
if start is None:
continue
again = trial(q, start)
if again[1] is not None or again[2] in self._LIMIT_REASONS:
return again
return x, perf, reason
x, perf, reason_hi = settled(q_top)
if x is not None and perf is not None:
return x, perf, None
# ``q_limit``: the smallest duty known to be refused by a limit.
# ``x_limit``: the approaches its search ended on, a start for the duties below.
limited = reason_hi in self._LIMIT_REASONS
q_limit, reason_limit, x_limit = q_top, reason_hi, x if limited else None
q_lo, x_lo, perf_lo = 0.0, None, None
last_reason = reason_hi
# The duties refused so far, from the top, each with why.
refused: list[tuple[float, Any]] = [(q_top, reason_hi)]
for fraction in self._CEILING_LADDER:
q = fraction * q_top
x, perf, reason = settled(q, x_limit)
if x is not None and perf is not None:
q_lo, x_lo, perf_lo = q, x, perf
break
last_reason = reason
if reason in self._LIMIT_REASONS:
q_limit, reason_limit, x_limit, limited = q, reason, x, True
refused.append((q, reason))
def running_between(q_under: float, q_over: float, sided: bool, look_above: bool = True):
"""A duty found to run between two refused duties, as ``(q, x, state)``; ``None`` when none is.
``sided``: the lower duty is refused from below, so the gap is
bisected by which side refuses the trial. Otherwise it is tried
at :attr:`_CEILING_PROBES`, from the top, until a duty runs or
is refused from below. A bisection step that names no limit --
the search ended short of it, or did not find it -- does not say
the band is under it: the gap above it is tried the same way
(once: ``look_above``) before the bisection goes on below.
"""
nonlocal q_limit, reason_limit, x_limit, limited, last_reason
probes = [] if sided else [q_under + f * (q_over - q_under) for f in self._CEILING_PROBES]
while probes or (sided and q_over - q_under > rel_tol * q_over):
q = 0.5 * (q_under + q_over) if sided else probes.pop(0)
x, perf, reason = settled(q, x_limit)
if x is not None and perf is not None:
return q, x, perf
if reason == self._MIN_AIRFLOW:
q_under, sided, probes = q, True, []
continue
last_reason = reason
if reason in self._LIMIT_REASONS:
if q < q_limit:
q_limit, reason_limit, x_limit, limited = q, reason, x, True
elif sided and look_above:
found = running_between(q, q_over, False, look_above=False)
if found is not None:
return found
q_over = q
return None
if perf_lo is None:
# No rung runs. The duties that run, if any, are a band no rung
# fell in (both fans at one airflow, outdoor 15 degC, room 35
# degC saturated: 12.2 to 13.7 kW of a 4 kW unit), so each gap
# between two rungs under the smallest duty a limit refuses is
# looked into, from the top. Two rungs refused from below (the
# fans' smallest airflows) end the sweep: nothing under them
# runs.
for (q_over, reason_over), (q_under, reason_under) in zip(refused, refused[1:], strict=False):
if q_over > q_limit:
continue
if reason_under == self._MIN_AIRFLOW and reason_over == self._MIN_AIRFLOW:
break
found = running_between(q_under, q_over, reason_under == self._MIN_AIRFLOW)
if found is not None:
q_lo, x_lo, perf_lo = found
break
def bisect(q_lo: float, x_lo: Any, perf_lo: Any, q_hi: float, reason_hi: Any):
while q_hi - q_lo > rel_tol * q_hi:
mid = 0.5 * (q_lo + q_hi)
x, perf, reason = settled(mid, x_lo, x_limit)
if x is not None and perf is not None:
q_lo, x_lo, perf_lo = mid, x, perf
else:
q_hi, reason_hi = mid, reason
return q_lo, x_lo, perf_lo, q_hi, reason_hi
def climb(q_lo: float, x_lo: Any, perf_lo: Any):
"""From a duty that runs to the largest found above it: ``(q, x, state, why the next is refused)``."""
q_hi, reason_hi = q_limit, reason_limit
for _ in range(len(self._CEILING_PROBES)):
q_lo, x_lo, perf_lo, q_hi, reason_hi = bisect(q_lo, x_lo, perf_lo, q_hi, reason_hi)
if reason_hi in self._LIMIT_REASONS or not q_limit > q_hi:
break
# The bracket closed on a duty that names no limit: look above it.
for fraction in self._CEILING_PROBES:
q = q_hi + fraction * (q_limit - q_hi)
x, perf, reason = settled(q, x_lo, x_limit)
if x is not None and perf is not None:
q_lo, x_lo, perf_lo = q, x, perf
q_hi, reason_hi = q_limit, reason_limit
break
else:
break
return q_lo, x_lo, perf_lo, reason_hi
if x_lo is not None and perf_lo is not None:
q_lo, x_lo, perf_lo, reason_hi = climb(q_lo, x_lo, perf_lo)
# What the search of the top delivered, flat out: one more duty to
# try, a hair under it, where it lies above what was found. It adds
# to the search above and replaces none of it.
q_lead = lead(q_top) if lead is not None else None
if q_lead is not None and q_lo < q_lead * (1.0 - rel_tol) < q_limit:
q = q_lead * (1.0 - rel_tol)
x, perf, reason = settled(q, x_lo, x_limit)
if x is not None and perf is not None:
q_lo, x_lo, perf_lo, reason_hi = climb(q, x, perf)
if x_lo is None or perf_lo is None:
return None, None, reason_limit if limited else last_reason
return x_lo, perf_lo, reason_hi
def _binding_of(self, reason: str | None) -> str:
"""``capacity_binding`` for the reason the next larger duty has no operating point.
``"cycle_invalid"`` -- the next larger duty has no cycle the model can
represent, in practice a condensing temperature at the critical point
-- is not a binding a unit runs on: :meth:`analyze_steady` does not
settle there (as the water-heating models do not; see
:mod:`tmhp.compressor_envelope`), and only :meth:`max_capacity`
reports it.
"""
if reason in ("compressor", self._SEARCH_FLAT_OUT):
return "compressor"
if reason == self._AIR_SIDE:
return BINDING_CYCLE
return self._ENVELOPE_BINDING.get(reason or "", "cycle_invalid")
[docs]
def max_capacity(
self,
T0: float,
T_a_room: float | None = None,
*,
mode: str = "heating",
grid_points: int | None = None,
rel_tol: float = 1e-3,
RH_out: float | None = None,
RH_room: float | None = None,
) -> dict:
"""Largest duty the unit can actually deliver at this condition.
Nameplate capacity is a label attached to one rating point, not a
ceiling. A real unit delivers more than nameplate when the outdoor air
is mild and less when it is severe, because the limit is set by
whichever of the compressor speed range, the compressor envelope and
the air-side heat exchangers binds first. Clipping a load schedule at
nameplate therefore errs in both directions at once. This returns the
ceiling the model itself implies, so a schedule can be clipped against
the machine rather than against its label and the shortfall reported as
a result.
The ceiling is the unit running flat out: the compressor at
``rps_max`` and both fans at their largest airflow, which is the least
lift at which that speed's duty is delivered
(:meth:`_largest_airflow_point`). Where that point is outside the
compressor envelope (pressure ratio, discharge temperature even under
its control, condensing temperature) or beyond what a coil carries
inside the approach bounds, the ceiling is the largest duty whose
least-lift point is an operating point -- a unit's controller holds
the compressor back to it -- found by bisection on the duty.
The ceiling is not the largest heat any approach pair delivers at
``rps_max``. An adiabatic compressor turns its losses into delivered
heat, so starving the outdoor coil of air (a lower evaporating
pressure, a higher pressure ratio, a lower overall efficiency) can
raise the heating duty a little while the COP collapses; no unit runs
its fans that way.
.. warning::
The answer is only as trustworthy as the compressor correlations at
the speeds it reaches. Those correlations are fits, and a validation
carried out at part load does not cover the top of the speed range.
Check that the returned ``cop_sys [-]`` is credible before using the
ceiling, and consider lowering ``rps_max`` to the highest speed the
validation actually reached.
Parameters
----------
T0 : float
Outdoor air temperature [°C].
T_a_room : float | None
Room air temperature [°C]. Uses the constructor default if None.
mode : str
``"heating"`` or ``"cooling"``.
grid_points : int | None
Unused. The ceiling was once swept on a grid of approach
temperatures of this resolution; it is solved now. Accepted so
that existing calls keep running.
rel_tol : float
Relative width at which the bisection on the duty stops when the
unit cannot run flat out. A flat-out ceiling and one set by the
indoor coil are exact.
RH_out : float | None
Outdoor relative humidity as a fraction (0-1) for the frost
correction in heating. None: the frost model's default.
RH_room : float | None
Room relative humidity as a fraction (0-1), for the wet indoor
coil in cooling (see :meth:`analyze_steady`). None: the dry coil.
Not read in heating, whatever is given.
Returns
-------
dict
``Q_max [W]`` (0.0 when the unit cannot run at all here), the
approach temperatures there, the electrical input and system COP at
that point, and ``binding`` naming what stopped it:
``"compressor"`` (the speed range), ``"pressure_ratio"``,
``"discharge_temperature"`` or ``"condensing_temperature"`` (the
compressor envelope: the next larger duty exceeds ``PR_cycle_max``,
``T_dis_max`` under its control, or ``T_cond_max``),
``"cycle"`` (a coil at its largest airflow and the widest
approach the search admits), ``"cycle_invalid"`` (the next larger
duty has no cycle the model can represent -- a condensing
temperature at the critical point; :meth:`analyze_steady` does not
settle on that edge) and ``"infeasible"`` when no duty has an
operating point.
In heating with a frosting outdoor coil the ceiling, the input and
the COP are the mean over frosting and defrost -- the heat is
what :meth:`analyze_steady` delivers there (where a coil sets
the ceiling it goes on to pick the point of least input at that
duty, a little below the input reported here), with the frost of
the coil at the ceiling duty: a ceiling below what the
coil-temperature correlation's unit delivers at ``T0`` (an
envelope limit, a small speed range) is a part-loaded coil, with
less frost than the rated-load correction or none -- and
``Q_max_frost_free [W]`` is the frost-free ceiling they come from
(``defrost_fraction [-]`` > 0). Otherwise the two are equal.
``Q_max [W]`` is the refrigerant-side coil heat, as
``Q_ref_iu [W]`` is: with ``RH_room`` in cooling it is sensible
plus latent, and ``SHR_iu [-]`` is the sensible share of it there
(1 for a dry coil and in heating, NaN when the unit cannot run).
``Q_room_sensible_at_Q_max [W]`` is the room's net sensible heat
at that ceiling: ``Q_room_sensible [W]`` of the state the unit
runs at there -- the coil's sensible heat less the indoor fan's
heat in cooling, plus it in heating, under frost the mean over
frosting and defrost -- and 0.0 when the unit cannot run. It is
what a request made with ``request_basis="sensible"``
gets when the search arrives at the ceiling
(:meth:`analyze_steady`). It is the net sensible heat at the
largest coil duty, not a maximum over the coil duties: the two
are the same wherever the net sensible heat rises with the coil
duty up to the ceiling, which it did at every one of 444
conditions of default units of 2.5 to 10 kW (dry and wet
cooling, heating). A unit with a fan held at one flow can take
more sensible heat at a smaller coil duty (4 kW unit, outdoor
fan held, 15 degC outdoor, saturated 35 degC room: 2,705 W at
the 13.7 kW ceiling, 2,773 W at 13.0 kW; one of 312 conditions
of six fan-constrained units), so it is not to be read as the
largest sensible load such a unit can meet.
Notes
-----
With ``RH_room`` in cooling the ceiling is searched together with the
other two searches of the condition, and each takes the others'
verified operating points for candidates: where the search on the
duty finds none, the duty the low-load search ends on (the one
:meth:`analyze_steady` cycles a small request at) runs, and the
ceiling is searched upwards from it; and a flat-out ceiling of a
unit with a fan held at one flow, on the pressure-ratio floor, is
what the ordinary search delivers there. The answer is the same
whatever was solved before. A request for the ``Q_max [W]``
returned, with the same ``RH_room``, is delivered that duty with
nothing unmet (:meth:`analyze_steady`): by the search of the
request where it arrives there, else at this state
(``capacity_clamped == "max"``).
A fan held at one flow (``dV_*_fan_a_min == dV_*_fan_a_max``) leaves
its coil one approach temperature per duty. On the pressure-ratio
floor, with both fans held, the duties that run in continuous
operation can then be a window a fraction of a percent wide (4 kW
unit, 8 degC outdoor, room 35 degC saturated: 14.31 to 14.35 kW),
or none. The searches sample the duty -- a ladder and a
bisection, to ``rel_tol`` here -- and can miss a window narrower
than the spacing of their samples. The result is then
``Q_max [W] == 0`` with ``binding == "infeasible"`` (and
:meth:`analyze_steady` answers a request with the unit off,
``failure_reason == "hx_not_converged"``) although a duty inside the
window would run. Give the fan a flow range, or request a duty
inside the window.
"""
if mode not in ("heating", "cooling"):
raise ValueError(f"mode must be 'heating' or 'cooling', got {mode!r}")
if not (math.isfinite(rel_tol) and rel_tol > 0.0):
raise ValueError(f"rel_tol must be a positive number, got {rel_tol!r}")
if T_a_room is None:
T_a_room = self.T_a_room
# Read, and checked, for the cooling ceiling only.
RH_room = _check_room_humidity(RH_room) if RH_room is not None and mode == "cooling" else None
with self._solving_with_room_humidity(RH_room, T_a_room, cooling=mode == "cooling"):
return self._solve_max_capacity(T0, T_a_room, mode, rel_tol, RH_out)
def _solve_max_capacity(
self,
T0: float,
T_a_room: float,
mode: str,
rel_tol: float,
RH_out: float | None,
*,
flat_out_only: bool = False,
) -> dict:
""":meth:`max_capacity` for checked arguments, with the room humidity of the point already set.
``flat_out_only`` answers with the flat-out ceiling or with none
(``binding == "infeasible"``): the search on the duty that follows
where the unit cannot run flat out is left out.
"""
empty = {
"Q_max [W]": 0.0,
"dT_ref_evap [K]": float("nan"),
"dT_ref_cond [K]": float("nan"),
"E_tot [W]": float("nan"),
"cop_sys [-]": float("nan"),
"binding": "infeasible",
"mode": mode,
"T0 [°C]": T0,
"T_a_room [°C]": T_a_room,
"Q_max_frost_free [W]": 0.0,
"defrost_fraction [-]": 0.0,
"SHR_iu [-]": float("nan"),
"Q_room_sensible_at_Q_max [W]": 0.0,
}
sign = 1.0 if mode == "cooling" else -1.0
wet = self._coil_may_be_wet and sign > 0
# The ceiling of a wet condition is searched once while a solve or a
# run is in progress: it is the same for every request of it.
# (Not the flat-out answer alone, which is one solve and not the ceiling where it is none.)
memo = self._wet_points if wet and not flat_out_only else None
key = self._wet_point_key("ceiling", T0, T_a_room, float(rel_tol))
if memo is not None and key in memo:
return dict(memo[key])
ceiling = self._search_max_capacity(T0, T_a_room, mode, rel_tol, RH_out, empty, flat_out_only)
if memo is not None:
memo[key] = dict(ceiling)
return ceiling
def _search_max_capacity(
self,
T0: float,
T_a_room: float,
mode: str,
rel_tol: float,
RH_out: float | None,
empty: dict,
flat_out_only: bool = False,
) -> dict:
"""The search of :meth:`_solve_max_capacity`; ``empty`` is its answer where no duty runs."""
sign = 1.0 if mode == "cooling" else -1.0
binding = "compressor"
lo_x, lo_perf, _ = self._largest_airflow_point(sign * self._FLAT_OUT_FACTOR * self.hp_capacity, T0, T_a_room)
if lo_x is not None and lo_perf is not None and self._coil_may_be_wet and sign > 0:
# Flat out with a wet coil: on the pressure-ratio floor a fan held
# at one flow delivers more than at the least-lift point.
lo_x, lo_perf = self._flat_out_point_on_the_floor(lo_x, lo_perf, T0, T_a_room)
if (lo_x is None or lo_perf is None) and flat_out_only:
return empty
if lo_x is None or lo_perf is None:
# Not flat out: no request above the indoor coil's own limit has an
# operating point, so the ceiling is that limit (known exactly) or
# the largest duty below it the envelope admits.
lo_x, lo_perf, reason = self._largest_deliverable_duty(
sign, self._indoor_coil_limit(T_a_room), T0, T_a_room, rel_tol
)
# The limit itself runs: the indoor coil at its largest airflow
# and the widest approach is what stops the unit.
binding = BINDING_CYCLE if reason is None else self._binding_of(reason)
if lo_x is None or lo_perf is None:
return empty
lo_q = abs(float(lo_perf["Q_ref_iu [W]"]))
ceiling = {
"Q_max [W]": lo_q,
"dT_ref_evap [K]": lo_x[0],
"dT_ref_cond [K]": lo_x[1],
"E_tot [W]": float(lo_perf.get("E_tot [W]", float("nan"))),
"cop_sys [-]": float(lo_perf.get("cop_sys [-]", float("nan"))),
"binding": binding,
"mode": mode,
"T0 [°C]": T0,
"T_a_room [°C]": T_a_room,
"Q_max_frost_free [W]": lo_q,
"defrost_fraction [-]": 0.0,
"SHR_iu [-]": float(lo_perf.get("SHR_iu [-]", float("nan"))),
# The same ceiling as the room's net sensible heat: the coil's
# sensible heat there with the indoor fan's heat counted.
"Q_room_sensible_at_Q_max [W]": float(lo_perf.get("Q_room_sensible [W]", float("nan"))),
}
# The frost of the ceiling duty: the coil is loaded by what the unit
# absorbs flat out, the rated-load state where that is what the
# coil-temperature correlation's unit delivers or more.
frost = self._frost_state_at_load(lo_q, T0, RH_out) if mode == "heating" else NO_FROST
if frost.active:
# The ceiling analyze_steady delivers: the mean over frosting and defrost.
mean = dict(lo_perf)
ceiling["Q_max [W]"] = self._average_over_frost(mean, frost, T0)
ceiling["E_tot [W]"] = float(mean["E_tot [W]"])
ceiling["cop_sys [-]"] = float(mean["cop_sys [-]"])
ceiling["defrost_fraction [-]"] = frost.defrost_fraction
ceiling["Q_room_sensible_at_Q_max [W]"] = float(mean["Q_room_sensible [W]"])
return ceiling
def _least_power_at_ceiling(self, result: dict, Q_r_iu: float, T0: float, T_a_room: float) -> dict:
"""Least-power operating point at the ceiling duty, when a coil sets the ceiling.
The ceiling comes from the least-lift point, where both fans run at
their largest airflow. Where a coil sets the ceiling the compressor is
clear of its own limits and the other fan has a range to choose from:
the indoor coil at its largest airflow and widest approach fixes the
duty, while the outdoor fan can still trade its own power against the
compressor's (default 4 kW unit at 7 degC: 1.3 % of the input). The
ceiling duty is therefore solved the ordinary way, so that the row is
the one a request arriving at the ceiling from below ends at. At the
speed ceiling or on an envelope limit the least-lift point is the only
one that delivers the duty, and this is not called.
"""
delivered = abs(float(result.get("Q_ref_iu [W]", 0.0)))
power = float(result.get("E_tot [W]", math.nan))
if not (delivered > 0.0 and math.isfinite(power) and power > 0.0):
return result
duty = math.copysign(delivered, Q_r_iu)
with contextlib.suppress(Exception):
opt = self._optimize_operation(Q_r_iu=duty, T0=T0, T_a_room=T_a_room)
if not (bool(getattr(opt, "success", False)) and float(opt.fun) < OBJ_CAPACITY_LIMITED):
return result
state = self._calc_state(dT_ref_evap=opt.x[0], dT_ref_cond=opt.x[1], Q_r_iu=duty, T0=T0, T_a_room=T_a_room)
if state is None or not state.get("converged", False) or state.get("capacity_clamped") is not None:
return result
heat, input_power = abs(float(state["Q_ref_iu [W]"])), float(state["E_tot [W]"])
if abs(heat - delivered) <= 1e-9 * delivered and input_power < power:
state.update(
{
"capacity_clamped": CAPACITY_CLAMPED_MAX,
"Q_request [W]": Q_r_iu,
"Q_max [W]": heat,
"capacity_binding": result.get("capacity_binding", BINDING_CYCLE),
}
)
return state
return result
#: ``binding`` values of :meth:`max_capacity` that name a ceiling.
_CEILING_BINDINGS = frozenset(
{
"compressor",
BINDING_CYCLE,
BINDING_CONDENSING,
BINDING_DISCHARGE,
BINDING_PRESSURE_RATIO,
}
)
def _capacity_limited_operating_point(
self, Q_r_iu: float, T0: float, T_a_room: float, *, ceiling: dict | None = None
) -> dict | None:
"""The state a unit runs at when the request itself has no operating point.
Above the ceiling (:meth:`max_capacity`) that is the ceiling. A
request below the ceiling can still be refused -- the envelope is not
monotone in the duty: at mid speed the efficiency is lower and the
discharge hotter than flat out -- and the unit then runs at the
largest duty below the request that has an operating point
(:meth:`_largest_deliverable_duty`). Either way the state is
energy-balanced, with ``capacity_clamped == "max"``, ``Q_max [W]`` and
``capacity_binding``. ``None`` when the request needs no such state
or none exists.
A cooling request solved with a room humidity is also the ceiling's
where it is under the ceiling by no more than the ceiling is searched
to (:attr:`_CEILING_REL_TOL`, 0.1 %) -- the request equal to it
first of all. The caller comes here with a request the ordinary
search did not deliver, and that search starts from the request's
least-lift point solved to a looser tolerance than the ceiling's
(:attr:`_LEAST_LIFT_SEED_RTOL`, with a step into the fans' flow range
of 1e-4 of the approaches). Close under the ceiling it reads the
request as beyond the limit that sets the ceiling, or as short of it
flat out, although the ceiling search has verified an operating
point there. Measured on default units of 2 to 10 kW at 180
conditions (20 to 46 degC outdoor, room 20 to 32 degC at 30 to 80 %):
the request equal to the ceiling was answered with the unit off at 4
(the limit for the reason) and up to 0.012 % short at 143, and the
sliver of requests not delivered reached from 6.5e-6 to 6.4e-5 of
the ceiling under it (every request 1e-4 under was delivered) --
while a request one float step above the ceiling ran at it. Such a
request runs at the ceiling now: the state :meth:`max_capacity`
reported, re-solved at its approaches (:meth:`_delivering_state`),
with ``Q_ref_iu [W]`` its ``Q_max [W]`` to rounding and nothing
unmet.
That is more than was asked by at most the 0.1 % the ceiling is
known to (by the width of the sliver, in those conditions). A
request the ordinary search delivers never comes here, and the dry
coil's requests, and heating's, are answered as they were (the
ceiling strictly above the request, else a search below it).
``ceiling`` is the ceiling of the condition where the caller has
it in hand (the result of :meth:`max_capacity`); it is solved here
otherwise.
"""
mode = "cooling" if Q_r_iu > 0 else "heating"
request = abs(Q_r_iu)
wet = self._coil_may_be_wet and Q_r_iu > 0
if ceiling is not None:
pass
elif self._RH_room is None:
ceiling = self.max_capacity(T0=T0, T_a_room=T_a_room, mode=mode)
else:
# The ceiling of the same room: its humidity goes with it.
ceiling = self.max_capacity(
T0=T0, T_a_room=T_a_room, mode=mode, rel_tol=self._CEILING_REL_TOL, RH_room=self._RH_room
)
# Anything else ("infeasible", a caller's own label) is not a ceiling.
if ceiling.get("binding") not in self._CEILING_BINDINGS:
return None
# The frost-free ceiling: this state is a cycle state, averaged later.
q_ceiling = float(ceiling.get("Q_max_frost_free [W]", ceiling["Q_max [W]"]))
if not math.isfinite(q_ceiling) or not q_ceiling > 0:
return None
# The request is the ceiling's: above it, or -- a wet cooling request
# -- not under it by more than the ceiling is searched to.
at_ceiling = q_ceiling < request or (wet and request >= q_ceiling * (1.0 - self._CEILING_REL_TOL))
if at_ceiling:
x = (ceiling["dT_ref_evap [K]"], ceiling["dT_ref_cond [K]"])
binding = ceiling["binding"]
else:
x_below, below, reason = self._largest_deliverable_duty(
math.copysign(1.0, Q_r_iu), request, T0, T_a_room, self._REDUCTION_REL_TOL
)
if x_below is None or below is None or reason is None:
return None
x, binding = x_below, self._binding_of(reason)
if binding not in self._CEILING_BINDINGS:
return None
q_ceiling = abs(float(below["Q_ref_iu [W]"]))
if not 0 < q_ceiling < request:
return None
state = self._delivering_state(x, math.copysign(q_ceiling, Q_r_iu), T0, T_a_room)
if state is None:
return None
state.update(
{
"capacity_clamped": CAPACITY_CLAMPED_MAX,
"Q_request [W]": Q_r_iu,
"Q_max [W]": q_ceiling,
"capacity_binding": binding,
}
)
return state
#: Duties tried, as fractions of the nameplate and from the bottom, to find
#: one that runs above a request the envelope refuses from below.
_FLOOR_LADDER: tuple[float, ...] = (0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0)
#: Factor between the duties tried above the ladder (:meth:`_floor_rungs`).
#: A search step, not a physical constant: the bisection that follows
#: closes on the duty to :attr:`_FLOOR_REL_TOL` whatever it is.
_FLOOR_CLIMB = 1.5
#: Relative width at which the bisection for the smallest continuous duty stops.
_FLOOR_REL_TOL = 5e-3
#: Relative width a wet cooling point's bisection goes on to where no duty
#: ran at :attr:`_FLOOR_REL_TOL`: the width the ceiling search closes to
#: (the default ``rel_tol`` of :meth:`max_capacity`). A search step, not a
#: physical constant.
_FLOOR_FINE_REL_TOL = 1e-3
#: Refusals a larger duty leaves behind: the limit the compressor meets
#: towards low speed at a large lift, where the overall efficiency
#: falls (:func:`~tmhp.compressor_envelope.raise_duty_within_envelope`
#: is the boilers' counterpart).
_REFUSED_FROM_BELOW = frozenset({DISCHARGE_TEMP_ABOVE_MAX})
#: The same for the search of the smallest continuous duty, which also
#: climbs past a wet cooling point's duties the fans' smallest airflows
#: refuse (:attr:`_MIN_AIRFLOW`; never the reason of a dry solve).
_CLIMBED_PAST = _REFUSED_FROM_BELOW | {_MIN_AIRFLOW}
def _smallest_continuous_operating_point(self, Q_r_iu: float, T0: float, T_a_room: float) -> dict | None:
"""The smallest duty above a request the envelope refuses from below, as a continuous state.
The compressor's speed floor is not the only lower end of continuous
operation. At a large lift (a low-pressure refrigerant in severe cold)
the overall efficiency falls towards low speed, and before
``rps_min`` is reached the envelope refuses the point for the
discharge temperature, which the falling efficiency drives above
``T_dis_max`` even with the discharge-temperature control used up.
Every duty below the one at which that limit lets go is refused --
while larger duties run. A unit does not stay off there: it runs at the smallest
duty the envelope admits and switches off when the room has had
enough, exactly as it does below its minimum speed.
A ladder of duties above the request is climbed past the rungs
refused the same way to the first that is not, and a bisection closes
on the smallest duty that runs (to :attr:`_FLOOR_REL_TOL`). The rung
that ends the climb may itself be refused by a limit of the other
side (the pressure ratio, a coil): the duties that run, if any, then
lie between it and the rung below, and the bisection goes by which
side refuses the trial. Every trial is the ordinary search
(:meth:`_optimize_operation`), so a request at or above the duty
returned is one :meth:`analyze_steady` solves in continuous
operation. The state is returned with ``capacity_clamped == "min"``:
it delivers more than the request and is averaged over the cycling
period like a minimum-speed row (:meth:`_report_part_load`). ``None``
when no duty runs: the limits of the two sides meet.
A cooling point solved with a room humidity has a second lower end
(:attr:`_MIN_AIRFLOW`): in mild weather the pressure ratio is on its
floor, which holds the condensing temperature well above the outdoor
air, and the evaporating temperature that would make room for the
outdoor coil's smallest airflow makes the wet indoor coil carry more
than a small duty at its own. Default 4 kW unit, outdoor 10 degC, room 27
degC at 80 %: no duty below 1.54 kW runs continuously (the dry coil
runs 1.2 kW at the same pressure ratio, 1.5). The climb passes those
duties the same way and the unit cycles at the smallest that runs.
With high smallest airflows that duty lies above the ladder's top,
and the wet climb goes on to the indoor coil's limit
(:meth:`_floor_rungs`).
The climb (:meth:`_climb_to_continuous_duty`) starts from the
request, so two requests of one condition can close on duties that
differ within :attr:`_FLOOR_REL_TOL`. The dry model, as before,
searches a condition once inside a frost balance or a dynamic run
and reuses the state for the smaller requests that follow
(:meth:`_remembering_floors`): such a row can differ by that
tolerance from the same request solved alone. A wet cooling point is
always answered as if it were solved alone -- its trials are
remembered one by one instead (:attr:`_wet_points`), which changes
no result. Where its own climb finds nothing at
:attr:`_FLOOR_REL_TOL` it is bisected on to a finer width
(:meth:`_climb_to_continuous_duty`), and where that finds nothing
either the caller takes the flat-out state the ceiling search has
verified (:meth:`_point_of_another_search`).
"""
sign, request = math.copysign(1.0, Q_r_iu), abs(float(Q_r_iu))
wet = self._coil_may_be_wet and sign > 0
# The floor belongs to the condition, not to the request: inside one
# frost balance or one dynamic run (the model does not change there)
# it is searched once per condition and reused for smaller requests.
# Not with a wet coil, whose row is that of the request solved alone
# (see the docstring); its searches are remembered trial by trial.
memo, key = None if wet else self._floor_memo, (sign, float(T0), float(T_a_room), self._w_room)
if memo is not None and key in memo and request < abs(float(memo[key]["Q_ref_iu [W]"])):
return dict(memo[key])
found, _ = self._climb_to_continuous_duty(Q_r_iu, T0, T_a_room)
if found is None:
return None
floor = dict(found[1])
floor["capacity_clamped"] = CAPACITY_CLAMPED_MIN
if memo is not None:
memo[key] = dict(floor)
return floor
def _climb_to_continuous_duty(
self, Q_r_iu: float, T0: float, T_a_room: float
) -> tuple[tuple[tuple[float, float], dict] | None, bool]:
"""The climb and the bisection of :meth:`_smallest_continuous_operating_point`, from the request.
Returns ``(point, to_the_top)``. ``point`` is
``((dT_ref_evap, dT_ref_cond), state)`` of the smallest duty found
to run in continuous operation above ``Q_r_iu``, or ``None``.
``to_the_top`` says the climb passed every rung, the last included,
as refused from below: no duty tried above the request was refused
any other way.
The trials are the ordinary search of a duty; for a cooling
condition solved with a room humidity each is made once while
:attr:`_wet_points` is kept, and answered from it afterwards -- the
approaches it ended on, from which :meth:`_calc_state` gives the
state again.
The bisection goes by which side refuses the trial, so it closes on
the place where the refusal changes sides -- where the duties that
run are, if any do. With a fan held at one flow on the
pressure-ratio floor they can be a window narrower than
:attr:`_FLOOR_REL_TOL` (4 kW unit with both fans held, outdoor 8
degC, room 35 degC saturated: 14.31 to 14.35 kW, 0.23 %), which the
bracket then closes around without a trial inside it (a 13.7 kW
request ended between 14,304.7 and 14,371.9 W). A wet cooling point
whose bracket closes with nothing running is therefore bisected on
to :attr:`_FLOOR_FINE_REL_TOL`, two or three trials more. Where a
duty ran at the first width nothing changes, and the dry search, and
heating's, stop where they did.
"""
sign, request = math.copysign(1.0, Q_r_iu), abs(float(Q_r_iu))
known: dict[float, tuple[tuple[float, float] | None, str | None]] | None = None
if self._coil_may_be_wet and sign > 0 and self._wet_points is not None:
known = self._wet_points.setdefault(self._wet_point_key("trials", T0, T_a_room), {})
def trial(q: float) -> tuple[dict | None, tuple[float, float] | None, str | None]:
if known is not None and q in known:
x, reason = known[q]
if x is None:
return None, None, reason
return (
self._calc_state(dT_ref_evap=x[0], dT_ref_cond=x[1], Q_r_iu=sign * q, T0=T0, T_a_room=T_a_room),
x,
None,
)
state, x, reason = searched(q)
if known is not None:
known[q] = (x, reason)
return state, x, reason
def searched(q: float) -> tuple[dict | None, tuple[float, float] | None, str | None]:
opt = self._optimize_operation(Q_r_iu=sign * q, T0=T0, T_a_room=T_a_room)
if not (bool(getattr(opt, "success", False)) and float(opt.fun) < OBJ_CAPACITY_LIMITED):
return None, None, getattr(opt, "least_lift_reason", None)
state = self._calc_state(
dT_ref_evap=opt.x[0], dT_ref_cond=opt.x[1], Q_r_iu=sign * q, T0=T0, T_a_room=T_a_room
)
if state is None or not state.get("converged", False) or state.get("capacity_clamped") is not None:
return None, None, None
return state, (opt.x[0], opt.x[1]), None
# ``q_lo`` is refused from below; ``q_hi`` runs (``running`` is its
# state, ``x_running`` its approaches) or is refused from above.
q_lo, q_hi, running, x_running = request, math.nan, None, None
for q in self._floor_rungs(sign, T_a_room):
if not q > request * (1.0 + self._FLOOR_REL_TOL):
continue
state, x, reason = trial(q)
if state is None and reason in self._CLIMBED_PAST:
q_lo = q
continue
q_hi, running, x_running = q, state, x
break
if not math.isfinite(q_hi):
return None, True
# A wet cooling point whose bracket closes with nothing running is
# bisected on, to the width the ceiling search closes to (below).
fine = self._coil_may_be_wet and sign > 0
for rel_tol in (self._FLOOR_REL_TOL, self._FLOOR_FINE_REL_TOL):
while q_hi - q_lo > rel_tol * q_hi:
mid = 0.5 * (q_lo + q_hi)
state, x, reason = trial(mid)
if state is not None:
q_hi, running, x_running = mid, state, x
elif running is not None or reason in self._CLIMBED_PAST:
q_lo = mid
else:
q_hi = mid # refused from above: the duties that run, if any, are below
if running is not None or not fine:
break
if running is None or x_running is None:
return None, False
return ((float(x_running[0]), float(x_running[1])), running), False
def _point_of_another_search(self, Q_r_iu: float, T0: float, T_a_room: float) -> dict | None:
"""The state a wet cooling request runs at where its own searches found none, from the ceiling's point.
For a request the fans' smallest airflows refuse
(:attr:`_MIN_AIRFLOW`) whose climb found no larger duty that runs
(:meth:`_climb_to_continuous_duty`). The climb tries duties the
compressor delivers inside its speed range. A unit with both fans
held at one flow, on the pressure-ratio floor, can run at none of
them and still run flat out -- the state the ceiling search starts
with (:meth:`max_capacity`; 2.5 kW unit, outdoor 8 degC, room 35
degC at 90 %: 9.63 kW). Before the request is answered with the
unit off, that state is taken for a candidate, re-solved as a
request of its own duty (:meth:`_delivering_state`):
- above the request, it is the duty the request is met by cycling
at (returned with ``capacity_clamped == "min"``, as
:meth:`_smallest_continuous_operating_point` returns its state);
- at the request or under it -- the least-lift point of the flat-out
duty itself, and of a request a little above it, can read as
refused from below -- it is where the unit runs for it, as for
any request at or above its ceiling (``capacity_clamped ==
"max"``, :meth:`_capacity_limited_operating_point`). The request
equal to the flat-out duty was answered with the unit off, between
two float neighbours that ran.
The flat-out state is a function of the condition, so the answer is
the same whatever was solved before. It is one solve
(:meth:`_largest_airflow_point`), not a search: the search of the
ceiling on the duty is not asked for here. It samples from the top
the duties the climb has just bisected from below -- closing on the
same place, where the refusal changes sides -- and where it ends
with nothing it costs seconds, for a request whose own climb took a
tenth of one. And where the climb passed every duty up to the
indoor coil's limit as refused from below, no duty above the request
was refused any other way: the unit is off in this weather, and
nothing is asked.
``None`` when the candidate gives no state.
"""
request = abs(float(Q_r_iu))
# Answered from the trials the request's own climb has just made.
_, to_the_top = self._climb_to_continuous_duty(Q_r_iu, T0, T_a_room)
if to_the_top:
return None
ceiling = self._solve_max_capacity(T0, T_a_room, "cooling", self._CEILING_REL_TOL, None, flat_out_only=True)
if ceiling.get("binding") not in self._CEILING_BINDINGS:
return None
q_ceiling = float(ceiling["Q_max [W]"])
if not (math.isfinite(q_ceiling) and q_ceiling > 0.0):
return None
if not q_ceiling > request:
return self._capacity_limited_operating_point(Q_r_iu, T0, T_a_room, ceiling=ceiling)
x = (float(ceiling["dT_ref_evap [K]"]), float(ceiling["dT_ref_cond [K]"]))
state = self._delivering_state(x, q_ceiling, T0, T_a_room)
if state is None:
return None
state["capacity_clamped"] = CAPACITY_CLAMPED_MIN
return state
def _floor_rungs(self, sign: float, T_a_room: float) -> Iterator[float]:
"""Duties the climb for the smallest continuous duty tries, from the bottom [W].
:attr:`_FLOOR_LADDER`, to twice the nameplate. A cooling point solved
with a room humidity goes on from there, by :attr:`_FLOOR_CLIMB` a
rung, to the largest duty the indoor coil carries
(:meth:`_indoor_coil_limit`), above which no request has an operating
point: fans with a high smallest airflow leave no continuous wet duty
under twice the nameplate in mild weather (default 4 kW unit with
both smallest flows at 65 % of the largest, outdoor 15 degC, room 35
degC saturated: 8.44 kW), and the climb ends on a duty that runs or
on one refused from above. The dry coil's climb, and heating's, ends
where it did.
"""
q = 0.0
for fraction in self._FLOOR_LADDER:
q = fraction * self.hp_capacity
yield q
if not (self._coil_may_be_wet and sign > 0):
return
top = self._indoor_coil_limit(T_a_room)
while q < top:
q = min(self._FLOOR_CLIMB * q, top)
yield q
#: Smallest continuous states found in the frost balance or dynamic run in
#: progress, by (mode sign, T0, T_a_room, room humidity ratio); ``None`` outside one.
_floor_memo: dict[tuple[float, float, float, float | None], dict] | None = None
@contextlib.contextmanager
def _remembering_floors(self) -> Iterator[None]:
"""Reuse :meth:`_smallest_continuous_operating_point` results while the block runs."""
outer = self._floor_memo
if outer is None:
self._floor_memo = {}
try:
yield
finally:
self._floor_memo = outer
# =============================================================
# Steady-state analysis
# =============================================================
[docs]
@steady_notice(delivered_key="Q_ref_iu [W]")
@steady_envelope()
def analyze_steady(
self,
Q_r_iu: float,
T0: float,
T_a_room: float | None = None,
*,
return_dict: bool = True,
postprocess: bool = True,
verbose: bool = True,
RH_out: float | None = None,
RH_room: float | None = None,
request_basis: str = REQUEST_BASIS_TOTAL,
) -> dict | pd.DataFrame:
"""Run a steady-state performance snapshot.
Parameters
----------
Q_r_iu : float
Indoor thermal load [W]. >0 cooling, <0 heating, 0 off. With the
default ``request_basis`` it is the
heat the refrigerant exchanges with the room air at the indoor
coil (``Q_ref_iu [W]``): in cooling the coil's total heat,
sensible plus latent, before the indoor fan's heat. What the room
receives is reported as ``Q_room_sensible [W]`` and
``Q_iu_latent [W]`` (below). With
``request_basis="sensible"`` it is the net sensible heat
the room air gives up (cooling) or receives (heating).
T0 : float
Dead-state / outdoor-air temperature [°C].
T_a_room : float | None
Room air temperature [°C]. Uses constructor default if None.
return_dict : bool
If True return dict; else single-row DataFrame.
postprocess : bool
If True, apply postprocess_exergy to the output.
verbose : bool
If False, the :class:`~tmhp.OperatingLimitWarning` of this call
is not issued (the row is the same).
RH_out : float | None
Outdoor relative humidity as a fraction (0-1), used by the frost
correction in heating. None: the frost model's default (0.84).
RH_room : float | None
Room relative humidity as a fraction (0-1) at ``T_a_room`` and
one standard atmosphere. With it, a cooling coil whose surface --
taken at the evaporating temperature -- is below the room air's
dew point condenses water (the wet coil of
:func:`tmhp.heat_exchanger.calc_HX_perf_for_target_heat`), and
the request ``Q_r_iu`` is met by sensible plus latent heat. None
(default): the dry coil, all of the coil heat sensible. Not read
on a heating request, where the indoor coil is the condenser, nor
on an off one (``Q_r_iu <= 0``): anything may be given there. On
a cooling request a value that is not a number in 0-1 raises
``ValueError``.
request_basis : str
What ``Q_r_iu`` is a request for. ``"total"`` (default): the
refrigerant-side heat of the indoor coil, ``Q_ref_iu [W]``.
``"sensible"``: the net sensible heat of the room air,
``Q_room_sensible [W]`` -- the sensible load a zone of a building
simulation hands over. The coil then has to carry more than the
request in cooling (the indoor fan's heat, and with ``RH_room``
the latent heat of the water it condenses) and less in heating
(the fan's heat is part of what the room receives), and the
model finds the coil duty at which ``Q_room_sensible [W]`` of the
row equals the request (see *Notes*). Any other value raises
``ValueError``.
Returns
-------
dict | pd.DataFrame
Cycle state plus diagnostic flags.
Two keys are useful for branching:
- ``"converged"`` (bool) — True only when the inner HX optimisation
and the SciPy optimiser both succeeded.
- ``"failure_reason"`` (str) — one of ``"none"``, ``"cycle_invalid"``
(the refrigerant cycle itself was infeasible), ``"pr_above_max"``,
``"discharge_temp_above_max"``, ``"condensing_temp_above_max"``
(the
compressor envelope refuses the request where it is easiest to
meet -- at its least-lift point -- and no smaller duty runs
either; a request that a smaller duty meets returns that duty
with ``capacity_clamped="max"`` and ``capacity_binding`` naming
the limit: ``"discharge_temperature"``,
``"condensing_temperature"`` for ``T_cond_max``),
``"hx_not_converged"`` (cycle OK
but a coil cannot carry the duty inside the approach bounds), or
``"optimizer_failed"`` (SciPy reported ``success=False``).
ASHP triggers an off-mode fallback for any of the non-``"none"``
reasons — ``E_cmp [W]`` will be 0 and the COP keys will be NaN
in that case. Treat ``failure_reason != "none"`` as "do not
trust the numbers".
Part load is reported on every row: ``Q_request [W]`` (signed,
as asked), ``Q_unmet [W]`` (request not delivered, >= 0),
``runtime_fraction [-]``, ``capacity_ratio [-]``,
``part_load_factor [-]``, ``Q_min [W]`` and
``E_cycling_loss [W]``. A request below the minimum continuous
capacity (``capacity_clamped == "min"``) is the mean over an
on/off cycling period: ``Q_ref_iu [W]`` equals the request,
heat and flow rates are the running values times
``capacity_ratio [-]`` (the indoor fan's power with them),
compressor and outdoor-fan power the running values times
``runtime_fraction [-]``, and the COP keys carry the EN 14825
degradation; temperatures, pressures and speed are those of
the running machine (:mod:`tmhp.cycling`). A request above
the ceiling (``capacity_clamped == "max"``) adds ``Q_max [W]``
and ``capacity_binding`` (``"compressor"``,
``"discharge_temperature"``, ``"condensing_temperature"``,
``"pressure_ratio"`` or ``"cycle"``; see
:meth:`max_capacity`).
Heating below the frost model's outdoor limit (5 degC; the
correction grows to its full size at 2 degC) is
the mean over frosting and defrost (:mod:`tmhp.defrost`):
``defrost_fraction [-]`` is the share of the runtime spent
defrosting, ``frost_capacity_factor [-]`` and
``frost_power_factor [-]`` the multipliers of the frosted coil,
``E_defrost [W]`` and ``Q_defrost [W]`` the mean power and room
heat the defrost takes, and ``Q_ref_iu_frost_free [W]`` /
``E_tot_frost_free [W]`` the frost-free cycle the row was solved
at. Without frost those two repeat ``Q_ref_iu [W]`` and
``E_tot [W]``.
The indoor coil's heat is split on every row:
``Q_iu_sensible [W]`` and ``Q_iu_latent [W]`` (air side, before
the fan; their sum is ``Q_ref_iu [W]`` within the coil solver's
tolerance), ``SHR_iu [-]`` their sensible share,
``m_dot_iu_condensate [kg/s]`` the water condensed, and
``w_iu_a_in [kg/kg]`` / ``w_iu_a_out [kg/kg]`` the humidity ratio
of the air entering and leaving the unit, with ``RH_room [-]``
the room humidity used (the three NaN without one). Latent heat
is zero for a dry coil. ``Q_room_sensible [W]`` is the net
sensible heat the room air gives up (cooling:
``Q_iu_sensible - E_iu_fan``) or receives (heating:
``Q_iu_sensible + E_iu_fan``), the indoor fan's heat counted.
With ``RH_room`` in cooling both ends of the range are the wet
coil's. A request above its ceiling runs there
(``capacity_clamped == "max"``; :meth:`max_capacity` with the
same ``RH_room``). A request equal to the ceiling is delivered
it, with ``Q_unmet [W]`` zero: as an ordinary row
(``capacity_clamped`` ``None``) where the search of the request
delivers that duty, and otherwise as the ceiling's own state
(``capacity_clamped == "max"``, ``Q_ref_iu [W]`` the
``Q_max [W]`` :meth:`max_capacity` reports, to rounding). The
ceiling's state also answers a request the search does not
deliver that is under the ceiling by no more than the 0.1 % the
ceiling is searched to, which is up to that 0.1 % more than was
asked (measured on default units: 0.006 %). A request the
search delivers is an ordinary row at any distance from the
ceiling. In mild weather, on the pressure-ratio floor,
the fans' smallest airflows leave no continuous operation below
some duty; a smaller request is met by cycling at that duty
(``capacity_clamped == "min"``, ``Q_min [W]``). Where the
search above the request finds no such duty, the state the unit
runs flat out at is taken -- the one the ceiling search of
:meth:`max_capacity` starts with -- which the request is met by
cycling at when it lies above the request and where the unit
runs when it lies under it; and where no duty is
found to run the row is off with
``failure_reason == "hx_not_converged"`` (a fan held at one flow
can leave a window of duties too narrow for the searches to hit:
see the notes of :meth:`max_capacity`). Without ``RH_room``
such a request is answered as before, with the unit off and
``"cycle_invalid"``. On a row whose coil removes water
(``Q_iu_latent [W]`` > 0) the exergy columns ``Xc_iu_hx [W]``,
``X_eff_iu_hx [-]`` and ``X_eff_sys [-]`` are NaN
(:meth:`postprocess_exergy`).
``Q_request [W]`` and ``Q_unmet [W]`` are on the basis of
``Q_r_iu``, which ``request_basis`` names on every row. With
``"total"``: refrigerant-side coil heat, total (sensible plus
latent) and before the fan heat -- not the room-side
``Q_room_sensible [W]``. With ``"sensible"``: that
room-side heat, ``Q_unmet [W]`` being what
``Q_room_sensible [W]`` is short of the request. Every other key
means the same on either basis: ``Q_ref_iu [W]``, ``Q_max [W]``
and ``Q_min [W]`` are coil heat. ``cop_sys [-]`` is on the room
side: ``Q_room_sensible [W]`` plus ``Q_iu_latent [W]`` over
``E_tot [W]``.
A row asked with ``"sensible"`` has one key more, after the
others: ``request_solves [-]`` (int), the number of total-basis
solves the search of the request took -- what the row cost, in
solves of ``request_basis="total"``. It is 0 for a zero request,
which is not searched, and never above
:attr:`_ROOM_SENSIBLE_MAX_SOLVES`; a row short of its request
that took them all is one the search did not finish (*Notes*). A
total-basis row does not have the key.
Warns
-----
OperatingLimitWarning
Once, when the compressor was asked to run and the result is the
off state (``failure_reason`` other than ``"none"``) or a running
point that delivers less than the request (``capacity_clamped ==
"max"``): the request, what is delivered, the limit in words and
what removes it. Issued once per model and limit unless the
``"always"`` filter is set (:mod:`tmhp.operating_limits`).
Notes
-----
A request on the room's net sensible heat
(``request_basis="sensible"``) is answered with the row of a
coil duty -- the row ``request_basis="total"`` returns for that duty,
key for key, with ``Q_request [W]``, ``Q_unmet [W]`` and
``request_basis`` written over, and ``request_solves [-]`` added.
The duty is searched: the request itself first, then that duty
scaled by the request over the net sensible heat it gave, then by
the secant through the last two duties; a search that five solves
have not ended, with trials on both sides of the request, takes its
steps from the trials of each side, which is what closes on a duty
just beyond a kink of the net sensible heat
(:meth:`_solve_room_sensible`). ``Q_room_sensible [W]`` is read
from the row as it is
reported, so a request the unit meets by cycling, and a heating
request with frost on the outdoor coil, are matched in their means.
While the compressor is off the indoor fan is off with it: a cycling
row carries the running coil heat, the fan's power and so the net
sensible heat all times ``capacity_ratio [-]`` (:mod:`tmhp.cycling`),
and nothing for a fan that circulates air between the compressor's
runs.
The match is to 1e-6 of the request where the first three solves
reach it, which they do on a row whose coil is dry (no ``RH_room``,
a coil above the room's dew point, heating) of a unit whose fans
modulate: such a row is smooth along the duty. Otherwise it is to
1e-4. On a row that condenses water the operating point of a duty is
the optimiser's, located to 1e-3 K of approach and 0.1 W of input,
and the sensible share of neighbouring wet duties scatters by up to
that much; a fan held at one flow scatters a dry row by about 1e-5
(:attr:`_ROOM_SENSIBLE_LOOSE_RTOL`). A row inside the tolerance is
met, ``Q_unmet [W]`` zero. The ``Q_ref_iu [W]`` the row reports is
the coil duty that was solved, to rounding: asked again for it as
``request_basis="total"``, a unit whose fans modulate repeats the row
(every numeric key to 1e-12 on 2,646 requests of default units, wet
rows included). A unit with a fan held at one flow repeats it to the
scatter of its own rows: its search can end on either of two
operating points for duties one rounding apart (4 kW unit with the
indoor fan held, 25/35 degC, 4,023.127 W: 568.58 W of input with
60.9 W at the outdoor fan, or 568.14 W with 54.6 W).
The search ends without a match on
- a row at a limit: the coil duty asked for is delivered short
(``capacity_clamped == "max"``) with less net sensible heat than
the request. Above the ceiling of the condition that is the
ceiling's row, the largest coil duty the unit delivers
(:meth:`max_capacity`, ``Q_room_sensible_at_Q_max [W]``); the rest is
``Q_unmet [W]``. Where an earlier trial delivered more net
sensible heat (an indoor fan whose heat grows faster than the
coil's sensible heat), that trial is the answer;
- an off row (``failure_reason`` other than ``"none"``): the model
answers the coil duty tried with the unit off. A unit with a fan
held at one flow can have such duties below its ceiling, and
duties delivered short (see :meth:`max_capacity`); the duties
around the first one tried are not searched. The answer is the
trial that comes closest to the request from below, the off row
(nothing delivered) among them. Where the off row is the first
trial it is the answer, with the whole request unmet; after a
trial that delivered some net sensible heat, that trial is;
- a row that delivers more than the request where no duty tried
delivers less (a unit without the cycling model, below its
smallest continuous duty), with nothing unmet, as on the coil
basis;
- after :attr:`_ROOM_SENSIBLE_MAX_SOLVES` solves, the row that comes
closest to the request from below, with what is missing in
``Q_unmet [W]``. A unit with its outdoor fan held at one flow can
pass from one indoor airflow to another between two neighbouring
coil duties, and its net sensible heat with it (4 kW unit, 35 degC
outdoor, room 35 degC at 60 %: 1,665 W at a coil duty of 3,571 W,
2,490 W at 3,586 W); a request between the two is answered with
the lower row.
"""
validate_steady(locals())
request_basis = _check_request_basis(request_basis)
if T_a_room is None:
T_a_room = self.T_a_room
# Read, and checked, on a cooling request only: a heating or an off
# point has no use for it, whatever it is given.
RH_room = _check_room_humidity(RH_room) if RH_room is not None and Q_r_iu > 0 else None
solves = 0
if request_basis == REQUEST_BASIS_SENSIBLE and Q_r_iu != 0:
# The coil duty whose row has the requested net sensible heat.
result, solves = self._solve_room_sensible(
Q_r_iu, T0, T_a_room, postprocess=postprocess, verbose=verbose, RH_out=RH_out, RH_room=RH_room
)
else:
# A cooling point with a room humidity is solved with the wet indoor
# coil; any other point with the dry one.
with self._solving_with_room_humidity(RH_room, T_a_room, cooling=Q_r_iu > 0):
result = self._solve_steady(
Q_r_iu, T0, T_a_room, postprocess=postprocess, verbose=verbose, RH_out=RH_out
)
if result:
result[REQUEST_BASIS_KEY] = request_basis
if request_basis == REQUEST_BASIS_SENSIBLE:
# What the row cost: the last key, on rows of this basis only.
result[REQUEST_SOLVES_KEY] = solves
if return_dict:
return result
return pd.DataFrame([result]) if result else pd.DataFrame()
#: Relative tolerance to which ``Q_room_sensible [W]`` is matched with a
#: request on that basis (``request_basis="sensible"``) by the first
#: :attr:`_ROOM_SENSIBLE_STRICT_SOLVES` solves of a row whose coil is dry.
#: A search tolerance, not a physical constant: such a row of a unit
#: whose fans modulate is smooth along the coil duty (its net sensible
#: heat departs from a straight line by less than 6e-7 of itself over
#: 1 % of the duty, default 4 kW unit at 35/27 degC), and the secant
#: reaches 1e-6 on its third solve.
_ROOM_SENSIBLE_RTOL = 1e-6
#: The tolerance of a row that condenses water (``Q_iu_latent [W]`` > 0),
#: and of any row from the solve after
#: :attr:`_ROOM_SENSIBLE_STRICT_SOLVES` on. The operating point of a duty
#: is where the refinement of :meth:`_optimize_operation` stops -- 1e-3 K
#: of approach, 0.1 W of input -- and a wet coil's sensible share moves
#: with the evaporating approach, so the net sensible heat of
#: neighbouring wet duties scatters around a smooth curve: by up to
#: 1.1e-4 of itself in the scans it was measured on (default 4 kW unit,
#: 35/27 degC at 50 %, 4.97 kW: 0.39 W of 3,599 W over 81 duties 0.005 %
#: apart; 30/27 degC at 80 %, 3 kW: 4e-5). A dry row of a unit with a fan
#: held at one flow scatters too, by about 1e-5 (both fans of a 4 kW unit
#: held, 46/27 degC, 2 kW: a step of 0.018 W between duties 0.0003 W
#: apart). No duty need have a net sensible heat closer to the request
#: than that scatter, so a search that has not arrived by then is not
#: held to 1e-6.
_ROOM_SENSIBLE_LOOSE_RTOL = 1e-4
#: Solves a dry row is held to :attr:`_ROOM_SENSIBLE_RTOL` for: the
#: request, the first guess from it, and one secant step, which is where
#: a smooth row arrives.
_ROOM_SENSIBLE_STRICT_SOLVES = 3
#: Factor by which the outer search moves the coil duty where every trial
#: so far lies on one side of the request and the secant through the last
#: two points the wrong way, or nowhere: the net sensible heat is not
#: monotone in the coil duty everywhere (a wet coil that cycles on the
#: pressure-ratio floor: default 2.5 kW unit, 20 degC outdoor, room 30
#: degC at 50 %, 119.8 W at a coil duty of 135.5 W and 118.3 W at
#: 158.2 W). A search step, not a physical constant: the trials that
#: follow close on the duty whatever it is.
_ROOM_SENSIBLE_GROWTH = 1.5
#: Solves up to which a search with trials on both sides of the request
#: takes the secant through its last two trials; from the next one on it
#: takes its step from the trials of each side
#: (:meth:`_solve_room_sensible`). A step of the search, not a physical
#: constant. Where the net sensible heat is smooth along the coil duty
#: that secant is the quickest of the steps tried and arrives within five
#: solves: 1,936 of the 1,950 requests met on the grid of
#: :attr:`_ROOM_SENSIBLE_MAX_SOLVES`, and 1,482 of 1,490 on six units
#: with a fan held at one flow; steps from the sides from the first
#: bracket on took 3.45 solves a request on that grid instead of 2.91.
#: A search
#: still open then is at a kink or a step of the net sensible heat, where
#: the last two trials lie on either side of it and their secant closes
#: on the request only linearly. The default 2.5 kW unit at 20 degC
#: outdoor with the room at 29.9 degC and 50 % cycles with a running
#: state that changes with the request below a coil duty of 205.2 W and
#: does not above it: 0.22 W of net sensible heat per W of coil heat
#: below, 0.61 W above. The request for 125.25 W, whose duty is 0.2 W
#: above the kink, was 0.05 W short after twelve such secants and is met
#: in eight solves by the steps from the sides.
_ROOM_SENSIBLE_SECANT_SOLVES = 5
#: Total-basis solves one request on the room's net sensible heat may
#: take. A budget of the search, not a physical constant: on 2,646
#: requests of three default units (2.5 to 10 kW, dry and wet, cooling
#: and heating) a request that was met took 2.8 solves on a dry row and
#: 4.1 on a wet one on average, at most four on a dry row and at most
#: seven on 846 of the 848 wet ones; the other two took eight (one of
#: them the cycling unit of :attr:`_ROOM_SENSIBLE_GROWTH`, where the
#: search first has to pass a stretch along which the net sensible heat
#: falls). Among 528 requests around the kink of
#: :attr:`_ROOM_SENSIBLE_SECANT_SOLVES` the most was ten. A search
#: that uses the budget up without a match has tried no duty with the
#: requested net sensible heat (:meth:`_solve_room_sensible`).
_ROOM_SENSIBLE_MAX_SOLVES = 12
def _solve_room_sensible(
self,
Q_r_iu: float,
T0: float,
T_a_room: float,
*,
postprocess: bool,
verbose: bool,
RH_out: float | None,
RH_room: float | None,
) -> tuple[dict, int]:
""":meth:`analyze_steady` for a request on the room's net sensible heat (checked arguments, not zero).
Returns the row and the number of total-basis solves it took
(``request_solves [-]``). The row is the row of a coil duty, solved
the ordinary way
(``request_basis="total"``), in which ``Q_request [W]`` and
``Q_unmet [W]`` are then written on the basis of the request. The
duty is found by an outer search on it, every trial a total-basis
solve whose ``Q_room_sensible [W]`` is read as the row reports it
(the mean over a cycling period, and over frosting and defrost):
1. the request itself. In cooling it gives too little (the coil's
heat less the latent part and the fan's heat), in heating too
much (the coil's heat plus the fan's);
2. that duty times the request over the net sensible heat it gave
-- exact for a cycling row, whose heats all scale with the
capacity ratio, and the fan heat (dry coil) or the sensible heat
ratio (wet coil) of the first solve otherwise. Where the first
solve gives zero or negative net sensible heat -- in cooling, an
indoor fan whose heat is at least the coil's sensible heat, which
only a fan far less efficient than the default reaches -- there
is nothing to scale by, and twice the request is taken, the
largest step step 3 takes upwards;
3. the secant through the last two trials. Where trials lie on both
sides of the request and the secant leaves the interval between
the closest of them (the bracket), its middle is taken. Where
every trial so far gives too little, the duty is above them all:
the secant is kept if it points there, by no more than a factor
two, and :attr:`_ROOM_SENSIBLE_GROWTH` times the largest duty
tried is taken otherwise (the net sensible heat is not monotone
in the coil duty everywhere); likewise downwards where every
trial gives too much;
4. from the solve after :attr:`_ROOM_SENSIBLE_SECANT_SOLVES` on, in
a bracket: a step from the trials of each side of the request.
The line through the two trials closest to the bracket under the
request, and the line through the two closest over it, each
name a duty; of those inside the bracket the one nearer to where
the chord between the bracket's ends meets the request is taken,
and the bracket's middle where neither is inside.
Step 4 is for a net sensible heat with a kink or a step along the
coil duty, which is where a search is still open by then. The net
sensible heat is smooth in stretches: a kink is where condensation
sets in or where the running state of a cycling unit stops changing
with the request, a step where the operating point of a unit with a
fan held at one flow passes from one airflow to another. Just past
a kink the secant through the last two trials, which lie on either
side of it, closes on the request only linearly. Two trials on the
request's own side of the kink lie on its stretch, and the line
through them names the duty as closely as that stretch is straight
-- exactly on a cycling row, whose heats all scale with the capacity
ratio. Where the net sensible heat bends one way between the trials
the lines of both sides err to the same side of the duty and the
chord to the other, so the line nearer the chord is the closer of
the two. A line that leaves the bracket says the request is not
reached along its stretch -- a step, or a kink beyond the other end
-- and the middle halves the bracket, which is what closes on a
step.
The bracketing methods of the textbooks were measured beside it,
each from the first bracket on, and not taken. For the request of
:attr:`_ROOM_SENSIBLE_SECANT_SOLVES`, 0.2 W above a kink: false
position with the Illinois correction twelve solves (the whole
budget), Brent's method ten, the steps above eight; over the 528
requests around it at most twelve, eleven and ten. Neither is as
quick as the secant where the row is smooth: 2.918 and 2.908 solves
a request on the grid of :attr:`_ROOM_SENSIBLE_MAX_SOLVES` against
2.906, and 2.575 and 2.547 against 2.546 on six units with a fan
held (the search as it is: 2.905 and 2.546). Both interpolate
between the bracket's ends, which lie on either side of a kink
until the bracket has closed past it.
The search ends on a trial whose net sensible heat is within the
tolerance of the request: :attr:`_ROOM_SENSIBLE_RTOL` for the first
:attr:`_ROOM_SENSIBLE_STRICT_SOLVES` trials of a dry coil,
:attr:`_ROOM_SENSIBLE_LOOSE_RTOL` where the trial's coil condenses
water and for every later trial. It also ends on a trial that says
no other duty is the unit's answer:
- the unit delivers the coil duty short (``capacity_clamped ==
"max"`` with coil heat unmet) and its net sensible heat is under
the request: the unit is at a limit. A coil duty above the ceiling
of the condition gives the ceiling's row, so this is where a
request above the largest net sensible heat ends;
- the unit is off (``failure_reason`` set): the coil duty has no
operating point and no smaller one is run in its place. Duties
around it are not tried.
Two trials with the same net sensible heat are a unit without the
cycling model below its smallest duty; what follows applies where
the later of them did not end the search (met, off, or short of the
request at a limit, above). Under the request the search
goes on: inside the bracket where a trial over the request lies
above them (its middle, or the step of step 4 from the solve named
there on), and otherwise :attr:`_ROOM_SENSIBLE_GROWTH` times higher,
twice where no trial has yet given positive net sensible heat, as
every step up then is. Over the request they end it.
Where the trials stop moving (two with the same net sensible heat
over the request), where
:attr:`_ROOM_SENSIBLE_MAX_SOLVES` are used up, or where the search
ends on one of the two trials above, no duty tried has the
requested net sensible heat. The answer is then the trial that comes
closest to the request from below, so that what is missing shows as
``Q_unmet [W]``; where every trial delivers more than the request,
the one that delivers least. This is where the total-basis rows of
neighbouring duties are not neighbours themselves -- a unit with its
outdoor fan held at one flow whose operating point passes from one
indoor airflow to another between two duties (4 kW unit, 35 degC
outdoor, room 35 degC at 60 %: 1,665 W of net sensible heat at a
coil duty of 3,571 W, 2,490 W at 3,586 W) has no duty for a request
between the two.
The trials of a wet cooling condition share what its searches find
(:meth:`_sharing_wet_points`), which changes none of them; nothing
else is carried from one trial to the next, and nothing from one
request to another: the row is a function of the request and the
condition.
"""
sign, request = math.copysign(1.0, Q_r_iu), abs(float(Q_r_iu))
# The trials in the order solved: (coil duty the row sits at, its net
# sensible heat, the row).
trials: list[tuple[float, float, dict]] = []
met = False # whether the last trial has the requested net sensible heat
def tolerance(row: dict) -> float:
"""Largest difference from the request at which ``row``, the last trial, is met."""
wet = float(row.get("Q_iu_latent [W]", 0.0)) > 0.0
strict = not wet and len(trials) <= self._ROOM_SENSIBLE_STRICT_SOLVES
return (self._ROOM_SENSIBLE_RTOL if strict else self._ROOM_SENSIBLE_LOOSE_RTOL) * request
def solve(duty: float) -> bool:
"""Solve the total-basis row of ``duty``; whether the search ends on it."""
nonlocal met
row = self.analyze_steady(
Q_r_iu=sign * duty,
T0=T0,
T_a_room=T_a_room,
return_dict=True,
postprocess=postprocess,
verbose=verbose,
RH_out=RH_out,
RH_room=RH_room,
)
assert isinstance(row, dict)
running = bool(row.get("hp_is_on", False)) and row.get("failure_reason", "none") == "none"
sensible = float(row.get("Q_room_sensible [W]", 0.0)) if running else 0.0
if not math.isfinite(sensible):
sensible = 0.0
# Delivered short of the coil duty asked for: the row sits at the
# duty it delivers, and no larger request moves it.
short = (
running
and row.get("capacity_clamped") == CAPACITY_CLAMPED_MAX
and float(row.get("Q_unmet [W]", 0.0)) > 0.0
)
trials.append((abs(float(row["Q_ref_iu [W]"])) if short else duty, sensible, row))
met = running and abs(sensible - request) <= tolerance(row)
return met or not running or (short and sensible < request)
def step_from_the_sides(under: float, over: float) -> float:
"""A duty inside the bracket ``(under, over)``, from the trials of each side of the request (step 4)."""
# By duty: the bracket's end last of those under the request, first of those over it.
lower = sorted(t[:2] for t in trials if t[1] < request)[-2:]
upper = sorted(t[:2] for t in trials if t[1] > request)[:2]
chord = under + (request - lower[-1][1]) * (over - under) / (upper[0][1] - lower[-1][1])
steps = []
for side in (lower[::-1], upper):
if len(side) < 2:
continue
(near, sensible_near), (far, sensible_far) = side
if sensible_near != sensible_far:
step = near + (request - sensible_near) * (near - far) / (sensible_near - sensible_far)
if under < step < over:
steps.append(step)
return min(steps, key=lambda step: abs(step - chord)) if steps else 0.5 * (under + over)
def next_duty() -> float | None:
"""The coil duty to try after the trials made; ``None`` where they give none."""
duty, sensible, _ = trials[-1]
if len(trials) == 1:
# No net sensible heat to scale by (the fan's heat at least
# the coil's sensible heat): the duty is above, by the
# largest step that step 3 takes upwards.
return request * duty / sensible if sensible > 0.0 else 2.0 * duty
before, sensible_before, _ = trials[-2]
if duty == before:
return None
# Where no trial has cooled the room yet (the fan's heat at least
# the coil's sensible heat in every one), the slope says nothing
# of how far the duty is: the largest step upwards.
grow = 2.0 if max(t[1] for t in trials) <= 0.0 else self._ROOM_SENSIBLE_GROWTH
under = max((t[0] for t in trials if t[1] < request), default=math.nan)
over = min((t[0] for t in trials if t[1] > request), default=math.nan)
if sensible == sensible_before:
# Flat: a unit without the cycling model below its smallest
# duty. Over the request that row is the answer; under it
# (the fan's heat outweighs the coil's) the duty is above --
# inside the bracket where a trial over the request lies
# above, by the bracket's rule (middle, then step 4).
if sensible > request:
return None
if not under < over:
return grow * max(duty, before)
if len(trials) >= self._ROOM_SENSIBLE_SECANT_SOLVES:
return step_from_the_sides(under, over)
return 0.5 * (under + over)
step = duty + (request - sensible) * (duty - before) / (sensible - sensible_before)
if under < over:
# Trials on both sides: the duty lies between the closest two.
if len(trials) >= self._ROOM_SENSIBLE_SECANT_SOLVES:
# Not found where a smooth row is: a kink or a step.
step = step_from_the_sides(under, over)
elif not under < step < over:
step = 0.5 * (under + over)
elif math.isnan(over):
# Every trial gives too little: the duty is above them all,
# whatever the last two say of the slope.
if grow == 2.0 or not under < step <= 2.0 * under:
step = grow * under
elif math.isnan(under):
# Every trial gives too much: below them all.
if not 0.5 * over <= step < over:
step = over / grow
else:
# Both sides, out of order along the duty (not monotone there).
step = min(max(step, 0.5 * duty), 2.0 * duty)
if not (math.isfinite(step) and step > 0.0) or step == duty:
return None
return step
ended = False
duty: float | None = request
# What the wet coil's searches find of the condition serves every trial.
with self._sharing_wet_points():
for _ in range(self._ROOM_SENSIBLE_MAX_SOLVES):
assert duty is not None
ended = solve(duty)
if ended:
break
duty = next_duty()
if duty is None:
break
if met:
_, sensible, result = trials[-1]
else:
# No trial has the requested net sensible heat (or the last is
# the unit off or at its ceiling, which an earlier trial may beat
# where the net sensible heat falls with the duty): the closest
# from below, else the least of those above.
below = [t for t in trials if t[1] < request]
_, sensible, result = max(below, key=lambda t: t[1]) if below else min(trials, key=lambda t: t[1])
result["Q_request [W]"] = float(Q_r_iu)
unmet = request - sensible
result["Q_unmet [W]"] = unmet if unmet > self._ROOM_SENSIBLE_LOOSE_RTOL * request else 0.0
# The binding of the row was settled by the solve it came from: the
# envelope's check of this call (:func:`~tmhp.compressor_envelope.steady_envelope`)
# has nothing left to solve again.
self._condensing_rejected = False
return result, len(trials)
def _solve_steady(
self, Q_r_iu: float, T0: float, T_a_room: float, *, postprocess: bool, verbose: bool, RH_out: float | None
) -> dict:
""":meth:`analyze_steady` for checked arguments, with the room humidity of the point already set."""
# Heating with a frosting outdoor coil is the mean over frosting and
# defrost: solved frost-free at a larger duty, then averaged.
frost = self._frost_state(Q_r_iu, T0, RH_out)
if frost.active:
# The frost balance solves the frost-free cycle at several duties.
with self._remembering_floors():
return self._analyze_steady_frosted(
frost, Q_r_iu, T0, T_a_room, postprocess=postprocess, verbose=verbose
)
if Q_r_iu == 0:
result: dict | None = self._calc_state(
dT_ref_evap=5.0,
dT_ref_cond=5.0,
Q_r_iu=0.0,
T0=T0,
T_a_room=T_a_room,
)
if result is not None:
result["failure_reason"] = "none"
else:
opt_result = self._optimize_operation(
Q_r_iu=Q_r_iu,
T0=T0,
T_a_room=T_a_room,
)
result = None
with contextlib.suppress(Exception):
result = self._calc_state(
dT_ref_evap=opt_result.x[0],
dT_ref_cond=opt_result.x[1],
Q_r_iu=Q_r_iu,
T0=T0,
T_a_room=T_a_room,
)
# Pressure-ratio envelope event of the final operating point.
# Floor -> the ratio is held on it and the cycle is solved;
# ceiling -> rejected (the off state below). Nothing is printed.
pr_event = self._last_pr_event
# opt_success=True at the infeasible sentinel is a false success:
# the optimiser converged but never escaped the penalty region. A
# capacity-limited optimum sits in its own band below that sentinel
# and counts as success — the machine ran flat out and delivered
# less than asked, which is operation, not failure.
opt_fun = float(getattr(opt_result, "fun", OBJ_INFEASIBLE))
opt_success = bool(getattr(opt_result, "success", False)) and opt_fun < OBJ_INFEASIBLE
# Why the least-lift point of this request is not an operating
# point, when the search found none: the limit that refuses the
# request where it is easiest to meet. The probe the search ends on
# is an arbitrary approach pair, and the limit it happens to break
# (the pressure ratio at 15 K + 15 K, say) need not be the one in
# the way.
least_lift_reason = getattr(opt_result, "least_lift_reason", None)
if (result is None or not result.get("converged", False)) and least_lift_reason is not None:
failure_reason = "hx_not_converged" if least_lift_reason == self._AIR_SIDE else least_lift_reason
elif result is None:
# Distinguish a pressure-ratio ceiling rejection from a generic
# invalid cycle so downstream consumers see the specific cause.
failure_reason = (
pr_event[0] if pr_event is not None and pr_event[0] != "pr_below_min" else "cycle_invalid"
)
elif not result.get("converged", False):
failure_reason = "hx_not_converged"
elif not opt_success:
failure_reason = "optimizer_failed"
else:
failure_reason = "none"
# A wet coil refused by the fans' smallest airflows is refused from
# below: its answer is the smallest continuous duty, further down.
unsolved = failure_reason not in ("none", self._MIN_AIRFLOW) and (
result is None or not result.get("converged", False)
)
limited = (
failure_reason == "none"
and result is not None
and result.get("capacity_clamped") == CAPACITY_CLAMPED_MAX
)
if unsolved or limited:
# The request has no operating point of its own: the compressor
# runs out of speed, or the envelope or a coil binds first. The
# unit then runs at its ceiling (:meth:`max_capacity`), which is
# solved rather than searched -- ranking capacity-limited
# candidates by delivered heat walks into states that starve
# the outdoor coil (see :meth:`max_capacity`). A capacity-limited
# search result stands only if the ceiling cannot be solved.
# Match the existing numerical off-state fallback if the
# envelope search itself encounters an invalid cycle.
with contextlib.suppress(Exception):
ceiling_state = self._capacity_limited_operating_point(Q_r_iu, T0, T_a_room)
if ceiling_state is not None:
result = ceiling_state
failure_reason = "none"
if failure_reason in self._CLIMBED_PAST:
# Refused at low speed -- the discharge temperature -- or, with
# a wet coil on the pressure-ratio floor, by the fans' smallest
# airflows, while larger duties run: the unit's
# smallest continuous duty lies above the request, and the
# request is met by cycling at it.
with contextlib.suppress(Exception):
floor_state = self._smallest_continuous_operating_point(Q_r_iu, T0, T_a_room)
if floor_state is not None:
result = floor_state
failure_reason = "none"
if failure_reason == self._MIN_AIRFLOW:
# The climb found no larger duty that runs. The state the
# ceiling search of this condition starts with, the unit
# flat out, is a candidate: above the request it is cycled
# at, under it it is where the unit runs.
with contextlib.suppress(Exception):
other_state = self._point_of_another_search(Q_r_iu, T0, T_a_room)
if other_state is not None:
result = other_state
failure_reason = "none"
if failure_reason == self._MIN_AIRFLOW:
# No duty runs. The limit is a coil's: it
# cannot carry so little inside its fan's flow range.
failure_reason = "hx_not_converged"
if failure_reason != "none":
# Not a warning here: this solve may be the frost-free trial of
# a frosted request. The call that owns the result words it
# (tmhp.operating_limits.steady_notice); the value that broke
# the limit is known when the search ended on that probe.
ended_on_it = least_lift_reason is None and pr_event is not None and pr_event[0] == failure_reason
note_refusal(failure_reason, Q_r_iu, pr_event[1] if ended_on_it and pr_event is not None else None)
result = self._calc_state(
dT_ref_evap=5.0,
dT_ref_cond=5.0,
Q_r_iu=0.0,
T0=T0,
T_a_room=T_a_room,
)
if result is not None:
result["converged"] = False
result["failure_reason"] = failure_reason
else:
# By construction (failure_reason == "none") result is a dict.
assert result is not None
# Only a ceiling set by a coil leaves a choice of operating
# point: at the speed ceiling and on an envelope limit the
# least-lift point is the only one that delivers the duty.
if (
result.get("capacity_clamped") == CAPACITY_CLAMPED_MAX
and result.get("capacity_binding", BINDING_CYCLE) == BINDING_CYCLE
):
result = self._least_power_at_ceiling(result, Q_r_iu, T0, T_a_room)
result["converged"] = True
result["failure_reason"] = "none"
if result is None:
result = {}
if result:
self._report_part_load(result, Q_r_iu)
# A request the frost model finds too small to frost may be met by
# a machine that does: on its speed floor the unit runs at more
# than the request (a load-weighted frost model; otherwise unchanged).
running_frost = self._frost_state_of_running(result, frost, T0)
if running_frost.active and not frost.active:
with self._remembering_floors():
return self._analyze_steady_frosted(
running_frost, Q_r_iu, T0, T_a_room, postprocess=postprocess, verbose=verbose
)
if result:
self._write_frost_free(result, frost)
self._complete_row(result)
if postprocess and result:
result = self._exergy_of_row(result)
return result
# =============================================================
# Dynamic simulation
# =============================================================
[docs]
@dynamic_notice
def analyze_dynamic(
self,
simulation_period_sec: int,
dt_s: int,
Q_r_iu_schedule,
T0_schedule,
T_a_room_schedule=None,
result_save_csv_path: str | None = None,
RH_out_schedule=None,
*,
RH_room_schedule=None,
request_basis: str = REQUEST_BASIS_TOTAL,
) -> pd.DataFrame:
"""Run a time-stepping dynamic simulation.
Parameters
----------
simulation_period_sec : int
Total simulation duration [s].
dt_s : int
Time step size [s].
Q_r_iu_schedule : array-like
Indoor thermal load per step [W].
T0_schedule : array-like
Outdoor temperature per step [°C].
T_a_room_schedule : array-like | None
Room air temperature per step [°C].
If None, uses constructor default.
result_save_csv_path : str | None
Optional CSV output path.
RH_out_schedule : array-like | None
Outdoor relative humidity per step, as a fraction (0-1), for the
frost correction in heating. If None, the frost model's default.
RH_room_schedule : array-like | None
Room relative humidity per step, as a fraction (0-1), for the wet
indoor coil in cooling (``RH_room`` of :meth:`analyze_steady`).
If None, the dry coil on every step. One entry per step (a
list, an array or a Series). Only the cooling steps are read,
each as ``RH_room`` of :meth:`analyze_steady` is: a cooling step
whose entry is not a number in 0-1 raises ``ValueError`` naming
the step; what a heating or an off step holds (a missing value)
is not looked at.
request_basis : str
What the entries of ``Q_r_iu_schedule`` are requests for, on
every step: ``"total"`` (default), the refrigerant-side heat of
the indoor coil, or ``"sensible"``, the net sensible heat
of the room air -- the zone sensible loads of a building
simulation, with its room temperatures and humidities as
``T_a_room_schedule`` and ``RH_room_schedule``
(``request_basis`` of :meth:`analyze_steady`, which solves each
step). Any other value raises ``ValueError``. The argument is
handed to :meth:`analyze_steady` only where it is not
``"total"``: a subclass that overrides :meth:`analyze_steady`
without it runs a total-basis schedule as before, and has to
accept it to run another (Python's ``TypeError`` otherwise).
A run on ``"sensible"`` has one column more,
``request_solves [-]``: the total-basis solves of each step.
Returns
-------
pd.DataFrame
Per-timestep result DataFrame.
Warns
-----
OperatingLimitWarning
Once, at the end of a run in which the compressor was called but
did not run on some step, or ran below the request: the steps by
limit and what they left unserved. The totals are in
``df.attrs["operating_limits"]``
(:func:`tmhp.operating_limits.summarize_operating_limits`).
"""
validate_dynamic(locals())
request_basis = _check_request_basis(request_basis)
time: np.ndarray = np.arange(0, simulation_period_sec, dt_s)
tN: int = len(time)
T0_schedule = np.array(T0_schedule)
Q_r_iu_schedule = np.array(Q_r_iu_schedule, dtype=float)
if len(T0_schedule) != tN:
raise ValueError(f"T0_schedule length ({len(T0_schedule)}) != time length ({tN})")
if len(Q_r_iu_schedule) != tN:
raise ValueError(f"Q_r_iu_schedule length ({len(Q_r_iu_schedule)}) != time length ({tN})")
if T_a_room_schedule is not None:
T_a_room_arr = np.array(T_a_room_schedule, dtype=float)
if len(T_a_room_arr) != tN:
raise ValueError(f"T_a_room_schedule length ({len(T_a_room_arr)}) != tN ({tN})")
else:
T_a_room_arr = np.full(tN, self.T_a_room)
RH_out_arr = None
if RH_out_schedule is not None:
RH_out_arr = np.array(RH_out_schedule, dtype=float)
if len(RH_out_arr) != tN:
raise ValueError(f"RH_out_schedule length ({len(RH_out_arr)}) != tN ({tN})")
# One entry per step, kept as given: only the cooling steps are read,
# each with the check ``RH_room`` gets, so what a heating or an off
# step holds (a missing value, text) is never converted.
RH_room_arr = None
if RH_room_schedule is not None:
RH_room_arr = np.asarray(RH_room_schedule, dtype=object)
if RH_room_arr.ndim != 1:
raise ValueError(
f"RH_room_schedule must hold one entry per step (tN = {tN}), got shape {RH_room_arr.shape}"
)
if len(RH_room_arr) != tN:
raise ValueError(f"RH_room_schedule length ({len(RH_room_arr)}) != tN ({tN})")
self.time = time
self.dt = dt_s
results_data: list[dict] = []
# A total-basis run calls ``analyze_steady`` as it was called before the
# option existed, so a subclass that overrides it without the option
# still runs; only another basis is handed over.
basis = {} if request_basis == REQUEST_BASIS_TOTAL else {"request_basis": request_basis}
# The model does not change during a run: the smallest continuous
# duty of a condition (where the envelope refuses lower speeds) is searched once,
# and so is what the searches of a wet cooling condition find (no row depends on it).
with self._remembering_floors(), self._sharing_wet_points():
for n in tqdm(range(tN), desc="ASHP Simulating"):
t_s: float = time[n]
hr: float = t_s * cu.s2h
Q_r_iu_n: float = Q_r_iu_schedule[n]
T0_n: float = T0_schedule[n]
T_a_room_n: float = T_a_room_arr[n]
# Use analyze_steady for robust calculation and fallback handling
hp_result = self.analyze_steady(
Q_r_iu=Q_r_iu_n,
T0=T0_n,
T_a_room=T_a_room_n,
return_dict=True,
postprocess=False, # Exergy postprocessing applied in bulk at the end
verbose=False, # Suppress warnings during long dynamic loops
RH_out=None if RH_out_arr is None else float(RH_out_arr[n]),
# Read on cooling rows only: heating and off rows have no
# use for it, and whatever stands there is not an error.
RH_room=(
None if RH_room_arr is None or not Q_r_iu_n > 0 else _room_humidity_of_step(RH_room_arr[n], n)
),
**basis,
)
# Add time columns
hp_result["time [s]"] = t_s
hp_result["time [h]"] = hr
results_data.append(hp_result)
results_df: pd.DataFrame = pd.DataFrame(results_data)
results_df = self.postprocess_exergy(results_df)
if result_save_csv_path:
results_df.to_csv(result_save_csv_path, index=False)
return results_df
# =============================================================
# Exergy post-processing
# =============================================================
def _exergy_of_row(self, result: dict) -> dict:
"""``result`` with its exergy variables, as :meth:`postprocess_exergy` gives them for a one-row frame.
A steady point is one row, and filling some fifty columns of a
one-row frame one assignment at a time costs more than the cycle
solve's last step. The row is computed here from the same formulas on
scalars (:func:`_exergy_row`); the keys, their order, the types and the
values are those of ``postprocess_exergy(pd.DataFrame([result])).iloc[0].to_dict()``,
to the last bit. A row that is not of the usual shape -- a value of a
type a frame would treat differently, a missing column the frame
would raise on or skip the exergy for -- goes through the frame.
"""
try:
return _exergy_row(result, self.ref)
except (_NotARow, KeyError):
processed: dict = self.postprocess_exergy(pd.DataFrame([result])).iloc[0].to_dict()
return processed
[docs]
def postprocess_exergy(self, df: pd.DataFrame) -> pd.DataFrame:
"""Compute ASHP-specific exergy variables.
Mirrors ``AirSourceHeatPumpBoiler.postprocess_exergy()``
with adaptations for indoor-unit air exchange.
Pipeline:
1. Refrigerant state-point exergy (CoolProp)
2. Electricity = exergy (compressor, IU fan, OU fan)
3. Air exergy (outdoor unit + indoor unit)
4. HX Carnot exergy (condenser, evaporator)
5. Component-level exergy destruction
6. Exergetic efficiency metrics
The air columns (``X_a_iu_*``, ``X_a_ou_*``) are the thermal exergy
of a dry air stream: heat capacity rate times
``(T - T0) - T0 ln(T / T0)``. A moist-air exergy balance -- a
reference humidity for the dead state, the chemical exergy of the
water vapour, the condensate leaving the coil -- is not modelled. On
a row whose indoor coil removes water (``Q_iu_latent [W]`` > 0) the
refrigerant side of that coil carries the latent heat while the air
side counts the temperature change only, so their difference is not
the coil's exergy destruction (it comes out negative at a low
sensible heat ratio). There ``Xc_iu_hx [W]``, ``X_eff_iu_hx [-]``
and ``X_eff_sys [-]`` are NaN; every other column, the thermal
exergy of the air streams included, is reported as on a dry row. Rows
that remove no water are not touched.
"""
from .enex_functions import (
calc_exergy_flow,
calc_refrigerant_exergy,
convert_electricity_to_exergy,
)
df = df.copy()
# Guard: if T0 [°C] is missing (very defensive), skip
if "T0 [°C]" not in df.columns:
return df
T0_K = cu.C2K(df["T0 [°C]"])
# ── 1. Refrigerant exergy ────────────────────────
if "h_ref_cmp_in [J/kg]" in df.columns:
df = calc_refrigerant_exergy(df, self.ref, T0_K)
else:
return df # OFF-only DataFrame, skip exergy
# ── 2. Electricity = exergy ─────────────────────
df = convert_electricity_to_exergy(df)
# Add indoor fan exergy (electricity = exergy)
if "E_iu_fan [W]" in df.columns:
df["X_iu_fan [W]"] = df["E_iu_fan [W]"]
# ── 3. Air exergy (outdoor unit) ────────────────
if "dV_ou_a [m3/s]" in df.columns and "T_ou_a_in [°C]" in df.columns:
# Same air mass as the cycle solve: density at the coil inlet.
G_a_ou = air_heat_capacity_rate(df["dV_ou_a [m3/s]"].fillna(0), df["T_ou_a_in [°C]"])
Tin_ou = cu.C2K(df["T_ou_a_in [°C]"])
Tmid_ou = cu.C2K(df["T_ou_a_mid [°C]"])
Tout_ou = cu.C2K(df["T_ou_a_out [°C]"]) if "T_ou_a_out [°C]" in df.columns else Tin_ou
df["X_a_ou_in [W]"] = calc_exergy_flow(G_a_ou, Tin_ou, T0_K)
df["X_a_ou_out [W]"] = calc_exergy_flow(G_a_ou, Tout_ou, T0_K)
df["X_a_ou_mid [W]"] = calc_exergy_flow(G_a_ou, Tmid_ou, T0_K)
# ── 3b. Air exergy (indoor unit) ────────────────
if "dV_iu_a [m3/s]" in df.columns and "T_iu_a_in [°C]" in df.columns:
G_a_iu = air_heat_capacity_rate(df["dV_iu_a [m3/s]"].fillna(0), df["T_iu_a_in [°C]"])
Tin_iu = cu.C2K(df["T_iu_a_in [°C]"])
Tmid_iu = cu.C2K(df["T_iu_a_mid [°C]"])
Tout_iu = cu.C2K(df["T_iu_a_out [°C]"]) if "T_iu_a_out [°C]" in df.columns else Tin_iu
df["X_a_iu_in [W]"] = calc_exergy_flow(G_a_iu, Tin_iu, T0_K)
df["X_a_iu_out [W]"] = calc_exergy_flow(G_a_iu, Tout_iu, T0_K)
df["X_a_iu_mid [W]"] = calc_exergy_flow(G_a_iu, Tmid_iu, T0_K)
# ── 4. HX Carnot exergy (mode-aware IU/OU) ─────
# calc_ref_state always uses mode="heating" internally:
# cmp_out → condenser inlet (high-pressure superheated)
# exp_in → condenser outlet (high-pressure subcooled)
# exp_out → evaporator inlet (low-pressure two-phase)
# cmp_in → evaporator outlet (low-pressure superheated)
#
# Mapping to physical units:
# Heating: IU = condenser, OU = evaporator
# Cooling: IU = evaporator, OU = condenser
# The Carnot factor for each location uses the saturation temperature of
# the refrigerant role it plays in the current mode. Output exergy is
# labelled by location (X_ref_iu/X_ref_ou); the refrigerant-state
# saturation keys remain cond/evap (refrigerant-intrinsic).
# The condenser's factor uses the temperature the cycle condenses at,
# the bubble point ``T_ref_cond_sat_l`` -- the value
# ``T_ref_cond_sat_v`` repeated before it reported a zeotrope's dew point.
if {"T_ref_cond_sat_l [°C]", "T_ref_evap_sat [°C]", "mode"} <= set(df.columns):
is_heating = df["mode"] == "heating"
T_iu_sat_K = cu.C2K(df["T_ref_cond_sat_l [°C]"].where(is_heating, df["T_ref_evap_sat [°C]"]))
T_ou_sat_K = cu.C2K(df["T_ref_evap_sat [°C]"].where(is_heating, df["T_ref_cond_sat_l [°C]"]))
df["X_ref_iu [W]"] = df["Q_ref_iu [W]"] * (1 - T0_K / T_iu_sat_K)
df["X_ref_ou [W]"] = df["Q_ref_ou [W]"] * (1 - T0_K / T_ou_sat_K)
# ── 5. Total exergy input ───────────────────────
X_tot = df["E_cmp [W]"] + df["E_ou_fan [W]"].fillna(0) + df["E_iu_fan [W]"].fillna(0)
df["X_tot [W]"] = X_tot
# ── 6. Component exergy destruction (IU/OU naming) ──
# Air exergy helper Series
X_a_ou_in = df.get("X_a_ou_in [W]", pd.Series(0.0, index=df.index)).fillna(0)
X_a_ou_mid = df.get("X_a_ou_mid [W]", pd.Series(0.0, index=df.index)).fillna(0)
X_a_ou_out = df.get("X_a_ou_out [W]", pd.Series(0.0, index=df.index)).fillna(0)
X_a_iu_in = df.get("X_a_iu_in [W]", pd.Series(0.0, index=df.index)).fillna(0)
X_a_iu_mid = df.get("X_a_iu_mid [W]", pd.Series(0.0, index=df.index)).fillna(0)
X_a_iu_out = df.get("X_a_iu_out [W]", pd.Series(0.0, index=df.index)).fillna(0)
if "X_cmp [W]" not in df.columns:
return df
# Mode masks
is_heating = df["mode"] == "heating"
is_cooling = df["mode"] == "cooling"
# ── 6a. Compressor (X_in, Xc, X_out) ──
df["X_in_cmp [W]"] = df["X_cmp [W]"] + df["X_ref_cmp_in [W]"]
df["X_out_cmp [W]"] = df["X_ref_cmp_out [W]"]
df["Xc_cmp [W]"] = df["X_in_cmp [W]"] - df["X_out_cmp [W]"]
# ── 6b. Expansion valve (X_in, Xc, X_out) ──
df["X_in_exp [W]"] = df["X_ref_exp_in [W]"]
df["X_out_exp [W]"] = df["X_ref_exp_out [W]"]
df["Xc_exp [W]"] = df["X_in_exp [W]"] - df["X_out_exp [W]"]
# ── 6c. Indoor Unit HX (mode-aware: X_in, Xc, X_out) ──
# Heating: IU = condenser → ref enters from cmp_out, exits to exp_in
# Cooling: IU = evaporator → ref enters from exp_out, exits to cmp_in
X_in_iu_hx = pd.Series(0.0, index=df.index)
X_out_iu_hx = pd.Series(0.0, index=df.index)
X_in_iu_hx[is_heating] = df.loc[is_heating, "X_ref_cmp_out [W]"] + X_a_iu_in[is_heating]
X_out_iu_hx[is_heating] = df.loc[is_heating, "X_ref_exp_in [W]"] + X_a_iu_mid[is_heating]
X_in_iu_hx[is_cooling] = df.loc[is_cooling, "X_ref_exp_out [W]"] + X_a_iu_in[is_cooling]
X_out_iu_hx[is_cooling] = df.loc[is_cooling, "X_ref_cmp_in [W]"] + X_a_iu_mid[is_cooling]
df["X_in_iu_hx [W]"] = X_in_iu_hx
df["X_out_iu_hx [W]"] = X_out_iu_hx
df["Xc_iu_hx [W]"] = X_in_iu_hx - X_out_iu_hx
# ── 6d. Outdoor Unit HX (mode-aware: X_in, Xc, X_out) ──
# Heating: OU = evaporator → ref enters from exp_out, exits to cmp_in
# Cooling: OU = condenser → ref enters from cmp_out, exits to exp_in
X_in_ou_hx = pd.Series(0.0, index=df.index)
X_out_ou_hx = pd.Series(0.0, index=df.index)
X_in_ou_hx[is_heating] = df.loc[is_heating, "X_ref_exp_out [W]"] + X_a_ou_in[is_heating]
X_out_ou_hx[is_heating] = df.loc[is_heating, "X_ref_cmp_in [W]"] + X_a_ou_mid[is_heating]
X_in_ou_hx[is_cooling] = df.loc[is_cooling, "X_ref_cmp_out [W]"] + X_a_ou_in[is_cooling]
X_out_ou_hx[is_cooling] = df.loc[is_cooling, "X_ref_exp_in [W]"] + X_a_ou_mid[is_cooling]
df["X_in_ou_hx [W]"] = X_in_ou_hx
df["X_out_ou_hx [W]"] = X_out_ou_hx
df["Xc_ou_hx [W]"] = X_in_ou_hx - X_out_ou_hx
# ── 6e. Outdoor fan (X_in, Xc, X_out) ──
df["X_in_ou_fan [W]"] = df["X_ou_fan [W]"].fillna(0) + X_a_ou_mid
df["X_out_ou_fan [W]"] = X_a_ou_out
df["Xc_ou_fan [W]"] = df["X_in_ou_fan [W]"] - df["X_out_ou_fan [W]"]
# ── 6f. Indoor fan (X_in, Xc, X_out) ──
df["X_in_iu_fan [W]"] = df["X_iu_fan [W]"].fillna(0) + X_a_iu_mid
df["X_out_iu_fan [W]"] = X_a_iu_out
df["Xc_iu_fan [W]"] = df["X_in_iu_fan [W]"] - df["X_out_iu_fan [W]"]
# ── 7. Exergetic efficiency metrics ─────────────
# System exergetic efficiency
df["X_eff_sys [-]"] = (X_a_iu_out - X_a_iu_in) / df["X_tot [W]"].replace(0, np.nan)
# Compressor exergetic efficiency
df["X_eff_cmp [-]"] = 1 - df["Xc_cmp [W]"] / df["X_in_cmp [W]"].replace(0, np.nan)
# Expansion valve exergetic efficiency
df["X_eff_exp [-]"] = 1 - df["Xc_exp [W]"] / df["X_in_exp [W]"].replace(0, np.nan)
# Indoor unit HX exergetic efficiency
df["X_eff_iu_hx [-]"] = 1 - df["Xc_iu_hx [W]"] / df["X_in_iu_hx [W]"].replace(0, np.nan)
# Outdoor unit HX exergetic efficiency
df["X_eff_ou_hx [-]"] = 1 - df["Xc_ou_hx [W]"] / df["X_in_ou_hx [W]"].replace(0, np.nan)
# Outdoor fan exergetic efficiency
df["X_eff_ou_fan [-]"] = 1 - df["Xc_ou_fan [W]"] / df["X_in_ou_fan [W]"].replace(0, np.nan)
# Indoor fan exergetic efficiency
df["X_eff_iu_fan [-]"] = 1 - df["Xc_iu_fan [W]"] / df["X_in_iu_fan [W]"].replace(0, np.nan)
# ── 8. A coil that removes water: no indoor-coil balance ──
if "Q_iu_latent [W]" in df.columns:
removes_water = df["Q_iu_latent [W]"] > 0
if removes_water.any():
df.loc[removes_water, list(_NO_MOIST_AIR_BALANCE)] = np.nan
return df
# =============================================================
# Standard-condition check
# =============================================================
[docs]
def operating_range(self, conditions: Iterable[StandardCondition] | None = None) -> pd.DataFrame:
"""Solve standard rating conditions and tabulate whether the heat pump runs at each.
A check to call before a simulation; it is not made at construction
because it solves the cycle at every condition. One row per
condition: whether the compressor runs, delivers the request or a
reduced duty, or cycles on and off, its ``failure_reason``,
``cop_sys [-]``, and the limit in words. No
:class:`~tmhp.OperatingLimitWarning` is issued and the model is not
changed.
Parameters
----------
conditions : iterable of StandardCondition, optional
Conditions to solve; :data:`tmhp.standard_conditions.AIR_TO_AIR`
(A7/20 ... A-15/20 and A35/27 at the nameplate duty) when omitted.
Returns
-------
pd.DataFrame
Columns :data:`tmhp.standard_conditions.COLUMNS`; see
:func:`tmhp.standard_conditions.operating_range`.
"""
return _operating_range(self, "air_to_air", conditions)