Subsystems

Composable subsystems that the *_stc_* and *_pv_ess model variants plug onto the core cycle, tank backends, plus the UV-treatment subsystem.

Solar thermal collector

class tmhp.subsystems.SolarThermalCollector(A_stc=2.0, stc_tilt=35.0, stc_azimuth=180.0, A_stc_pipe=None, alpha_stc=None, h_o_stc=None, h_r_stc=None, k_ins_stc=None, x_air_stc=None, x_ins_stc=None, preheat_start_hour=6.0, preheat_end_hour=18.0, dV_stc_w=None, E_stc_pump=50.0, eta0_stc=0.78, a1_stc=3.6, a2_stc=0.015, b0_stc=0.1, K_d_stc=None, dT_stc_on=6.0, dT_stc_off=2.0, T_stc_tank_max=85.0, T_stc_boil=100.0, latitude=37.57, longitude=126.98, utc_offset_h=9.0, start_time=None, albedo=0.2, sky_model='perez', T_stc_freeze=4.0, T_stc_lockout=130.0)[source]

Bases: _SunFacingSurface

Glazed solar thermal collector (STC) — pure physics engine.

Bundles the collector (area, orientation, ISO 9806 efficiency), its loop pump and controller settings, and the site and clock used for the sun position. This class is a stateless physics calculator: given the irradiance, the inlet and ambient temperatures and the flow it returns a performance dict. Activation and routing are the scenario classes’ job.

Thermal model

Quasi-steady collector efficiency of ISO 9806 / EN 12975 on the mean fluid temperature T_m = (T_in + T_out)/2:

Q_u = A·[η0·(K_b·G_b + K_d·G_d) − a1·(T_m − T_a) − a2·(T_m − T_a)·|T_m − T_a|]
Q_u = ṁ·c_p·(T_out − T_in)

solved in closed form for T_out. G_b / G_d are the beam and diffuse (sky + ground-reflected) irradiance on the collector plane, transposed from I_DN / I_dH with the sun position of the step (plane_irradiance()); K_b = 1 − b0·(1/cos θ − 1) is the ASHRAE incidence-angle modifier and K_d the diffuse one (Brandemuehl–Beckman equivalent angles of b0 unless K_d_stc is given). T_a is the outdoor temperature T0. Q_sol_stc = A·η0·(K_b·G_b + K_d·G_d) is the heat absorbed (after optical losses) and the balance Q_sol_stc = (Q_stc_w_out − Q_stc_w_in) + Q_l_stc closes exactly. The absolute-value form of the quadratic term keeps the loss odd in T_m − T_a.

The defaults describe a representative single-glazed selective flat-plate collector (Solar Keymark range η0 0.75–0.82, a1 3–4 W/(m²·K), a2 0.01–0.02 W/(m²·K²), b0 ≈ 0.1); its stagnation temperature at 1000 W/m² and 30 °C ambient is about 170 °C. Take eta0_stc, a1_stc, a2_stc and b0_stc (or K_d_stc) from a collector datasheet together with the area they refer to.

param A_stc:

Collector area [m²] that the efficiency coefficients refer to (aperture or gross, as on the datasheet). Absorption, losses and the default flow scale with it.

type A_stc:

float

param stc_tilt:

Tilt from horizontal [°].

type stc_tilt:

float

param stc_azimuth:

Azimuth of the collector normal, clockwise from north [°] (180 = south).

type stc_azimuth:

float

param A_stc_pipe:

Deprecated alias of A_stc (it used to be the only area in the heat balance).

type A_stc_pipe:

float | None

param alpha_stc:

Deprecated construction parameters of the former lumped model. alpha_stc becomes eta0_stc; the others give the linear loss coefficient a1_stc of that model (with a2_stc = 0).

type alpha_stc:

float | None

param h_o_stc:

Deprecated construction parameters of the former lumped model. alpha_stc becomes eta0_stc; the others give the linear loss coefficient a1_stc of that model (with a2_stc = 0).

type h_o_stc:

float | None

param h_r_stc:

Deprecated construction parameters of the former lumped model. alpha_stc becomes eta0_stc; the others give the linear loss coefficient a1_stc of that model (with a2_stc = 0).

type h_r_stc:

float | None

param k_ins_stc:

Deprecated construction parameters of the former lumped model. alpha_stc becomes eta0_stc; the others give the linear loss coefficient a1_stc of that model (with a2_stc = 0).

type k_ins_stc:

float | None

param x_air_stc:

Deprecated construction parameters of the former lumped model. alpha_stc becomes eta0_stc; the others give the linear loss coefficient a1_stc of that model (with a2_stc = 0).

type x_air_stc:

float | None

param x_ins_stc:

Deprecated construction parameters of the former lumped model. alpha_stc becomes eta0_stc; the others give the linear loss coefficient a1_stc of that model (with a2_stc = 0).

type x_ins_stc:

float | None

param preheat_start_hour:

Clock window [h] in which the collector may run, used by the preheat, ground and routed scenarios (the tank-loop scenarios are governed by their controller only).

type preheat_start_hour:

float

param preheat_end_hour:

Clock window [h] in which the collector may run, used by the preheat, ground and routed scenarios (the tank-loop scenarios are governed by their controller only).

type preheat_end_hour:

float

param dV_stc_w:

Collector-loop flow [m³/s] of the pumped loops. None (default): the ISO 9806 test flow, 0.02 kg/(s·m²) × A_stc. The mains preheat scenario runs the collector at the tank feed instead.

type dV_stc_w:

float | None

param E_stc_pump:

Collector-loop pump power [W] while it runs.

type E_stc_pump:

float

param eta0_stc:

Zero-loss efficiency η0 [-] (normal incidence).

type eta0_stc:

float

param a1_stc:

First-order heat-loss coefficient [W/(m²·K)].

type a1_stc:

float

param a2_stc:

Second-order heat-loss coefficient [W/(m²·K²)].

type a2_stc:

float

param b0_stc:

ASHRAE incidence-angle-modifier coefficient [-].

type b0_stc:

float

param K_d_stc:

Diffuse incidence-angle modifier [-]; None derives it from b0_stc.

type K_d_stc:

float | None

param dT_stc_on:

Differential controller [K]: a stopped pump starts when the idle collector is dT_stc_on above the sink (and the run would hold), a running pump runs on while its outlet stays dT_stc_off above it.

type dT_stc_on:

float

param dT_stc_off:

Differential controller [K]: a stopped pump starts when the idle collector is dT_stc_on above the sink (and the run would hold), a running pump runs on while its outlet stays dT_stc_off above it.

type dT_stc_off:

float

param T_stc_tank_max:

Storage high limit [°C]: the collector loop stops charging the tank at this temperature (within the step) and starts again once the tank is 2 K below it.

type T_stc_tank_max:

float

param T_stc_boil:

Boiling protection [°C]: the loop does not run when the collector outlet would reach this temperature.

type T_stc_boil:

float

param latitude:

Site [°], north and east positive. Default Seoul.

type latitude:

float

param longitude:

Site [°], north and east positive. Default Seoul.

type longitude:

float

param utc_offset_h:

Local standard time offset from UTC [h] of the run’s clock. Default 9 (KST).

type utc_offset_h:

float

param start_time:

Local standard time of simulation second 0 (anything pandas.Timestamp accepts; an aware timestamp is converted). None: 00:00 on 20 March (the equinox, a year-average sun path). The boilers count their hour of day from second 0, so a run starting at local midnight keeps their schedules and the sun in step.

type start_time:

object

param albedo:

Ground reflectance [-].

type albedo:

float

param sky_model:

Sky-diffuse transposition: "perez" (default), "haydavies" or "isotropic".

type sky_model:

str

param T_stc_freeze:

Freeze protection [°C]. The collector carries water (tank or mains water), so it is a drain-back system: while the idle collector (stagnation_temperature_K()) is below this temperature the loop does not run and the collector is drained (stc_freeze_protected [-]); nor does a pumped loop run while the sink it would draw from is below 0 °C. Default 4 °C; None switches the protection off (a loop filled with antifreeze).

type T_stc_freeze:

float | None

param T_stc_lockout:

Collector lock-out after stagnation [°C]. A pumped loop that a protection holds off (storage limit, boiling protection, clock window) while its idle collector is at or above this temperature is not started until the collector has cooled 10 K below it (stc_stagnation_lockout [-]): cold water must not be pumped into an absorber far above its boiling point. Default 130 °C; None switches the lock-out off.

type T_stc_lockout:

float | None

A_stc: float = 2.0
stc_tilt: float = 35.0
stc_azimuth: float = 180.0
A_stc_pipe: float | None = None
alpha_stc: float | None = None
h_o_stc: float | None = None
h_r_stc: float | None = None
k_ins_stc: float | None = None
x_air_stc: float | None = None
x_ins_stc: float | None = None
preheat_start_hour: float = 6.0
preheat_end_hour: float = 18.0
dV_stc_w: float | None = None
E_stc_pump: float = 50.0
eta0_stc: float = 0.78
a1_stc: float = 3.6
a2_stc: float = 0.015
b0_stc: float = 0.1
K_d_stc: float | None = None
dT_stc_on: float = 6.0
dT_stc_off: float = 2.0
T_stc_tank_max: float = 85.0
T_stc_boil: float = 100.0
latitude: float = 37.57
longitude: float = 126.98
utc_offset_h: float = 9.0
start_time: object = None
albedo: float = 0.2
sky_model: str = 'perez'
T_stc_freeze: float | None = 4.0
T_stc_lockout: float | None = 130.0
property loop_flow: float

Collector-loop flow of the pumped loops [m³/s] (dV_stc_w or the ISO test flow).

calc_overall_heat_transfer_coeff()[source]

Linear heat-loss coefficient a1_stc [W/(m²·K)] (kept for the former API).

Return type:

float

incidence_modifiers(aoi_deg)[source]

Beam, sky-diffuse and ground-diffuse incidence-angle modifiers [-].

Parameters:

aoi_deg (float)

Return type:

tuple[float, float, float]

absorbed_irradiance(plane)[source]

Irradiance the absorber turns into heat, η0·(K_b·G_b + K_d·G_d) [W/m²].

Parameters:

plane (dict)

Return type:

float

stagnation_temperature_K(plane, T0_K)[source]

Absorber temperature with no flow [K] (all absorbed heat lost).

Parameters:
  • plane (dict)

  • T0_K (float)

Return type:

float

calc_performance(I_DN_stc, I_dH_stc, T_stc_w_in_K, T0_K, dV_stc=None, is_active=True, *, time_s=None, plane=None)[source]

Compute STC thermal performance for one timestep.

Parameters:
  • I_DN_stc (float) – Direct-normal irradiance [W/m²].

  • I_dH_stc (float) – Diffuse-horizontal irradiance [W/m²].

  • T_stc_w_in_K (float) – Inlet water temperature [K].

  • T0_K (float) – Outdoor (ambient and dead-state) temperature [K].

  • dV_stc (float | None) – Flow through the collector [m³/s]; defaults to loop_flow.

  • is_active (bool) – If False (no flow), the flow terms are NaN; the plane irradiance and the stagnation temperature are still reported.

  • time_s (float | None) – Time after start_time [s] at which the sun is placed.

  • plane (dict | None) – Precomputed plane_irradiance() (takes precedence over time_s; the scenario classes compute it once per step).

Returns:

I_sol_stc (irradiance on the collector plane [W/m²]), Q_sol_stc (absorbed), S_sol_stc, X_sol_stc, Q_stc_w_in, Q_stc_w_out, Q_stc_pump_w_out, T_stc_w_out_K, T_stc_pump_w_out_K, T_stc_w_in_K, T_stc_K (mean fluid temperature), Q_l_stc, eta_stc, aoi_stc, T_stc_stag_K and the plane components G_stc_beam / G_stc_sky / G_stc_ground.

Return type:

dict

is_preheat_on(hour_of_day)[source]

Check whether hour_of_day falls in the window.

Parameters:

hour_of_day (float) – Hour within the day (0–24).

Return type:

bool

__init__(A_stc=2.0, stc_tilt=35.0, stc_azimuth=180.0, A_stc_pipe=None, alpha_stc=None, h_o_stc=None, h_r_stc=None, k_ins_stc=None, x_air_stc=None, x_ins_stc=None, preheat_start_hour=6.0, preheat_end_hour=18.0, dV_stc_w=None, E_stc_pump=50.0, eta0_stc=0.78, a1_stc=3.6, a2_stc=0.015, b0_stc=0.1, K_d_stc=None, dT_stc_on=6.0, dT_stc_off=2.0, T_stc_tank_max=85.0, T_stc_boil=100.0, latitude=37.57, longitude=126.98, utc_offset_h=9.0, start_time=None, albedo=0.2, sky_model='perez', T_stc_freeze=4.0, T_stc_lockout=130.0)
Parameters:
  • A_stc (float)

  • stc_tilt (float)

  • stc_azimuth (float)

  • A_stc_pipe (float | None)

  • alpha_stc (float | None)

  • h_o_stc (float | None)

  • h_r_stc (float | None)

  • k_ins_stc (float | None)

  • x_air_stc (float | None)

  • x_ins_stc (float | None)

  • preheat_start_hour (float)

  • preheat_end_hour (float)

  • dV_stc_w (float | None)

  • E_stc_pump (float)

  • eta0_stc (float)

  • a1_stc (float)

  • a2_stc (float)

  • b0_stc (float)

  • K_d_stc (float | None)

  • dT_stc_on (float)

  • dT_stc_off (float)

  • T_stc_tank_max (float)

  • T_stc_boil (float)

  • latitude (float)

  • longitude (float)

  • utc_offset_h (float)

  • start_time (object)

  • albedo (float)

  • sky_model (str)

  • T_stc_freeze (float | None)

  • T_stc_lockout (float | None)

Photovoltaic system

class tmhp.subsystems.PhotovoltaicSystem(A_pv=5.0, alp_pv=0.9, pv_tilt=35.0, pv_azimuth=180.0, h_o=15.0, eta_pv=0.15, beta_pv=0.0045, T_ref_pv_K=298.15, eta_ctrl=0.95, T_ctrl_K=308.15, b0_pv=0.05, latitude=37.57, longitude=126.98, utc_offset_h=9.0, start_time=None, albedo=0.2, sky_model='perez')[source]

Bases: _SunFacingSurface

Photovoltaic System (PV + Charge Controller) — pure physics engine.

Computes PV energy generation from irradiance inputs. This class is a stateless physics calculator: given physical inputs it returns a performance dict. All routing logic (ESS charge/discharge, Grid import, dump) is the responsibility of the scenario class.

The array sees the irradiance on its own plane (A_pv, pv_tilt, pv_azimuth), transposed from I_DN / I_dH with the sun position of the step (plane_irradiance(); site and clock as for SolarThermalCollector), less the reflection at the module glass (ASHRAE incidence-angle modifier b0_pv, 0.05 as pvlib’s default).

The public API:

Parameters:
  • A_pv (float)

  • alp_pv (float)

  • pv_tilt (float)

  • pv_azimuth (float)

  • h_o (float)

  • eta_pv (float)

  • beta_pv (float)

  • T_ref_pv_K (float)

  • eta_ctrl (float)

  • T_ctrl_K (float)

  • b0_pv (float)

  • latitude (float)

  • longitude (float)

  • utc_offset_h (float)

  • start_time (object)

  • albedo (float)

  • sky_model (str)

A_pv: float = 5.0
alp_pv: float = 0.9
pv_tilt: float = 35.0
pv_azimuth: float = 180.0
h_o: float = 15.0
eta_pv: float = 0.15
beta_pv: float = 0.0045
T_ref_pv_K: float = 298.15
eta_ctrl: float = 0.95
T_ctrl_K: float = 308.15
b0_pv: float = 0.05
latitude: float = 37.57
longitude: float = 126.98
utc_offset_h: float = 9.0
start_time: object = None
albedo: float = 0.2
sky_model: str = 'perez'
calc_performance(I_DN, I_dH, T0_K, *, time_s=None, plane=None)[source]

Compute PV generation for one timestep.

Parameters:
  • I_DN (float) – Direct-normal irradiance [W/m²].

  • I_dH (float) – Diffuse-horizontal irradiance [W/m²].

  • T0_K (float) – Dead-state (ambient) temperature [K].

  • time_s (float | None) – Time after start_time [s] at which the sun is placed.

  • plane (dict | None) – Precomputed plane_irradiance() (takes precedence).

Returns:

Keys: I_sol_pv (irradiance on the array plane), I_eff_pv (after the incidence-angle modifier), T_pv_K, eta_pv, E_pv_out, E_ctrl_out, Q_l_pv, Q_l_ctrl, X_sol, X_pv_out, X_ctrl_out, X_c_pv, X_c_ctrl, X_l_pv, X_l_ctrl.

Return type:

dict

__init__(A_pv=5.0, alp_pv=0.9, pv_tilt=35.0, pv_azimuth=180.0, h_o=15.0, eta_pv=0.15, beta_pv=0.0045, T_ref_pv_K=298.15, eta_ctrl=0.95, T_ctrl_K=308.15, b0_pv=0.05, latitude=37.57, longitude=126.98, utc_offset_h=9.0, start_time=None, albedo=0.2, sky_model='perez')
Parameters:
  • A_pv (float)

  • alp_pv (float)

  • pv_tilt (float)

  • pv_azimuth (float)

  • h_o (float)

  • eta_pv (float)

  • beta_pv (float)

  • T_ref_pv_K (float)

  • eta_ctrl (float)

  • T_ctrl_K (float)

  • b0_pv (float)

  • latitude (float)

  • longitude (float)

  • utc_offset_h (float)

  • start_time (object)

  • albedo (float)

  • sky_model (str)

Energy storage system

class tmhp.subsystems.EnergyStorageSystem(C_ess_max=3600000.0, SOC_init=0.0, SOC_min=0.1, SOC_max=1.0, eta_ess_chg=0.9, eta_ess_dis=0.9, T_ess_K=313.15)[source]

Bases: object

Energy Storage System (Battery) — pure physics engine.

Accepts charging / discharging requests (DC power, [W]) and enforces capacity and SOC limits. Internal losses and exergy destruction are computed from round-trip efficiencies.

State (SOC_ess) is updated in-place at each call to charge() or discharge(). Routing decisions (which request to fulfil and in what order) are entirely the responsibility of the scenario class.

The state is part of the run, not of the model: the scenario classes call reset() when a run starts, so a second analyze_dynamic on the same model starts from SOC_init again. Do not share one instance between models that are stepped at the same time.

Energy bookkeeping per call (E are DC powers at the battery terminals, C = C_ess_max):

charge:     C·ΔSOC/dt =  η_chg · E_ess_chg
discharge:  C·ΔSOC/dt = -E_ess_dis / η_dis
Q_l_ess     = (1 - η_chg)·E_ess_chg + (1/η_dis - 1)·E_ess_dis

so E_ess_chg - E_ess_dis = C·ΔSOC/dt + Q_l_ess. A state of charge outside [SOC_min, SOC_max] is never moved toward the band by a call (a battery that starts below SOC_min cannot discharge, but it is not topped up for free either).

Parameters:
  • C_ess_max (float) – Rated energy capacity [J]. Default 3.6 MJ (= 1 kWh).

  • SOC_init (float) – Initial state of charge [–].

  • SOC_min (float) – Minimum allowable SOC [–] (depth-of-discharge guard).

  • SOC_max (float) – Maximum allowable SOC [–].

  • eta_ess_chg (float) – Charging efficiency (electricity-in to stored) [–].

  • eta_ess_dis (float) – Discharging efficiency (stored to electricity-out) [–].

  • T_ess_K (float) – Representative battery temperature used for entropy calc [K].

C_ess_max: float = 3600000.0
SOC_init: float = 0.0
SOC_min: float = 0.1
SOC_max: float = 1.0
eta_ess_chg: float = 0.9
eta_ess_dis: float = 0.9
T_ess_K: float = 313.15
SOC_ess: float
reset()[source]

Restore the state of charge to SOC_init (start of a run).

Return type:

None

charge(E_req_chg, dt, T0_K)[source]

Request to charge the ESS with E_req_chg [W] for dt [s].

Returns a dict with keys E_ess_chg, E_ess_dis, SOC_ess plus Q_l_ess (charging loss [W]) and exergy keys.

Parameters:
  • E_req_chg (float)

  • dt (float)

  • T0_K (float)

Return type:

dict

discharge(E_req_dis, dt, T0_K)[source]

Request to discharge E_req_dis [W] from the ESS for dt [s].

Returns a dict with keys E_ess_dis (actual), E_ess_chg, SOC_ess plus Q_l_ess (discharging loss [W]) and exergy keys.

Parameters:
  • E_req_dis (float)

  • dt (float)

  • T0_K (float)

Return type:

dict

__init__(C_ess_max=3600000.0, SOC_init=0.0, SOC_min=0.1, SOC_max=1.0, eta_ess_chg=0.9, eta_ess_dis=0.9, T_ess_K=313.15)
Parameters:
  • C_ess_max (float)

  • SOC_init (float)

  • SOC_min (float)

  • SOC_max (float)

  • eta_ess_chg (float)

  • eta_ess_dis (float)

  • T_ess_K (float)

UV lamp

class tmhp.subsystems.UVLamp(lamp_watts=0.0, exposure_sec=0.0, num_switching=1, period_sec=10800, heat_to_water_fraction=0.9)[source]

Bases: object

UV disinfection lamp subsystem.

The lamp switches on periodically (num_switching times per period_sec, each for exposure_sec, evenly spaced). Each step reports the lamp’s step-average power, the switching schedule integrated over the step (tmhp.uv_treatment.calc_uv_lamp_energy()), so the energy does not depend on the time step.

Heat: heat_to_water_fraction of the lamp power ends up in the tank water. A low-pressure mercury lamp in a quartz sleeve inside the tank turns about a third of its input into 254 nm UV-C and the rest into heat and visible light; the water and the tank wall absorb all of it. Its ballast (electronic, about 90 % efficient) sits in the control box outside the tank, so the default is 0.9. Set 1.0 for a lamp and ballast both inside the tank boundary.

Step protocol: E_subsystem is the lamp’s electric power; the tank balance adds it as heat, and Q_contribution = -(1 - fraction)·E_uv takes off the part that leaves the tank boundary, so the tank gains fraction·E_uv once.

Parameters:
  • lamp_watts (float) – Rated lamp power [W].

  • exposure_sec (float) – Duration of each on-cycle [s].

  • num_switching (int) – Number of on-cycles per period.

  • period_sec (float) – Switching period [s] (default 3 h = 10 800 s).

  • heat_to_water_fraction (float) – Share of the lamp’s electric power that heats the tank water [-].

lamp_watts: float = 0.0
exposure_sec: float = 0.0
num_switching: int = 1
period_sec: float = 10800
heat_to_water_fraction: float = 0.9
step(ctx, ctrl, dt, T_tank_w_in_K)[source]

Step-average lamp power and the heat it gives the tank.

Parameters:
  • ctx (StepContext)

  • ctrl (ControlState)

  • dt (float)

  • T_tank_w_in_K (float)

Return type:

dict

assemble_results(ctx, ctrl, step_state, T_solved_K)[source]

Report the step-average UV power and its heat to the tank.

Parameters:
  • ctx (StepContext)

  • ctrl (ControlState)

  • step_state (dict)

  • T_solved_K (float)

Return type:

dict

calc_exergy(df, T0_K)[source]

UV exergy = electricity (handled by E→X conversion).

No additional post-processing needed. Returns None.

Parameters:
  • df (DataFrame)

  • T0_K (Series)

Return type:

SubsystemExergy | None

__init__(lamp_watts=0.0, exposure_sec=0.0, num_switching=1, period_sec=10800, heat_to_water_fraction=0.9)
Parameters:
  • lamp_watts (float)

  • exposure_sec (float)

  • num_switching (int)

  • period_sec (float)

  • heat_to_water_fraction (float)

UV treatment

UV water treatment utility functions.

Functions for UV lamp power scheduling, turbidity-based parameter lookup, and required exposure time calculation (Radial Model).

tmhp.uv_treatment.calc_uv_lamp_power(current_time_s, period_sec, num_switching, exposure_sec, lamp_watts)[source]

Calculate UV lamp power at a given time instant.

The lamp switches on num_switching times per period_sec, each activation lasting exposure_sec.

Parameters:
  • current_time_s (float) – Current simulation time [s].

  • period_sec (float) – Switching period (e.g. 3 h → 10800 s).

  • num_switching (int) – Number of on-cycles per period.

  • exposure_sec (float) – Duration of each on-cycle [s].

  • lamp_watts (float) – Rated lamp power [W].

Returns:

Instantaneous lamp power [W] (0 or lamp_watts). For the power over a time step use calc_uv_lamp_energy() / dt.

Return type:

float

tmhp.uv_treatment.calc_uv_lamp_energy(start_time_s, dt_s, period_sec, num_switching, exposure_sec, lamp_watts)[source]

Lamp energy [J] over the step [start_time_s, start_time_s + dt_s).

The on-time of the switching schedule of calc_uv_lamp_power() integrated over the step, for any step length (shorter or longer than an exposure or a period). Divided by dt_s it is the step-average power, so a run’s lamp energy does not depend on the time step (a sample at the step start would count a whole step whenever an exposure covers that instant and nothing when it falls between two samples).

Parameters:
  • start_time_s (float)

  • dt_s (float)

  • period_sec (float)

  • num_switching (int)

  • exposure_sec (float)

  • lamp_watts (float)

Return type:

float

tmhp.uv_treatment.get_uv_params_from_turbidity(turbidity_ntu)[source]

Return UV parameters from a turbidity lookup table.

Table data based on Table 1. Effect of Turbidity on UVT, UV Absorbance, UV Intensity, and Exposure Time.

Parameters:

turbidity_ntu (float) – Turbidity value [NTU].

Returns:

Keys: uv_absorbance, uv_transmittance_percent, reference_intensity_mw_cm2, reference_exposure_time_sec.

Return type:

dict

tmhp.uv_treatment.calc_uv_exposure_time(radius_cm, uvc_output_W, lamp_arc_length_cm, target_dose_mj_cm2=186, turbidity_ntu=0.25)[source]

Calculate required UV lamp exposure time via Radial Model.

Reference: ADA453967.pdf — Radial Model for UV disinfection.

Parameters:
  • radius_cm (float) – Tank radius (lamp-to-wall distance) [cm].

  • uvc_output_W (float) – UV-C output power of the lamp [W].

  • lamp_arc_length_cm (float) – Arc length of the lamp [cm].

  • target_dose_mj_cm2 (float) – Target germicidal dose [mJ/cm²]. Default 186 (EPA 4-log virus).

  • turbidity_ntu (float) – Water turbidity [NTU].

Returns:

Required single-exposure time [min].

Return type:

float

Stratified tank

Multi-node (1-D finite-volume) stratified thermal-storage tank.

Implements the multi-node model of Cadau et al. (Development and Analysis of a Multi-Node Dynamic Model for the Simulation of Stratified Thermal Energy Storage, Energies 2019, 12:4275): the tank is divided into N vertically stacked nodes (node 0 = top/hottest, node N-1 = bottom/coldest), each with a uniform temperature T_i. The per-node energy balance combines

  • advection — port inflow/outflow and inter-node vertical flow, upwinded by the flow direction (Cadau Eq. 4-6);

  • pseudo-conduction — k·(T_{i-1}-T_i) - k·(T_i-T_{i+1}) between neighbouring nodes, lumping conductive + convective exchange;

  • ambient loss — UA_i·(T_i - T_amb) through the side wall; and

  • buoyancy (inversion) mixing — a node warmer than the node above it rises and mixes instantly with it (TRNSYS Type 4/60 style), so the profile after a step is never inverted. See mix_inversions().

It is integrated implicitly (backward Euler) as a tridiagonal solve, so the update is unconditionally stable and smooth in the state — a property the legacy single-node lumped tank lacks and that an MPC-internal model needs. The lumped fully-mixed tank is exactly the N=1 limit of this model.

Numerical diffusion

First-order implicit upwinding smears a sharp thermocline like a physical axial diffusivity D_num = (v·Δz/2)·(1 + Co) with v = V̇/A and the Courant number Co = V̇·Δt/V_node. After the front has travelled a distance L its spread is σ² ≈ L·(Δz + v·Δt): the time step acts like an extra node thickness v·Δt, which is why refining the nodes alone stops helping once Co > 1. max_courant (opt-in) splits a step into equal implicit sub-steps with Co ≤ max_courant and bounds the spread at σ² ≈ L·Δz·(1 + max_courant). docs/tank_backends/tank_backends.md tabulates the effect.

Conventions

  • Node index increases downward: T[0] top (hot), T[N-1] bottom (cold).

  • charge_flow [m³/s] ≥ 0 (HP charging) enters the top node at T_charge and exits the bottom node (hot return to top, cold draw to HP) — a downward internal flow.

  • draw_flow [m³/s] ≥ 0 (load) draws hot water from the top node and admits cold makeup T_makeup at the bottom node — an upward internal flow.

  • The net inter-node flow is charge_flow - draw_flow (downward positive); advection is upwinded by its direction (Cadau Eq. 4-6).

  • Temperatures in °C; energy balances are temperature-difference based so the reference cancels.

  • The model is single-phase liquid water. A node pushed above T_boil (default 100 °C, atmospheric boiling) by q_source is outside the model’s validity: the step flags it (overheat in the result) and warns with TankOverheatWarning; the state is not clipped (clipping would destroy energy). The tank does not know its heat source — the caller must limit it.

Immersed heat exchanger

q_source puts a prescribed heat into each node whatever its temperature. A condenser coil (or any exchanger held at one temperature) cannot do that: heat flows only into water colder than the exchanger. hx_ua / T_hx model it: node i receives k·UA_i·(T_hx − T_i)⁺ with T_i the end-of-(sub)step temperature, so a node at or above T_hx receives nothing and no heated node ends above T_hx. With q_hx the common factor k is solved so the nodes receive exactly that heat (the split between the nodes stays proportional to UA_i·(T_hx − T_i)⁺); if even nodes held at T_hx cannot take it, the step delivers what they can and reports hx_limited. With q_hx and no T_hx the exchanger temperature itself is solved (k = 1): the temperature the coil needs to pass that heat.

tmhp.stratified_tank.INVERSION_TOL_K = 0.0001

a node counts as inverted only when it is warmer than the node above by more than this. 0.1 mK is far below any measurable (or buoyancy-relevant) difference and far above float round-off at tank temperatures (~1e-14 K), so a uniform or exactly layered profile is never “mixed” on one platform and not on another.

Type:

Temperature tolerance [K] of the buoyancy check

tmhp.stratified_tank.T_BOIL_ATM_C = 100.0

upper validity limit of the liquid model.

Type:

Atmospheric boiling point [°C]

tmhp.stratified_tank.OVERHEAT_TOL_K = 1e-06

Tolerance [K] above T_boil before a node is flagged as overheated, so a heater sized to land exactly on the limit is not flagged by round-off on one platform only.

tmhp.stratified_tank.HX_SCALE_MAX = 1000000.0

Largest common factor k on the exchanger conductance. At this value the heated nodes sit within ~1e-6 of T_hx; a request that still is not met cannot be delivered below T_hx (hx_limited).

tmhp.stratified_tank.HX_LIMIT_RTOL = 1e-09

Relative shortfall of the delivered exchanger heat that counts as limited.

tmhp.stratified_tank.HX_COURANT_MAX = 0.5

the heated water rises), the step is repeated in sub-steps of at most this fraction of the fastest node time constant C_node / UA_i, so the heat the coil can pass on by buoyancy does not depend on dt. Capped at HX_SUBSTEPS_MAX.

Type:

When an exchanger step mixes an inversion (a coil low in the tank

exception tmhp.stratified_tank.TankOverheatWarning[source]

Bases: RuntimeWarning

A tank node exceeded the liquid-water validity limit T_boil.

tmhp.stratified_tank.mix_inversions(T, cap, tol=0.0001)[source]

Energy-conserving instantaneous buoyancy mixing of a top→bottom profile.

Whenever a layer is warmer than the layer above it (by more than tol) the two are fully mixed at their capacity-weighted mean, and the check is repeated against the layer above — the classic instantaneous inversion mixing of TRNSYS Type 4/60 (EnergyPlus WaterHeater:Stratified resolves the same physics with a large inversion-mixing conductance). Implemented as pool-adjacent-violators, so the result is the capacity-weighted isotonic (non-increasing) profile: every mixed block holds its block-mean, energy Σ cap·T is conserved, and the output satisfies T[i+1] <= T[i] + tol.

Parameters:
  • T (array-like) – Layer temperatures, top first [°C].

  • cap (array-like) – Layer heat capacities (any consistent unit, e.g. J/K or m³).

  • tol (float) – Inversion tolerance [K] (see INVERSION_TOL_K).

Returns:

T_mixed is the input array itself when nothing was inverted (so an already stable profile is returned bit-for-bit), else a new array.

Return type:

tuple[ndarray, bool]

tmhp.stratified_tank.solve_one_sided_hx(ab, rhs, g, T_hx, T_start)[source]

Solve A·T = rhs + g·(T_hx − T)⁺ for a banded M-matrix A (ab).

g [W/K] is the exchanger conductance per control volume. The one-sided term is piecewise linear, so the solve is an active-set iteration (the semismooth Newton method, finite for M-matrices): the control volumes below T_hx carry the conductance, the others none. Returns (T, q) with q = g·(T_hx − T)⁺ >= 0 [W].

Parameters:
  • ab (ndarray)

  • rhs (ndarray)

  • g (ndarray)

  • T_hx (float)

  • T_start (ndarray)

tmhp.stratified_tank.solve_hx_scale(delivered, q_target)[source]

Common factor k with delivered(k) == q_target; (k, limited).

delivered [W] grows with k from zero and saturates once the heated nodes reach the exchanger temperature. limited is True when even HX_SCALE_MAX falls short of q_target.

Parameters:
  • delivered (Callable[[float], float])

  • q_target (float)

Return type:

tuple[float, bool]

tmhp.stratified_tank.solve_hx_temperature(delivered, q_target, T_low, span)[source]

Exchanger temperature [°C] with delivered(T_hx) == q_target.

delivered [W] grows without bound with the temperature and is zero below the coldest water the step reaches. T_low is the caller’s estimate of that (the coldest start, make-up and ambient temperature); span [K] is a first guess of how far above it the answer lies. Water that a negative q_source cools during the step can end below T_low, where the exchanger already delivers more than q_target: the bracket is then widened downward until it encloses the duty.

Parameters:
  • delivered (Callable[[float], float])

  • q_target (float)

  • T_low (float)

  • span (float)

Return type:

float

class tmhp.stratified_tank.StratifiedTank(n_nodes, volume, height, *, k_eff=0.606, ua=0.0, rho=1000, cp=4186, inversion_mixing=True, max_courant=None, T_boil=100.0)[source]

Bases: object

Multi-node stratified hot-water tank (implicit tridiagonal stepper).

Parameters:
  • n_nodes (int) – Number of vertical nodes N (N=1 recovers the lumped tank).

  • volume (float) – Total tank volume [m³].

  • height (float) – Tank height [m] (sets node thickness dz = height/N and the cross-sectional area volume/height for conduction).

  • k_eff (float) – Effective inter-node conductivity [W/m/K] (water conduction plus any turbulent-mixing enhancement). Defaults to water (k_w).

  • ua (float) – Total tank-to-ambient loss coefficient UA [W/K], split uniformly across nodes (side wall; no separate top/bottom plates). Defaults to 0 (adiabatic).

  • rho (float) – Water density [kg/m³] and specific heat [J/kg/K]; default to the project constants. Assumed constant (Cadau: density assumed constant per node).

  • cp (float) – Water density [kg/m³] and specific heat [J/kg/K]; default to the project constants. Assumed constant (Cadau: density assumed constant per node).

  • inversion_mixing (bool) – Mix temperature inversions after every (sub-)step (default True). False restores the pre-#96 behaviour, in which a bottom heater can leave the bottom hotter than the top indefinitely.

  • max_courant (float | None) – Opt-in sub-stepping: split each step into m = ceil(Co/max_courant) equal implicit sub-steps, Co = max(charge_flow, draw_flow)·dt/V_node. None (default) keeps one implicit step per call. Sub-stepping bounds the numerical diffusion independently of dt but makes the update piecewise in the flow (the sub-step count jumps at integer Courant numbers), so leave it off for gradient-based MPC.

  • T_boil (float) – Liquid-water validity limit [°C] for the overheat flag (default 100 °C; raise it for a pressurised tank).

__init__(n_nodes, volume, height, *, k_eff=0.606, ua=0.0, rho=1000, cp=4186, inversion_mixing=True, max_courant=None, T_boil=100.0)[source]
Parameters:
  • n_nodes (int)

  • volume (float)

  • height (float)

  • k_eff (float)

  • ua (float)

  • rho (float)

  • cp (float)

  • inversion_mixing (bool)

  • max_courant (float | None)

  • T_boil (float)

T: ndarray
reset(T_init)[source]

Set node temperatures (scalar = uniform, or length-N array).

Return type:

ndarray

property stored_energy: float

Sensible energy relative to 0 °C [J] (Σ m_node·cp·T_i).

substeps(dt, charge_flow=0.0, draw_flow=0.0)[source]

Number of implicit sub-steps step uses for these flows.

Parameters:
  • dt (float)

  • charge_flow (float)

  • draw_flow (float)

Return type:

int

step(dt, *, charge_flow=0.0, T_charge=0.0, draw_flow=0.0, T_makeup=10.0, q_source=None, T_amb=20.0, hx_ua=None, T_hx=None, q_hx=None)[source]

Advance one timestep (backward Euler, charge + draw + heat source).

Parameters:
  • dt (float) – Timestep [s].

  • charge_flow (float) – HP charge flow [m³/s] (hot T_charge into top, out at bottom).

  • T_charge (float) – Charge inlet temperature [°C] (used when charge_flow > 0).

  • draw_flow (float) – Load draw flow [m³/s] (hot from top, cold T_makeup into bottom).

  • T_makeup (float) – Cold makeup temperature [°C] (used when draw_flow > 0).

  • q_source (float or array-like, optional) – Internal heat input [W] from an immersed heater. A scalar is applied to the top node; a length-N array is applied per node. The heat goes in whatever the node temperature.

  • T_amb (float) – Ambient temperature [°C] for the side-wall loss.

  • hx_ua (float or array-like, optional) – Conductance [W/K] of an immersed exchanger held at T_hx (a condenser coil). A scalar is spread uniformly over the nodes; a length-N array is per node (zero where the coil is absent).

  • T_hx (float | None) – Exchanger temperature [°C] (the condensing temperature). Heat flows one way: node i receives k·hx_ua_i·(T_hx − T_i)⁺. None with q_hx: solved, with k = 1, so that the exchanger delivers q_hx.

  • q_hx (float | None) – Step-average heat the exchanger delivers [W]; with T_hx the factor k is solved to deliver it. None: k = 1 (the heat is whatever the conductance gives at T_hx).

Returns:

T (new node temperatures), T_top (top node), T_outlet (bottom node), T_draw_out / T_charge_out (flow-weighted mean temperature of the water that left through the top draw port / the bottom charge-return port during the step [°C]; equal to the node temperature when that flow is zero), Q_loss (mean ambient loss [W]), T_max [°C], overheat (T_max > T_boil), mixed (an inversion was mixed), substeps, and for the exchanger q_hx (step-average heat into each node [W]), Q_hx (their sum), hx_scale (k), T_hx (given or solved; None without an exchanger), T_hx_heated_max (the hottest water the exchanger heated, at the end of the solve that heated it; None if it heated none; never above T_hx) and hx_limited (the requested q_hx could not be delivered below T_hx; Q_hx is what was). The step closes ΔE = dt·[ρc·(V̇_c·T_charge + V̇_d·T_makeup − V̇_d·T_draw_out − V̇_c·T_charge_out) + Σq + Q_hx − Q_loss] to round-off. Without mixing and sub-steps T_draw_out == T_top and T_charge_out == T_outlet.

Return type:

dict

preview(dt, *, charge_flow=0.0, T_charge=0.0, draw_flow=0.0, T_makeup=10.0, q_source=None, T_amb=20.0, hx_ua=None, T_hx=None, q_hx=None)[source]

Result step() would give, without advancing the tank (and without warning).

Parameters:
  • dt (float)

  • charge_flow (float)

  • T_charge (float)

  • draw_flow (float)

  • T_makeup (float)

  • T_amb (float)

  • T_hx (float | None)

  • q_hx (float | None)

Return type:

dict

Hybrid stratified tank

1-D hybrid continuous–discrete multi-node stratified tank (Cruz-Loredo 2023).

Implements the idea of the hybrid thermocline model of De la Cruz-Loredo et al. (Experimental validation of a hybrid 1-D multi-node model of a hot water thermal energy storage tank, Applied Energy 2023, 332:120556): the standard multi-node model (StratifiedTank) is augmented by a flat thermocline barrier at vertical position y_th that travels in plug flow at v_th = V̇/A_c (paper Eq. 6). Across the barrier the temperature jumps; the node that contains it is not treated as fully mixed for advection, so the transition propagates at the physical front speed instead of smearing across nodes (the numerical diffusion of the standard model).

Formulation (conservative, any time step)

The paper realises the barrier with a discrete reference temperature T_{j,k} of the upstream node that stays frozen while the barrier is inside it (Eq. 3-5) and updates it every Δt = 1 s — the barrier then moves a tiny fraction of a node per update. Taken literally that scheme advects the frozen value into the next node while the upstream node loses its continuous value, so it does not conserve energy, and with a time step longer than one node transit the front cannot get past one node per step (#96: 7.7–58 % of the injected heat was stored). This module keeps the same states but closes the books:

  • the node containing the barrier carries two zones — water above the barrier (T_above) and below it (T_below, the paper’s discrete reference) — and its node temperature is their volume-weighted mean;

  • advection is an exact plug-flow shift of that piecewise-constant column by the step volume V̇·Δt (any number of nodes per step), remapped onto the nodes conservatively; only the barrier is kept as a sub-node discontinuity;

  • conduction (zone-aware), side-wall loss, q_source and the immersed exchanger (hx_ua / T_hx / q_hx, as in StratifiedTank) are then integrated implicitly (backward Euler) over the nodes plus the two zones;

  • buoyancy inversions are mixed instantly (mix_inversions()).

Every step closes ΔE = in − out + Σq·Δt − loss to round-off and the barrier sits exactly V_injected/A below the inlet.

Barrier life cycle (paper §3.3)

front="both" (default, Eqs. 4-6): the barrier forms at the inlet when net flow starts into a tank without one (top for net charge, bottom for net draw), moves with the net flow in either direction, persists while idle (only conduction acts on it) and disappears when it leaves the tank, when its two sides equalise (|T_above − T_below| ≤ FRONT_MERGE_TOL_K) or when buoyancy mixes them. front="charge" (Eq. 7) dissolves it whenever the net flow is upward; front="discharge" (Eq. 8) whenever it is downward — for tanks whose inlet mixing destroys the thermocline in one direction (the paper’s own tank had a sharp front only while discharging). Only one barrier is tracked: an interface created while one already exists (e.g. a new charge temperature) is carried by the ordinary node remap and diffuses like the standard model.

Simultaneous charge and draw: only the net flow charge − draw moves the column. The overlapping through-flow s = min(charge, draw)·Δt enters and leaves at the same end, so it is exchanged with the inlet node there, treated as a fully mixed volume (as in the standard model) and integrated exactly (T → T_in + (T − T_in)·exp(−s/V), independent of Δt): hot charge water mixes into the top node before the draw takes it, makeup mixes into the bottom node before the charge return takes it. While the ports overlap, a new barrier is formed below the mixed inlet node rather than at the inlet itself, so the front position stays independent of Δt. T_draw_out / T_charge_out in the result report the outflow temperatures.

Validation status: energy conservation, front position and sharpness are verified against plug flow (tests/test_hybrid_tank.py); no comparison with measured tank data has been made in tmhp.

Same geometry/units conventions as StratifiedTank (node 0 = top/hot).

tmhp.hybrid_tank.FRONT_MERGE_TOL_K = 0.001

Temperature difference [K] at or below which the two sides of the barrier are treated as the same water and the barrier is dropped (freeing it for the next real front). 1 mK is below any sensor resolution and far above round-off.

class tmhp.hybrid_tank.HybridStratifiedTank(n_nodes, volume, height, *, k_eff=0.606, ua=0.0, rho=1000, cp=4186, front='both', T_boil=100.0)[source]

Bases: object

Hybrid continuous–discrete multi-node tank with a flat thermocline.

Parameters:
__init__(n_nodes, volume, height, *, k_eff=0.606, ua=0.0, rho=1000, cp=4186, front='both', T_boil=100.0)[source]
Parameters:
  • n_nodes (int)

  • volume (float)

  • height (float)

  • k_eff (float)

  • ua (float)

  • rho (float)

  • cp (float)

  • front (str)

  • T_boil (float)

T: ndarray
reset(T_init)[source]
Return type:

ndarray

property stored_energy: float
property y_th: float | None

Barrier height above the tank bottom [m], None without a barrier.

property front_temperatures: tuple[float, float] | None

(T_above, T_below) of the barrier [°C], None without a barrier.

step(dt, *, charge_flow=0.0, T_charge=0.0, draw_flow=0.0, T_makeup=10.0, q_source=None, T_amb=20.0, hx_ua=None, T_hx=None, q_hx=None)[source]

Advance one timestep; arguments and result as StratifiedTank.step.

The result carries y_th (barrier height [m] or None) instead of substeps.

Parameters:
  • dt (float)

  • charge_flow (float)

  • T_charge (float)

  • draw_flow (float)

  • T_makeup (float)

  • T_amb (float)

  • T_hx (float | None)

  • q_hx (float | None)

Return type:

dict

preview(dt, *, charge_flow=0.0, T_charge=0.0, draw_flow=0.0, T_makeup=10.0, q_source=None, T_amb=20.0, hx_ua=None, T_hx=None, q_hx=None)[source]

Result step() would give, without advancing the tank (and without warning).

Parameters:
  • dt (float)

  • charge_flow (float)

  • T_charge (float)

  • draw_flow (float)

  • T_makeup (float)

  • T_amb (float)

  • T_hx (float | None)

  • q_hx (float | None)

Return type:

dict