Source code for tmhp.dhw

"""
Domestic Hot Water (DHW) load modeling.

Besides the draw-schedule helpers, this module holds the hot-water service
accounting the boiler models share: what a step was asked to deliver, what it
did not deliver (:func:`dhw_service_columns`), the totals of a run
(:func:`summarize_dhw_service`) and the end-of-run warning
(:func:`warn_if_dhw_unmet`).
"""

import math
import warnings

import numpy as np
import pandas as pd

from . import calc_util as cu
from .constants import c_w, rho_w
from .operating_limits import OperatingLimitWarning

__all__ = [
    "DHW_REQUEST_KEY",
    "DHW_SETPOINT_TOL_K",
    "DHW_UNMET_KEY",
    "DHWUnmetWarning",
    "build_dhw_usage_ratio",
    "calc_cold_water_temp",
    "calc_total_water_use_from_schedule",
    "dhw_service_columns",
    "make_dhw_schedule_from_Annex_42_profile",
    "summarize_dhw_service",
    "warn_if_dhw_unmet",
]

DHW_REQUEST_KEY: str = "Q_dhw_request [W]"
"""Result key: hot-water heat a step was asked to deliver [W]."""

DHW_UNMET_KEY: str = "Q_dhw_unmet [W]"
"""Result key: part of ``Q_dhw_request [W]`` a step did not deliver [W]."""

DHW_SETPOINT_TOL_K: float = 0.01
"""Width of the service set point [K].

A delivery whose shortfall is no more than the requested flow cooled by this
much counts as met (``Q_dhw_unmet [W]`` is 0). The mixing valve of a
multi-node tank is set on the outlet temperature by iteration (to 1e-3 K),
and a lumped tank sitting on the set point differs between platforms in the
last digits; neither is a hot-water shortfall. 0.01 K is 0.04 % of a 25 K lift.
"""


[docs] class DHWUnmetWarning(OperatingLimitWarning): """A dynamic run delivered less hot water than its draw schedule asked for. A :class:`tmhp.OperatingLimitWarning` (itself a ``UserWarning``): a filter on that class covers this one together with the warnings about a compressor that did not run or ran below the request. """
[docs] def dhw_service_columns( dV_request: float, dV_delivered: float, T_delivered_K: float, T_set_K: float, T_sup_w_K: float, ) -> dict[str, float]: """Hot-water heat a step was asked for and the part it did not deliver. The request is the scheduled mixed-water flow at the service set point, counted from the mains temperature:: Q_dhw_request = rho·c · dV_request · (T_set − T_sup_w) The delivery is the mixed water that actually left the valve at the temperature it left at, ``rho·c · dV_delivered · (T_delivered − T_sup_w)``, and ``Q_dhw_unmet = Q_dhw_request − delivery`` (never negative). Two things make it positive: - the tank is colder than the set point, so the mixing valve passes tank water unmixed and the water arrives below the set point; - a tank whose level varies stopped the draw at its lowest level, so less water was delivered (``dV_mix_w_out_unmet [m3/s]``). Both are step averages like every other rate in a dynamic result: ``Q_dhw_unmet·dt`` is the step's shortfall in joules. A shortfall within :data:`DHW_SETPOINT_TOL_K` of the set point is reported as 0. Parameters ---------- dV_request : float Mixed-water flow the draw schedule asks for [m³/s]. dV_delivered : float Mixed-water flow that left the mixing valve [m³/s]. T_delivered_K : float Temperature of the delivered water [K]; unused when nothing was delivered. T_set_K : float Service set point of the mixing valve [K]. T_sup_w_K : float Mains water temperature [K]. Returns ------- dict[str, float] ``{"Q_dhw_request [W]": ..., "Q_dhw_unmet [W]": ...}``. Both are 0 on a step without a draw, and when the mains water is already at the set point (nothing to heat). """ rc = c_w * rho_w request = max(0.0, rc * max(0.0, float(dV_request)) * (T_set_K - T_sup_w_K)) delivered = 0.0 if dV_delivered > 0.0 and math.isfinite(T_delivered_K): delivered = max(0.0, rc * float(dV_delivered) * (min(T_delivered_K, T_set_K) - T_sup_w_K)) unmet = max(0.0, request - delivered) if unmet <= rc * max(0.0, float(dV_request)) * DHW_SETPOINT_TOL_K: unmet = 0.0 return {DHW_REQUEST_KEY: request, DHW_UNMET_KEY: unmet}
[docs] def summarize_dhw_service(df: pd.DataFrame, dt_s: float) -> dict[str, float]: """Hot-water service totals of a dynamic result. Parameters ---------- df : pd.DataFrame Result of a boiler ``analyze_dynamic`` (or rows of ``step``) carrying ``Q_dhw_request [W]`` and ``Q_dhw_unmet [W]``. dt_s : float Time step of the result [s]. Returns ------- dict[str, float] - ``Q_dhw_request [kWh]``: heat the draw schedule asked for; - ``Q_dhw_delivered [kWh]``: heat delivered (request less unmet); - ``Q_dhw_unmet [kWh]``: heat not delivered; - ``dhw_unmet_fraction [-]``: unmet / request (0 without a request); - ``dhw_draw_steps [-]``: steps with a draw request; - ``dhw_unmet_steps [-]``: steps with ``Q_dhw_unmet [W] > 0``; - ``T_mix_w_out_min [°C]``: lowest delivered temperature on a step with a draw (NaN without a draw or without the column). Raises ------ KeyError If ``df`` does not carry the two hot-water columns. """ missing = [key for key in (DHW_REQUEST_KEY, DHW_UNMET_KEY) if key not in df.columns] if missing: raise KeyError(f"summarize_dhw_service: result has no {missing} (a boiler dynamic result is expected)") request = np.nan_to_num(pd.to_numeric(df[DHW_REQUEST_KEY], errors="coerce").to_numpy(dtype=float)) unmet = np.nan_to_num(pd.to_numeric(df[DHW_UNMET_KEY], errors="coerce").to_numpy(dtype=float)) to_kwh = float(dt_s) / 3.6e6 request_kwh = float(request.sum()) * to_kwh unmet_kwh = float(unmet.sum()) * to_kwh drawing = request > 0.0 T_min = math.nan if drawing.any() and "T_mix_w_out [°C]" in df.columns: T_mix = pd.to_numeric(df["T_mix_w_out [°C]"], errors="coerce").to_numpy(dtype=float)[drawing] if np.isfinite(T_mix).any(): T_min = float(np.nanmin(T_mix)) return { "Q_dhw_request [kWh]": request_kwh, "Q_dhw_delivered [kWh]": request_kwh - unmet_kwh, "Q_dhw_unmet [kWh]": unmet_kwh, "dhw_unmet_fraction [-]": unmet_kwh / request_kwh if request_kwh > 0.0 else 0.0, "dhw_draw_steps [-]": int(drawing.sum()), "dhw_unmet_steps [-]": int((unmet > 0.0).sum()), "T_mix_w_out_min [°C]": T_min, }
[docs] def warn_if_dhw_unmet(df: pd.DataFrame, dt_s: float, who: str, T_set_C: float) -> None: """Warn once (:class:`DHWUnmetWarning`) if a run left hot-water demand unmet. Called at the end of each boiler ``analyze_dynamic``. Silent when every draw was delivered at the set point, and on frames without the hot-water columns. """ if DHW_REQUEST_KEY not in df.columns or DHW_UNMET_KEY not in df.columns: return s = summarize_dhw_service(df, dt_s) if s["dhw_unmet_steps [-]"] == 0: return coldest = s["T_mix_w_out_min [°C]"] coldest_txt = f"; coldest delivery {coldest:.1f} °C" if math.isfinite(coldest) else "" warnings.warn( f"{who}: hot-water demand was not fully met on {s['dhw_unmet_steps [-]']} of " f"{s['dhw_draw_steps [-]']} draw steps: {s['Q_dhw_unmet [kWh]']:.2f} kWh of " f"{s['Q_dhw_request [kWh]']:.2f} kWh requested ({100.0 * s['dhw_unmet_fraction [-]']:.1f} %) " f"was not delivered at the {T_set_C:.0f} °C set point{coldest_txt}. " "See 'Q_dhw_unmet [W]' per step and tmhp.dhw.summarize_dhw_service(df, dt_s).", DHWUnmetWarning, stacklevel=3, )
def _schedule_time(seconds: int) -> str: """Format a daily schedule boundary, adding seconds only between whole minutes.""" hours, within_hour = divmod(seconds, cu.h2s) minutes, remainder = divmod(within_hour, cu.m2s) return f"{hours:02d}:{minutes:02d}" + (f":{remainder:02d}" if remainder else "") def _schedule_seconds(time_str: str) -> float: """Convert hours with optional minute and second fields to seconds from midnight.""" parts = time_str.split(":") hours = float(parts[0]) minutes = float(parts[1]) if len(parts) > 1 else 0.0 seconds = float(parts[2]) if len(parts) > 2 else 0.0 return hours * cu.h2s + minutes * cu.m2s + seconds
[docs] def make_dhw_schedule_from_Annex_42_profile( flow_rate_array: np.ndarray, df_time_step: int, simulation_time_step: int ) -> list[tuple[str, str, float]]: """Generate DHW schedule list from flow profile data. Treat each input rate as constant over its sample interval. Each output fraction is the time-weighted mean rate over the interval divided by the profile peak. The last interval ends at midnight, even for a step that does not divide the day. Parameters ---------- flow_rate_array : np.ndarray One day of finite, nonnegative flow rates [L/min]. df_time_step : int Time step of the input ``flow_rate_array`` [min]. simulation_time_step : int Positive whole-second time step for the simulation schedule [s]. Returns ------- list[tuple[str, str, float]] Nonzero intervals as tuples (start_time, end_time, fraction). Times include seconds for boundaries that do not fall on a whole minute. Raises ------ ValueError If the profile is not a day of finite, nonnegative rates or the target step is not a positive whole number of seconds. """ flow_rate_array = np.asarray(flow_rate_array, dtype=float) if flow_rate_array.ndim != 1 or not np.all(np.isfinite(flow_rate_array)) or np.any(flow_rate_array < 0): raise ValueError("Input profile must be a one-dimensional array of finite nonnegative flow rates") # NumPy integer scalars can overflow in both the day-length and seconds calculations. sample_minutes = float(df_time_step) total_minutes = len(flow_rate_array) * sample_minutes if total_minutes != 1440: raise ValueError(f"Input profile must cover exactly 24 hours (got {total_minutes} min)") if ( not np.isfinite(simulation_time_step) or simulation_time_step <= 0 or simulation_time_step != int(simulation_time_step) ): raise ValueError("simulation_time_step must be a positive whole number of seconds") peak_flow = flow_rate_array.max() if peak_flow == 0.0: return [] source_seconds = sample_minutes * cu.m2s source_edges = np.arange(len(flow_rate_array) + 1) * source_seconds target_edges = np.append(np.arange(0, cu.d2s, min(int(simulation_time_step), cu.d2s)), cu.d2s) # The integral of a piecewise-constant rate is linear between source edges. cumulative = np.append(0.0, np.cumsum(flow_rate_array / peak_flow)) * source_seconds at_edges = np.interp(target_edges, source_edges, cumulative) fractions = np.clip(np.diff(at_edges) / np.diff(target_edges), 0.0, 1.0) return [ (_schedule_time(int(start)), _schedule_time(int(end)), float(frac)) for start, end, frac in zip(target_edges[:-1], target_edges[1:], fractions, strict=True) if frac > 0.0 ]
[docs] def calc_total_water_use_from_schedule( schedule: list[tuple[str, str, float]], peak_load_m3s: float, info: bool = True, info_unit: str = "L", ) -> float: """Calculate total daily water use from a schedule. Parameters ---------- schedule : list[tuple[str, str, float]] Schedule list. Each item is (start_str, end_str, ratio) with times in hours, hours:minutes or hours:minutes:seconds. peak_load_m3s : float Peak load water flow rate [m3/s]. info : bool, optional Flag to print info. Default is True. info_unit : str, optional Unit to print info. Default is 'L'. Returns ------- float Total daily water usage [m3]. """ total_m3 = 0.0 for start, end, frac in schedule: dt_s = _schedule_seconds(end) - _schedule_seconds(start) total_m3 += peak_load_m3s * frac * dt_s if info: if info_unit == "L": print(f"Total water use: {total_m3 * cu.m32L:.1f} L/day") else: print(f"Total water use: {total_m3:.3f} m3/day") return total_m3
[docs] def calc_cold_water_temp(df: pd.DataFrame, target_date_str: str, *, latitude: float | None = None) -> float: """Mains water temperature [°C] by the EnergyPlus ``Site:WaterMainsTemperature`` correlation. The correlation of Burch & Christensen (NREL; Hendron et al. 2004) as EnergyPlus evaluates it (Engineering Reference, "Water Mains Temperatures"; ``WaterMainsTempFromCorrelation`` in ``WeatherManager.cc``). It is fitted in °F, so the inputs are converted to °F, the correlation is evaluated there and the result converted back:: T_mains = (T_avg + 6) + ratio · (ΔT_max / 2) · sin(0.986·(day − 15 − lag) − 90) ratio = 0.4 + 0.01·(T_avg − 44) lag = 35 − 1.0·(T_avg − 44) in °F with the sine argument in degrees, ``T_avg`` the annual mean outdoor temperature and ``ΔT_max`` the spread (max − min) of the monthly mean outdoor temperatures. The result is not allowed below 32 °F (0 °C). South of the equator the seasonal term changes sign, as in EnergyPlus. References ---------- Hendron, R., Anderson, R., Christensen, C., Eastment, M., & Reeves, P. (2004). Development of an Energy Savings Benchmark for All Residential End-Uses. SimBuild 2004, IBPSA-USA. EnergyPlus Engineering Reference, Water Systems. Parameters ---------- df : pd.DataFrame The twelve monthly mean outdoor temperatures [°C] in a column whose name contains ``T_avg`` (or ``기온``, ``temp``, ``T0``, ``°C``, ``℃``). target_date_str : str Target date string in 'YYYY-MM-DD' format. latitude : float | None Site latitude [°]; negative flips the season. ``None``: northern hemisphere. Returns ------- float Mains water temperature [°C]. """ # Dynamic temperature-column lookup. The Korean keywords ('기온') are kept # so KMA (Korea Meteorological Administration) CSVs match out of the box # alongside English column names (T_avg, temp, T0, °C, ℃). _TEMP_PATTERNS = ["t_avg", "기온", "temp", "t0", "°c", "℃"] temp_col: str | None = None for pat in _TEMP_PATTERNS: matched = df.columns[df.columns.str.lower().str.contains(pat.lower())] if len(matched) > 0: temp_col = str(matched[0]) break if temp_col is None: raise ValueError( f"calc_cold_water_temp: could not find a temperature column. " f"Columns present: {df.columns.tolist()}. " f"A column whose name contains one of " f"{_TEMP_PATTERNS} is required." ) monthly = df[temp_col].astype(float) T_avg_F = monthly.mean() * 9.0 / 5.0 + 32.0 dT_max_F = (monthly.max() - monthly.min()) * 9.0 / 5.0 day_of_year = pd.to_datetime(target_date_str).dayofyear ratio = 0.4 + 0.01 * (T_avg_F - 44.0) lag = 35.0 - 1.0 * (T_avg_F - 44.0) hemisphere = -1.0 if latitude is not None and latitude < 0 else 1.0 T_mains_F = (T_avg_F + 6.0) + ratio * (dT_max_F / 2.0) * hemisphere * np.sin( np.radians(0.986 * (day_of_year - 15.0 - lag) - 90.0) ) T_mains_F = max(32.0, float(T_mains_F)) return (T_mains_F - 32.0) * 5.0 / 9.0
[docs] def build_dhw_usage_ratio(entries: list[tuple[str, str, float]], t_array: np.ndarray) -> np.ndarray: """Build schedule ratio array from schedule entries for each timestep. Parameters ---------- entries : list[tuple[str, str, float]] Schedule entry list. Each item is (start_str, end_str, frac) with times in hours, hours:minutes or hours:minutes:seconds. t_array : np.ndarray Array of time seconds from start of day. Returns ------- np.ndarray Array of fractions corresponding to ``t_array``. """ ratio = np.zeros_like(t_array, dtype=float) for start, end, frac in entries: s_sec = _schedule_seconds(start) e_sec = _schedule_seconds(end) mask = (t_array >= s_sec) & (t_array < e_sec) ratio[mask] = np.maximum(ratio[mask], frac) return ratio