enex_analysis package

Subpackages

Submodules

enex_analysis.dynamic_context module

Shared dynamic simulation context and control helpers.

Provides reusable dataclasses and pure functions that form the backbone of time-stepping heat-pump simulations. Extracted from AirSourceHeatPumpBoiler so that GroundSourceHeatPumpBoiler and future models can share the same infrastructure.

class enex_analysis.dynamic_context.StepContext(n, current_time_s, current_hour, hour_of_day, T0, T0_K, activation_flags, T_tank_w_K, tank_level, dV_mix_w_out, I_DN=0.0, I_dH=0.0, T_sup_w_K=288.15)[source]

Bases: object

Per-timestep immutable context (time, environment, demand).

n

Current step index.

Type:

int

current_time_s

Elapsed simulation time [s].

Type:

float

current_hour

Elapsed simulation time [h].

Type:

float

hour_of_day

Hour within the current day (0–24, repeating).

Type:

float

T0

Dead-state / outdoor-air temperature [°C].

Type:

float

T0_K

Dead-state temperature [K].

Type:

float

activation_flags

Per-subsystem schedule activation flags for this step. e.g. {"stc": True} when the STC preheat window is active. An empty dict means no subsystem has a schedule constraint.

Type:

dict[str, bool]

T_tank_w_K

Current tank water temperature [K].

Type:

float

tank_level

Fractional tank fill level (0–1).

Type:

float

dV_mix_w_out

Service water draw-off flow rate [m³/s].

Type:

float

I_DN

Direct-normal irradiance on collector plane [W/m²].

Type:

float

I_dH

Diffuse-horizontal irradiance [W/m²].

Type:

float

T_sup_w_K

Mains water supply temperature [K].

Type:

float

Parameters:
  • n (int)

  • current_time_s (float)

  • current_hour (float)

  • hour_of_day (float)

  • T0 (float)

  • T0_K (float)

  • activation_flags (dict)

  • T_tank_w_K (float)

  • tank_level (float)

  • dV_mix_w_out (float)

  • I_DN (float)

  • I_dH (float)

  • T_sup_w_K (float)

n: int
current_time_s: float
current_hour: float
hour_of_day: float
T0: float
T0_K: float
activation_flags: dict
T_tank_w_K: float
tank_level: float
dV_mix_w_out: float
I_DN: float = 0.0
I_dH: float = 0.0
T_sup_w_K: float = 288.15
__init__(n, current_time_s, current_hour, hour_of_day, T0, T0_K, activation_flags, T_tank_w_K, tank_level, dV_mix_w_out, I_DN=0.0, I_dH=0.0, T_sup_w_K=288.15)
Parameters:
  • n (int)

  • current_time_s (float)

  • current_hour (float)

  • hour_of_day (float)

  • T0 (float)

  • T0_K (float)

  • activation_flags (dict)

  • T_tank_w_K (float)

  • tank_level (float)

  • dV_mix_w_out (float)

  • I_DN (float)

  • I_dH (float)

  • T_sup_w_K (float)

class enex_analysis.dynamic_context.ControlState(is_on, Q_heat_source, dV_tank_w_in_ctrl, result=<factory>)[source]

Bases: object

Heat-source control decisions for one timestep.

Model-agnostic container: any boiler model populates these fields in its Phase-A helper. Subsystem states are managed separately via sub_states: dict[str, dict].

is_on

Whether the heat source is running.

Type:

bool

Q_heat_source

Net heat delivered to the tank from the heat source [W].

Type:

float

dV_tank_w_in_ctrl

Refill flow rate [m³/s]. None = always-full sentinel (inflow resolved inside residual).

Type:

float | None

result

Full result dictionary from the model’s _calc_state. Contents are model-specific.

Type:

dict

Parameters:
  • is_on (bool)

  • Q_heat_source (float)

  • dV_tank_w_in_ctrl (float | None)

  • result (dict)

is_on: bool
Q_heat_source: float
dV_tank_w_in_ctrl: float | None
result: dict
__init__(is_on, Q_heat_source, dV_tank_w_in_ctrl, result=<factory>)
Parameters:
  • is_on (bool)

  • Q_heat_source (float)

  • dV_tank_w_in_ctrl (float | None)

  • result (dict)

class enex_analysis.dynamic_context.SubsystemExergy(columns, X_tot_add=0.0, X_in_tank_add=0.0, X_out_tank_add=0.0)[source]

Bases: object

Subsystem-specific exergy calculation results.

Each subsystem’s calc_exergy() returns this object so that the host boiler can merge subsystem columns into the result DataFrame and adjust system-level totals.

columns

Exergy columns to append (key = column name).

Type:

dict[str, pd.Series]

X_tot_add

Additive contribution to system total exergy input X_tot [W] (e.g. pump electricity).

Type:

pd.Series | float

X_in_tank_add

Additive exergy entering the tank boundary (e.g. heated return water in tank_circuit).

Type:

pd.Series | float

X_out_tank_add

Additive exergy leaving the tank boundary (e.g. water drawn to STC in tank_circuit).

Type:

pd.Series | float

Parameters:
  • columns (dict)

  • X_tot_add (object)

  • X_in_tank_add (object)

  • X_out_tank_add (object)

columns: dict
X_tot_add: object = 0.0
X_in_tank_add: object = 0.0
X_out_tank_add: object = 0.0
__init__(columns, X_tot_add=0.0, X_in_tank_add=0.0, X_out_tank_add=0.0)
Parameters:
  • columns (dict)

  • X_tot_add (object)

  • X_in_tank_add (object)

  • X_out_tank_add (object)

class enex_analysis.dynamic_context.Subsystem(*args, **kwargs)[source]

Bases: Protocol

Pluggable subsystem interface.

Each subsystem computes its contribution for a single timestep and assembles result columns for the output DataFrame. New subsystems (PV, battery, …) implement this protocol and register with the boiler model.

step(ctx, ctrl, dt, T_tank_w_in_K)[source]

Compute subsystem state for this timestep.

Parameters:
  • ctx (StepContext) – Current-step immutable context.

  • ctrl (ControlState) – Heat-source control decisions.

  • dt (float) – Time-step size [s].

  • T_tank_w_in_K (float) – Mains water inlet temperature [K].

Returns:

Must include at least:

  • 'Q_contribution' (float):

    Net energy contribution to tank [W].

  • 'E_subsystem' (float):

    Electrical power consumed [W].

  • 'T_tank_w_in_override_K' (float | None):

    If the subsystem modifies the tank inlet temperature (e.g. mains preheat), provide the heated temperature [K]. None means no modification.

Return type:

dict

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

Build result columns for DataFrame output.

Parameters:
  • ctx (StepContext) – Current-step immutable context.

  • ctrl (ControlState) – HP control decisions.

  • step_state (dict) – Dict returned by step().

  • T_solved_K (float) – Solved tank temperature [K].

Returns:

Keyed result entries for the output DataFrame.

Return type:

dict

calc_exergy(df, T0_K)[source]

Compute subsystem-level exergy items.

Parameters:
  • df (DataFrame)

  • T0_K (Series)

Return type:

SubsystemExergy | None

calc_performance(**kwargs)[source]

Calculate performance at a specific condition.

Return type:

dict

__init__(*args, **kwargs)
enex_analysis.dynamic_context.check_hp_schedule_active(hour, hp_on_schedule)[source]

Check whether current hour falls within HP operating schedule.

Parameters:
  • hour (float) – Current time of day [h] (0.0–24.0).

  • hp_on_schedule (list of tuple) – List of (start_hour, end_hour) operating windows.

Return type:

bool

enex_analysis.dynamic_context.determine_heat_source_on_off(T_tank_w_C, T_lower, T_upper, is_on_prev, hour_of_day, on_schedule)[source]

Hysteresis-based heat-source on/off decision.

Parameters:
  • T_tank_w_C (float) – Current tank water temperature [°C].

  • T_lower (float) – Lower hysteresis bound [°C].

  • T_upper (float) – Upper hysteresis bound [°C].

  • is_on_prev (bool) – Heat-source state at the previous timestep.

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

  • on_schedule (list[tuple[float, float]]) – Active operating windows (start_h, end_h).

Returns:

Whether the heat source should run this timestep.

Return type:

bool

enex_analysis.dynamic_context.determine_tank_refill_flow(dt, tank_level, dV_tank_w_out, V_tank_full, tank_always_full, prevent_simultaneous_flow, tank_level_lower_bound, tank_level_upper_bound, dV_tank_w_in_refill, is_refilling)[source]

Determine refill flow rate from current level and operational mode.

Pure tank-level management: all subsystem-specific flow overrides (e.g. STC mains-preheat forced refill) are the responsibility of the scenario class via _run_subsystems / ctrl.dV_tank_w_in_ctrl.

Parameters:
  • dt (float) – Time-step size [s].

  • tank_level (float) – Current fractional tank level (0–1).

  • dV_tank_w_out (float) – Current outflow rate [m³/s].

  • V_tank_full (float) – Tank full volume [m³].

  • tank_always_full (bool) – Whether the tank is forced to stay full.

  • prevent_simultaneous_flow (bool) – Exclusive-flow mode flag.

  • tank_level_lower_bound (float) – Level lower bound for refill trigger.

  • tank_level_upper_bound (float) – Level upper bound for refill cut-off.

  • dV_tank_w_in_refill (float) – Refill flow rate [m³/s].

  • is_refilling (bool) – Whether we are currently in a refill cycle.

Returns:

(dV_tank_w_in, is_refilling). None means always-full sentinel (no PSF).

Return type:

tuple[float | None, bool]

enex_analysis.dynamic_context.tank_mass_energy_residual(x, ctx, ctrl, dt, T_tank_w_in_K, T_sup_w_K, T_mix_w_out_K, C_tank, UA_tank, V_tank_full, subsystems, sub_states)[source]

Energy and mass balance residuals at T^{n+1}.

The 3-way mixing valve ratio α(T) makes the outflow a nonlinear function of T^{n+1}, requiring fsolve.

Subsystem energy contributions and tank-inlet temperature overrides are read from sub_states.

Parameters:
  • x (list[float]) – [T_next_K, level_next].

  • ctx (StepContext) – Current-step immutable context.

  • ctrl (ControlState) – Current-step HP control decisions.

  • dt (float) – Time-step size [s].

  • T_tank_w_in_K (float) – Mains water inlet temperature [K].

  • T_sup_w_K (float) – Mains water supply temperature [K] (for mixing valve).

  • T_mix_w_out_K (float) – Target mixing-valve outlet temperature [K].

  • C_tank (float) – Tank thermal capacitance [J/K].

  • UA_tank (float) – Tank overall heat-loss coefficient [W/K].

  • V_tank_full (float) – Tank full volume [m³].

  • subsystems (dict[str, Subsystem]) – Registered subsystem instances.

  • sub_states (dict[str, dict]) – Per-subsystem state dicts from step().

Returns:

[r_energy, r_mass].

Return type:

list[float]

enex_analysis.eb_pv_ess module

EB Scenario: Electric Boiler driven by PV + ESS with Grid/Dump integration.

class enex_analysis.eb_pv_ess.EB_PV_ESS(*, pv, ess=None, eta_inv=0.95, T_inv_K=313.15, **kwargs)[source]

Bases: ElectricBoiler

Parameters:
__init__(*, pv, ess=None, eta_inv=0.95, T_inv_K=313.15, **kwargs)[source]
Parameters:

enex_analysis.eb_stc_preheat module

EB with SolarThermalCollector — mains_preheat placement.

class enex_analysis.eb_stc_preheat.EB_STC_preheat(*, stc, **kwargs)[source]

Bases: ElectricBoiler

Parameters:

stc (SolarThermalCollector)

__init__(*, stc, **kwargs)[source]
Parameters:

stc (SolarThermalCollector)

enex_analysis.eb_stc_tank module

EB with SolarThermalCollector — tank_circuit placement.

class enex_analysis.eb_stc_tank.EB_STC_tank(*, stc, **kwargs)[source]

Bases: ElectricBoiler

Parameters:

stc (SolarThermalCollector)

__init__(*, stc, **kwargs)[source]
Parameters:

stc (SolarThermalCollector)

enex_analysis.electric_boiler module

Electric Boiler Component Model.

class enex_analysis.electric_boiler.ElectricBoiler(*, heater_capacity, V_tank_full, T_sup_w_C, T_tank_w_lower_bound_C, T_tank_w_upper_bound_C, T_tank_w_in_C, T_mix_w_out_C, dV_mix_w_out_max, on_schedule=None, UA_tank=0.0, M_tank_empty=0.0, C_tank_empty=0.0, dV_tank_w_in_refill=None, tank_always_full=True, tank_level_lower_bound=0.2, tank_level_upper_bound=0.8, prevent_simultaneous_flow=True, subsystems=None)[source]

Bases: object

Parameters:
  • heater_capacity (float)

  • V_tank_full (float)

  • T_sup_w_C (float)

  • T_tank_w_lower_bound_C (float)

  • T_tank_w_upper_bound_C (float)

  • T_tank_w_in_C (float)

  • T_mix_w_out_C (float)

  • dV_mix_w_out_max (float)

  • on_schedule (dict | None)

  • UA_tank (float)

  • M_tank_empty (float)

  • C_tank_empty (float)

  • dV_tank_w_in_refill (float | None)

  • tank_always_full (bool)

  • tank_level_lower_bound (float)

  • tank_level_upper_bound (float)

  • prevent_simultaneous_flow (bool)

  • subsystems (dict | None)

__init__(*, heater_capacity, V_tank_full, T_sup_w_C, T_tank_w_lower_bound_C, T_tank_w_upper_bound_C, T_tank_w_in_C, T_mix_w_out_C, dV_mix_w_out_max, on_schedule=None, UA_tank=0.0, M_tank_empty=0.0, C_tank_empty=0.0, dV_tank_w_in_refill=None, tank_always_full=True, tank_level_lower_bound=0.2, tank_level_upper_bound=0.8, prevent_simultaneous_flow=True, subsystems=None)[source]
Parameters:
  • heater_capacity (float)

  • V_tank_full (float)

  • T_sup_w_C (float)

  • T_tank_w_lower_bound_C (float)

  • T_tank_w_upper_bound_C (float)

  • T_tank_w_in_C (float)

  • T_mix_w_out_C (float)

  • dV_mix_w_out_max (float)

  • on_schedule (dict | None)

  • UA_tank (float)

  • M_tank_empty (float)

  • C_tank_empty (float)

  • dV_tank_w_in_refill (float | None)

  • tank_always_full (bool)

  • tank_level_lower_bound (float)

  • tank_level_upper_bound (float)

  • prevent_simultaneous_flow (bool)

  • subsystems (dict | None)

analyze_steady(T_tank_w, T0, Q_heat_target, *, return_dict=True)[source]

Run a steady-state performance snapshot.

Parameters:
  • T_tank_w (float)

  • T0 (float)

  • Q_heat_target (float)

  • return_dict (bool)

Return type:

dict | DataFrame

postprocess_exergy(df)[source]
Parameters:

df (DataFrame)

Return type:

DataFrame

analyze_dynamic(simulation_period_sec, dt_s, T_tank_w_init_C, dhw_usage_schedule, T0_schedule, I_DN_schedule=None, I_dH_schedule=None, T_sup_w_schedule=None, tank_level_init=1.0, result_save_csv_path=None)[source]
Parameters:
  • simulation_period_sec (int)

  • dt_s (int)

  • T_tank_w_init_C (float)

  • tank_level_init (float)

  • result_save_csv_path (str | None)

Return type:

DataFrame

enex_analysis.enex_engine module

Energy, Entropy, and Exergy Analysis Engine.

This module contains classes for modeling various energy systems including: - Domestic hot water systems (electric boiler, gas boiler, heat pump boiler) - Air source heat pumps (cooling and heating modes) - Ground source heat pumps (cooling and heating modes) - Solar-assisted systems - Electric heaters

class enex_analysis.enex_engine.AirSourceHeatPump_cooling[source]

Bases: object

Air source heat pump model for cooling mode.

Simulates a single-step refrigerant cycle with indoor/outdoor heat exchangers and fans. Call system_update() after setting operating conditions to compute COP, capacities, and component powers.

system_update()[source]
__init__()
class enex_analysis.enex_engine.AirSourceHeatPump_heating[source]

Bases: object

Air source heat pump model for heating mode.

Mirror of AirSourceHeatPump_cooling configured for space heating. The condenser rejects heat to the indoor side while the evaporator absorbs from outdoor air.

system_update()[source]
__init__()
class enex_analysis.enex_engine.GroundSourceHeatPump_cooling[source]

Bases: object

Ground source heat pump model for cooling mode.

Uses borehole heat exchangers with finite-line-source g-functions for soil thermal response. Call system_update() each time step to advance the ground temperature history.

system_update()[source]
__init__()
class enex_analysis.enex_engine.GroundSourceHeatPump_heating[source]

Bases: object

Ground source heat pump model for heating mode.

Mirror of GroundSourceHeatPump_cooling configured for space heating. The evaporator absorbs heat from the ground loop while the condenser supplies heat indoors.

system_update()[source]
__init__()
class enex_analysis.enex_engine.GroundSourceHeatPump(H_b=150.0, D_b=2.0, r_b=0.08, k_p=0.4, k_grout=1.5, r_out=0.016, r_in=0.013, D_s=0.032, k_g=2.0, c_g=800.0, rho_g=2000.0, T_g=15.0, dV_f=20.0, Q_rated_cooling=20590.0, Q_rated_heating=16450.0, E_pmp=100.0, dP_iu_fan_design=60.0, eta_iu_fan_design=0.6, dt_hours=1, sim_hours=8760, Q_r_iu=0.0, T0=20.0, boundary_condition='uniform_temperature')[source]

Bases: object

Ground source heat pump model for both cooling and heating mode.

Uses borehole heat exchangers with pygfunction step-response factor array for precise soil thermal response with temporal superposition of dynamic building loads.

Parameters:
  • H_b (float)

  • D_b (float)

  • r_b (float)

  • k_p (float)

  • k_grout (float)

  • r_out (float)

  • r_in (float)

  • D_s (float)

  • k_g (float)

  • c_g (float)

  • rho_g (float)

  • T_g (float)

  • dV_f (float)

  • Q_rated_cooling (float)

  • Q_rated_heating (float)

  • E_pmp (float)

  • dP_iu_fan_design (float)

  • eta_iu_fan_design (float)

  • dt_hours (int)

  • sim_hours (int)

  • Q_r_iu (float)

  • T0 (float)

  • boundary_condition (str)

H_b: float = 150.0
D_b: float = 2.0
r_b: float = 0.08
k_p: float = 0.4
k_grout: float = 1.5
r_out: float = 0.016
r_in: float = 0.013
D_s: float = 0.032
k_g: float = 2.0
c_g: float = 800.0
rho_g: float = 2000.0
T_g: float = 15.0
dV_f: float = 20.0
Q_rated_cooling: float = 20590.0
Q_rated_heating: float = 16450.0
E_pmp: float = 100.0
dP_iu_fan_design: float = 60.0
eta_iu_fan_design: float = 0.6
dt_hours: int = 1
sim_hours: int = 8760
Q_r_iu: float = 0.0
T0: float = 20.0
boundary_condition: str = 'uniform_temperature'
system_update()[source]
__init__(H_b=150.0, D_b=2.0, r_b=0.08, k_p=0.4, k_grout=1.5, r_out=0.016, r_in=0.013, D_s=0.032, k_g=2.0, c_g=800.0, rho_g=2000.0, T_g=15.0, dV_f=20.0, Q_rated_cooling=20590.0, Q_rated_heating=16450.0, E_pmp=100.0, dP_iu_fan_design=60.0, eta_iu_fan_design=0.6, dt_hours=1, sim_hours=8760, Q_r_iu=0.0, T0=20.0, boundary_condition='uniform_temperature')
Parameters:
  • H_b (float)

  • D_b (float)

  • r_b (float)

  • k_p (float)

  • k_grout (float)

  • r_out (float)

  • r_in (float)

  • D_s (float)

  • k_g (float)

  • c_g (float)

  • rho_g (float)

  • T_g (float)

  • dV_f (float)

  • Q_rated_cooling (float)

  • Q_rated_heating (float)

  • E_pmp (float)

  • dP_iu_fan_design (float)

  • eta_iu_fan_design (float)

  • dt_hours (int)

  • sim_hours (int)

  • Q_r_iu (float)

  • T0 (float)

  • boundary_condition (str)

enex_analysis.enex_functions module

Utility functions for energy, entropy, and exergy analysis.

This module contains helper functions organized into the following categories:

  1. Friction and Flow Functions - darcy_friction_factor: Calculate Darcy friction factor - calc_Orifice_flow_coefficient: Calculate orifice flow coefficient - calc_boussinessq_mixing_flow: Calculate mixing flow based on Boussinesq approximation

  2. Heat Transfer Functions - calc_h_vertical_plate: Natural convection heat transfer coefficient - calc_UA_tank_arr: Tank heat loss UA calculation - calc_lmtd_*: Log mean temperature difference calculations - calc_UA_from_dV_fan: Heat transfer coefficient from fan flow rate

  3. Curve Fitting Functions - linear_function, quadratic_function, cubic_function, quartic_function

  4. Exergy and Entropy Functions - generate_entropy_exergy_term: Calculate entropy and exergy terms - calc_exergy_flow: Calculate exergy flow rate due to material flow

  5. G-function Calculations (Ground Source Heat Pumps) - f, chi, G_FLS: Helper functions for g-function calculation

  6. TDMA Solver Functions - TDMA: Solve tri-diagonal matrix system - _add_loop_advection_terms: Add forced convection terms to TDMA coefficients

  7. Heat Pump Cycle Functions - calculate_ASHP_*_COP: Air source heat pump COP calculations - calculate_GSHP_COP: Ground source heat pump COP calculation - calc_ref_state: Calculate refrigerant cycle states (with superheating/subcooling support) - find_ref_loop_optimal_operation: Find optimal operation point

  8. Tank Functions - update_tank_temperature: Update tank temperature based on energy balance

  9. Schedule Functions - _build_dhw_usage_ratio: Build schedule ratio array

  10. Balance Printing Utilities - print_balance: Print energy/entropy/exergy balance

enex_analysis.enex_functions.linear_function(x, a, b)[source]

Linear function: y = a*x + b

enex_analysis.enex_functions.quadratic_function(x, a, b, c)[source]

Quadratic function: y = a*x² + b*x + c

enex_analysis.enex_functions.cubic_function(x, a, b, c, d)[source]

Cubic function: y = a*x³ + b*x² + c*x + d

enex_analysis.enex_functions.quartic_function(x, a, b, c, d, e)[source]

Quartic function: y = a*x⁴ + b*x³ + c*x² + d*x + e

enex_analysis.enex_functions.print_balance(balance, decimal=2)[source]

Print energy, entropy, or exergy balance dictionary in a formatted way.

This function prints balance information for subsystems, categorizing entries into in, out, consumed, and generated categories.

Parameters:
  • balance (dict) – Dictionary containing balance information for subsystems. Structure: {subsystem_name: {category: {symbol: value}}} Categories: ‘in’, ‘out’, ‘con’ (consumed), ‘gen’ (generated)

  • decimal (int, optional) – Number of decimal places for output (default: 2)

Returns:

Only prints output

Return type:

None

Example

>>> balance = {
...     "hot water tank": {
...         "in": {"E_heater": 5000.0},
...         "out": {"Q_w_tank": 4500.0, "Q_l_tank": 400.0},
...         "con": {"X_c_tank": 100.0}
...     }
... }
>>> print_balance(balance)
enex_analysis.enex_functions.calc_mixing_valve_temp(T_tank_w_K, T_tank_w_in_K, T_mix_w_out_K)[source]

Calculate 3-way mixing valve output temperature and mixing ratio.

Mixes hot tank water with cold mains water to achieve the target service temperature T_mix_w_out_K.

Parameters:
  • T_tank_w_K (float) – Current tank water temperature [K].

  • T_tank_w_in_K (float) – Mains (cold) water supply temperature [K].

  • T_mix_w_out_K (float) – Target delivery temperature [K].

Returns:

{'alp': float, 'T_mix_w_out': float, 'T_mix_w_out_K': float} - alp: hot-water fraction [0–1] - T_mix_w_out: actual service temperature [°C] - T_mix_w_out_K: actual service temperature [K]

Return type:

dict

enex_analysis.enex_functions.calc_mixing_valve_flows(dV_mix_out, alp)[source]

Calculate volumetric flow rates at a 3-way mixing valve given a mixing ratio.

Parameters:
  • dV_mix_out (float) – Total requested service/mixed flow rate [m³/s].

  • alp (float) – Hot water mixing ratio [0-1].

Returns:

Dictionary containing generic mixing valve mass balances: - dV_hot_in: Flow rate drawn from the hot source [m³/s] - dV_cold_in: Flow rate drawn from the cold source [m³/s] - dV_mix_out: Total mixed flow rate [m³/s]

Return type:

dict

enex_analysis.enex_functions.calc_Orifice_flow_coefficient(D0, D1)[source]

Calculate the orifice flow coefficient based on diameters.

Flow configuration:

-> | D0 D1 -> -> |


type D0:

float

param D0:

Pipe diameter [m]

type D0:

float

type D1:

float

param D1:

Hole diameter [m]

type D1:

float

returns:

C_d – Orifice flow coefficient (dimensionless)

rtype:

float

Notes

This is a simplified calculation. A more complete implementation should be based on physical equations.

enex_analysis.enex_functions.calc_boussinessq_mixing_flow(T_upper, T_lower, A, dz, C_d=0.1)[source]

Calculate mixing flow rate between two adjacent nodes based on Boussinesq approximation.

Mixing occurs only when the lower node temperature is higher than the upper node, creating a gravitationally unstable condition.

Parameters:
  • T_upper (float) – Upper node temperature [K]

  • T_lower (float) – Lower node temperature [K]

  • A (float) – Tank cross-sectional area [m²]

  • dz (float) – Node height [m]

  • C_d (float, optional) – Flow coefficient (empirical constant), default 0.1

Returns:

dV_mix – Volumetric flow rate exchanged between nodes [m3/s]

Return type:

float

Notes

TODO: C_d value should be calculated based on physical equations.

enex_analysis.enex_functions.calc_HX_perf_for_target_heat(Q_ref_target, T_a_in_C=None, T_ref_sat_K=None, A_cross=None, UA_design=None, dV_fan_design=None, is_active=True, exponent=0.71, T_ou_a_in_C=None, T_ref_evap_sat_K=None, T_ref_cond_sat_l_K=None)[source]

ε-NTU 기반 공기측 열교환기 풍량 수치 해석.

This function determines the airflow that is needed to meet a specified heat transfer demand, accounting for dynamic changes in the overall heat transfer coefficient (UA) as a function of flow velocity based on the correlation for fin-and-tube heat exchangers by Wang et al. (2000) where UA ∝ velocity^0.71.

Parameters:
  • Q_ref_target (float) – 목표 열전달량 [W] (항상 양수).

  • T_a_in_C (float, optional) – 공기 입구 온도 [°C].

  • T_ref_sat_K (float, optional) – 냉매 포화 온도 [K] (일정 온도측).

  • A_cross (float) – HX 단면적 [m²].

  • UA_design (float) – 설계 UA [W/K].

  • dV_fan_design (float) – 설계 팬 풍량 [m³/s].

  • is_active (bool) – 활성화 여부.

  • exponent (float) – UA scaling exponent (default: 0.71).

  • (optional) (# Legacy Aliases)

  • T_ou_a_in_C (float, optional) – (하위 호환성) 과거 버전의 T_a_in_C 역할을 수행합니다.

  • T_ref_evap_sat_K (float, optional) – (하위 호환성) 과거 버전의 T_ref_sat_K 역할을 수행합니다.

  • T_ref_cond_sat_l_K (float, optional) – (하위 호환성) 과거 함수 시그니처 유지를 위한 미사용 파라미터입니다.

Returns:

Dictionary containing:
  • dV_fan : Required air-side flow rate [m3/s]

  • UA : Actual heat exchanger overall heat transfer coefficient at solution point [W/K]

  • T_a_mid_C : air temperature between heat exchanger and fan [°C]

  • Q_air : Heat transfer rate at operating point [W]

  • epsilon : Effectiveness at operating point [–]

  • converged : Whether the solver converged

Returns dict with all values as np.nan if is_active=False

Return type:

dict

enex_analysis.enex_functions.update_tank_temperature(T_tank_w_K, Q_gain, UA_tank, T0_K, C_tank, dt)[source]

Update tank temperature using the Crank-Nicolson implicit scheme.

The governing ODE for a lumped-capacitance tank is:

C dT/dt = Q_gain - UA (T - T0)

Crank-Nicolson averages the loss term across both time levels:

T^{n+1} = [(C/dt - UA/2) T^n + Q_gain + UA T0] / (C/dt + UA/2)

This scheme is second-order accurate in time and unconditionally stable, eliminating the overshoot that Forward Euler can exhibit when dt is large relative to the thermal time constant C/UA.

Parameters:
  • T_tank_w_K (float) – Current tank temperature [K].

  • Q_gain (float) – Total heat gain rate [W] (condenser, UV, STC, refill, etc.).

  • UA_tank (float) – Overall tank heat-loss coefficient [W/K].

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

  • C_tank (float) – Tank thermal capacitance [J/K] (= c_w * rho_w * V_tank * level).

  • dt (float) – Time step [s].

Returns:

Updated tank temperature [K].

Return type:

float

enex_analysis.enex_functions.calc_stc_performance(I_DN_stc, I_dH_stc, T_stc_w_in_K, T0_K, A_stc_pipe, alpha_stc, h_o_stc, h_r_stc, k_ins_stc, x_air_stc, x_ins_stc, dV_stc, E_pump, is_active=True)[source]

Solar Thermal Collector (STC) 성능을 계산합니다.

이 함수는 태양열 집열판의 열전달 분석을 수행합니다. enex_engine.py의 SolarAssistedGasBoiler.system_update() 로직을 참조하여 구현되었습니다.

Parameters:
  • I_DN_stc (float) – 직달일사 [W/m²]

  • I_dH_stc (float) – 확산일사 [W/m²]

  • T_stc_w_in_K (float) – STC 입수 온도 (저탕조 온도) [K]

  • T0_K (float) – 기준 온도 (환경 온도) [K]

  • A_stc_pipe (float) – STC 파이프 면적 [m²]

  • alpha_stc (float) – 흡수율 [-]

  • h_o_stc (float) – 외부 대류 열전달계수 [W/m²K]

  • h_r_stc (float) – 공기층 복사 열전달계수 [W/m²K]

  • k_ins_stc (float) – 단열재 열전도도 [W/mK]

  • x_air_stc (float) – 공기층 두께 [m]

  • x_ins_stc (float) – 단열재 두께 [m]

  • dV_stc (float) – STC 유량 [m3/s]

  • E_pump (float) – 펌프 소모 전력 [W]

  • is_active (bool, optional) – 활성화 여부 (기본값: True) is_active=False일 때 nan 값으로 채워진 딕셔너리 반환

Returns:

계산 결과 딕셔너리: - I_sol_stc: 총 일사량 [W/m²] - Q_sol_stc: 태양열 흡수 열량 [W] - Q_stc_w_in: STC 입수 열량 [W] - Q_stc_w_out: STC 출수 열량 [W] - ksi_stc: 무차원 수 [-] - T_stc_w_out_K: STC 출수 온도 [K] - T_stc_w_final_K: 펌프 열 포함 최종 출수 온도 [K] - T_stc_w_in_K: STC 입수 온도 [K] - T_stc_K: 집열판 평균 온도 [K] - Q_l_stc: 집열판 열 손실 [W] Returns dict with all values as np.nan (except T_stc_w_out_K, T_stc_w_in_K = T_stc_w_in_K) if is_active=False

Return type:

dict

Notes

  • 모든 변수명에 _stc 접미사를 사용하여 STC 관련 변수임을 명확히 구분합니다.

  • 열 손실은 Q_l_stc로 명명됩니다.

  • 엔트로피 및 엑서지 계산은 제거되었으며, CSV 파일 후처리를 통해 계산해야 합니다.

enex_analysis.gas_boiler module

Gas boiler model for steady-state and dynamic energy analysis.

Models a direct-supply gas boiler without a storage tank. The system chain is: Combustion Chamber → Mixing Valve → Service Water. Full energy, entropy, and exergy balances are computed at each operating point.

class enex_analysis.gas_boiler.GasBoiler(eta_comb=0.9, T_serv_w=45.0, T_sup_w=15.0, T_exh=70.0, T_comb_setpoint=60.0, dV_w_serv_m3s=0.0001)[source]

Bases: object

Direct-supply gas boiler with energy / entropy / exergy accounting.

The boiler heats mains water to T_comb_setpoint and mixes it with bypass water through a mixing valve to deliver service water at T_serv_w. No thermal storage tank is used.

__init__(eta_comb=0.9, T_serv_w=45.0, T_sup_w=15.0, T_exh=70.0, T_comb_setpoint=60.0, dV_w_serv_m3s=0.0001)[source]
analyze_steady(T0, Q_heat_target, *, return_dict=True)[source]

Run a steady-state performance snapshot.

Parameters:
  • T0 (float)

  • Q_heat_target (float)

  • return_dict (bool)

Return type:

dict | DataFrame

analyze_dynamic(simulation_period_sec, dt_s, dhw_usage_schedule, T0_schedule, heater_capacity_const=None, heater_capacity_schedule=None, result_save_csv_path=None)[source]

Run a time-stepping dynamic simulation.

Parameters:
  • simulation_period_sec (int) – Total simulation duration [s].

  • dt_s (int) – Time step size [s].

  • dhw_usage_schedule (list of tuple) – DHW schedule as (start_str, end_str, fraction) entries.

  • T0_schedule (array-like) – Dead-state temperature per time step [°C].

  • heater_capacity_const (float, optional) – Fixed heater power [W].

  • heater_capacity_schedule (array-like, optional) – Time-varying heater power [W].

  • result_save_csv_path (str, optional) – Path to save result CSV.

Returns:

Per-timestep simulation results.

Return type:

pd.DataFrame

enex_analysis.gas_boiler_tank module

Gas boiler with hot-water storage tank — dynamic model.

System chain:

Combustion Chamber → Hot Water Tank → 3-Way Mixing Valve → Service Water

The combustion model uses a constant thermal efficiency eta_comb to relate fuel input to useful heat. Exhaust gas losses are (1 − eta_comb) × E_NG.

Exergy topology (4 components):
  1. Combustion — NG chemical exergy, exhaust exergy

  2. Tank — stored, loss, destruction

  3. Mixing — destruction

  4. System total — NG exergy input

class enex_analysis.gas_boiler_tank.GasBoilerTank(eta_comb=0.9, T_exh=70.0, burner_capacity=15000.0, r0=0.2, H=0.8, x_shell=0.01, x_ins=0.1, k_shell=25, k_ins=0.03, h_o=15, T_tank_w_upper_bound=65.0, T_tank_w_lower_bound=60.0, T_mix_w_out=45.0, T_sup_w=10.0, dV_mix_w_out_max=0.001, tank_always_full=True, tank_level_lower_bound=0.5, tank_level_upper_bound=1.0, dV_tank_w_in_refill=0.001, prevent_simultaneous_flow=False, on_schedule=None, stc=None, uv=None)[source]

Bases: object

Gas-fired boiler with storage tank.

Combustion chamber heats water which is stored in an insulated tank. Service water is delivered via a 3-way mixing valve.

Parameters:
  • eta_comb (float)

  • T_exh (float)

  • burner_capacity (float)

  • r0 (float)

  • H (float)

  • x_shell (float)

  • x_ins (float)

  • k_shell (float)

  • k_ins (float)

  • h_o (float)

  • T_tank_w_upper_bound (float)

  • T_tank_w_lower_bound (float)

  • T_mix_w_out (float)

  • T_sup_w (float)

  • dV_mix_w_out_max (float)

  • tank_always_full (bool)

  • tank_level_lower_bound (float)

  • tank_level_upper_bound (float)

  • dV_tank_w_in_refill (float)

  • prevent_simultaneous_flow (bool)

  • on_schedule (list[tuple[float, float]] | None)

__init__(eta_comb=0.9, T_exh=70.0, burner_capacity=15000.0, r0=0.2, H=0.8, x_shell=0.01, x_ins=0.1, k_shell=25, k_ins=0.03, h_o=15, T_tank_w_upper_bound=65.0, T_tank_w_lower_bound=60.0, T_mix_w_out=45.0, T_sup_w=10.0, dV_mix_w_out_max=0.001, tank_always_full=True, tank_level_lower_bound=0.5, tank_level_upper_bound=1.0, dV_tank_w_in_refill=0.001, prevent_simultaneous_flow=False, on_schedule=None, stc=None, uv=None)[source]
Parameters:
  • eta_comb (float)

  • T_exh (float)

  • burner_capacity (float)

  • r0 (float)

  • H (float)

  • x_shell (float)

  • x_ins (float)

  • k_shell (float)

  • k_ins (float)

  • h_o (float)

  • T_tank_w_upper_bound (float)

  • T_tank_w_lower_bound (float)

  • T_mix_w_out (float)

  • T_sup_w (float)

  • dV_mix_w_out_max (float)

  • tank_always_full (bool)

  • tank_level_lower_bound (float)

  • tank_level_upper_bound (float)

  • dV_tank_w_in_refill (float)

  • prevent_simultaneous_flow (bool)

  • on_schedule (list[tuple[float, float]] | None)

analyze_steady(T_tank_w, T0, Q_heat_target, *, return_dict=True)[source]

Run a steady-state performance snapshot.

Parameters:
  • T_tank_w (float)

  • T0 (float)

  • Q_heat_target (float)

  • return_dict (bool)

Return type:

dict | DataFrame

analyze_dynamic(simulation_period_sec, dt_s, T_tank_w_init_C, dhw_usage_schedule, T0_schedule, tank_level_init=1.0, result_save_csv_path=None)[source]

Run a time-stepping dynamic simulation.

Parameters:
  • simulation_period_sec (int) – Total simulation duration [s].

  • dt_s (int) – Time step size [s].

  • T_tank_w_init_C (float) – Initial tank temperature [°C].

  • dhw_usage_schedule (array-like) – DHW usage schedule.

  • T0_schedule (array-like) – Outdoor temperature per step [°C].

  • tank_level_init (float) – Initial fractional tank level (0–1).

  • result_save_csv_path (str | None) – Optional CSV output path.

Returns:

Per-timestep result DataFrame.

Return type:

pd.DataFrame

postprocess_exergy(df)[source]

Compute gas-boiler exergy variables.

Exergy topology (4 components):

  1. NG chemical exergy, exhaust exergy

  2. Water exergy (tank inlet/outlet, mixing valve)

  3. Heat loss exergy, tank stored exergy

  4. Component-level exergy destruction

  5. Exergetic efficiency metrics

Parameters:

df (pd.DataFrame) – Result DataFrame from analyze_dynamic().

Returns:

DataFrame with exergy columns appended.

Return type:

pd.DataFrame

enex_analysis.simulation_runner module

enex_analysis.simulation_runner.simulate_ashp_step(args)[source]

Worker function for parallel ASHP simulation. args: (step, q_load, t0_val)

enex_analysis.solar_assisted_gas_boiler module

Solar-assisted gas boiler — dynamic hot-water tank model.

System chain (with tank):

STC → Combustion Chamber → Hot Water Tank → Mixing Valve → Service

The solar thermal collector (STC) is injected as a Subsystem (from subsystems.py). The combustion chamber supplements/replaces solar heat as needed. The STC’s mode (tank_circuit / mains_preheat) determines whether it operates on the tank loop or the mains water supply.

Exergy topology (5 components):
  1. NG chemical exergy, exhaust exergy

  2. STC exergy (via calc_exergy() protocol)

  3. Tank — stored, loss, destruction

  4. Mixing — destruction

  5. System total — NG + STC pump electricity

class enex_analysis.solar_assisted_gas_boiler.SolarAssistedGasBoiler(eta_comb=0.9, T_exh=70.0, burner_capacity=15000.0, r0=0.2, H=0.8, x_shell=0.01, x_ins=0.1, k_shell=25, k_ins=0.03, h_o=15, T_tank_w_upper_bound=65.0, T_tank_w_lower_bound=60.0, T_mix_w_out=45.0, T_sup_w=10.0, dV_mix_w_out_max=0.001, tank_always_full=True, tank_level_lower_bound=0.5, tank_level_upper_bound=1.0, dV_tank_w_in_refill=0.001, prevent_simultaneous_flow=False, on_schedule=None, stc=None, uv=None, stc_mode='tank_circuit', preheat_schedule=None, I_DN_schedule=None, I_dH_schedule=None)[source]

Bases: object

Gas boiler with solar thermal collector assist.

The STC is passed as the stc constructor argument and registered via the Subsystem protocol.

Parameters:
  • eta_comb (float)

  • T_exh (float)

  • burner_capacity (float)

  • r0 (float)

  • H (float)

  • x_shell (float)

  • x_ins (float)

  • k_shell (float)

  • k_ins (float)

  • h_o (float)

  • T_tank_w_upper_bound (float)

  • T_tank_w_lower_bound (float)

  • T_mix_w_out (float)

  • T_sup_w (float)

  • dV_mix_w_out_max (float)

  • tank_always_full (bool)

  • tank_level_lower_bound (float)

  • tank_level_upper_bound (float)

  • dV_tank_w_in_refill (float)

  • prevent_simultaneous_flow (bool)

  • on_schedule (list[tuple[float, float]] | None)

  • stc_mode (str)

  • preheat_schedule (list[tuple[float, float]] | None)

__init__(eta_comb=0.9, T_exh=70.0, burner_capacity=15000.0, r0=0.2, H=0.8, x_shell=0.01, x_ins=0.1, k_shell=25, k_ins=0.03, h_o=15, T_tank_w_upper_bound=65.0, T_tank_w_lower_bound=60.0, T_mix_w_out=45.0, T_sup_w=10.0, dV_mix_w_out_max=0.001, tank_always_full=True, tank_level_lower_bound=0.5, tank_level_upper_bound=1.0, dV_tank_w_in_refill=0.001, prevent_simultaneous_flow=False, on_schedule=None, stc=None, uv=None, stc_mode='tank_circuit', preheat_schedule=None, I_DN_schedule=None, I_dH_schedule=None)[source]
Parameters:
  • eta_comb (float)

  • T_exh (float)

  • burner_capacity (float)

  • r0 (float)

  • H (float)

  • x_shell (float)

  • x_ins (float)

  • k_shell (float)

  • k_ins (float)

  • h_o (float)

  • T_tank_w_upper_bound (float)

  • T_tank_w_lower_bound (float)

  • T_mix_w_out (float)

  • T_sup_w (float)

  • dV_mix_w_out_max (float)

  • tank_always_full (bool)

  • tank_level_lower_bound (float)

  • tank_level_upper_bound (float)

  • dV_tank_w_in_refill (float)

  • prevent_simultaneous_flow (bool)

  • on_schedule (list[tuple[float, float]] | None)

  • stc_mode (str)

  • preheat_schedule (list[tuple[float, float]] | None)

analyze_dynamic(simulation_period_sec, dt_s, T_tank_w_init_C, dhw_usage_schedule, T0_schedule, I_DN_schedule=None, I_dH_schedule=None, tank_level_init=1.0, result_save_csv_path=None)[source]

Run dynamic simulation with STC + gas boiler.

Parameters:
  • simulation_period_sec (int) – Total simulation duration [s].

  • dt_s (int) – Time step size [s].

  • T_tank_w_init_C (float) – Initial tank temperature [°C].

  • dhw_usage_schedule (array-like) – DHW usage schedule.

  • T0_schedule (array-like) – Outdoor temperature per step [°C].

  • I_DN_schedule (array-like, optional) – Direct-normal irradiance per step [W/m²].

  • I_dH_schedule (array-like, optional) – Diffuse-horizontal irradiance [W/m²].

  • tank_level_init (float) – Initial tank level (0–1).

  • result_save_csv_path (str | None) – Optional CSV output path.

Return type:

pd.DataFrame

postprocess_exergy(df)[source]

Compute solar-gas-boiler exergy variables.

Exergy topology (5 components):

  1. NG chemical exergy, exhaust exergy

  2. STC exergy via calc_exergy() protocol

  3. Water exergy (tank inlet/outlet, mixing valve)

  4. Heat loss / stored / tank destruction

  5. Exergetic efficiency

Parameters:

df (pd.DataFrame) – Result DataFrame from analyze_dynamic().

Returns:

DataFrame with exergy columns appended.

Return type:

pd.DataFrame

enex_analysis.tank_stratification_model module

Stratified tank model using TDMA (Tri-Diagonal Matrix Algorithm).

This module provides a 1D stratified hot-water tank model with vertical discretization. The model uses effective thermal conductivity to account for both molecular conduction and natural convection driven by buoyancy forces.

class enex_analysis.tank_stratification_model.StratifiedTankTDMA(H, N, r0, x_shell, x_ins, k_shell, k_ins, h_w, h_o, C_d_mix)[source]

Bases: object

TDMA-based 1D stratified hot-water tank model (vertical discretization).

This class models a cylindrical storage tank split into N vertical layers (nodes). Each node enforces an energy balance that includes:

  • Storage term via node thermal capacitance (C).

  • Effective thermal conduction between adjacent nodes using effective conductivity (k_eff) that accounts for both molecular conduction and natural convection driven by buoyancy forces.

  • Advection due to draw/inlet flow (G = rho_w * c_w * dV).

  • Heat loss to ambient through a per-node UA array (side for all nodes; bottom/top discs additionally for the end nodes).

  • Optional point heater applied at a single node.

  • Optional external loop advection across a node range in either direction, with loop heat input Q_loop.

Effective Thermal Conductivity Approach:

The model uses an effective thermal conductivity (k_eff) approach to integrate molecular conduction and natural convection effects. For each node pair (i, i+1), the effective conductivity is calculated based on:

  • Temperature difference (dT = T[i+1] - T[i])

  • Rayleigh number (Ra), which characterizes the buoyancy-driven flow

  • Nusselt number (Nu), which relates effective to molecular conductivity

Stable stratification (dT < 0, upper warmer than lower):

  • Convection is suppressed, primarily molecular conduction

  • Nu ≈ 1.0 with small correction terms

Unstable stratification (dT > 0, lower warmer than upper):

  • Natural convection enhances heat transfer

  • Nu > 1.0, increasing with Rayleigh number

  • Laminar (Ra < 1e7): Nu ∝ Ra^0.25

  • Turbulent (Ra ≥ 1e7): Nu ∝ Ra^0.33

The effective conduction coefficient between nodes is: K_eff = k_eff * A / dh, where k_eff = k_molecular * Nu

The semi-implicit time advance assembles a tri-diagonal linear system a, b, c, d and solves it with a TDMA routine (see TDMA()) to obtain next-step temperatures.

Units

  • Temperatures: K

  • Geometry: m

  • Volumetric flow: m³/s

  • UA, K: W/K

  • Heater power, heat flows: W

type H:

float

param H:

Tank height [m].

type H:

float

type N:

int

param N:

Number of vertical layers (nodes).

type N:

int

type r0:

float

param r0:

Inner radius of tank [m] (D = 2*r0).

type r0:

float

type x_shell:

float

param x_shell:

Shell thickness [m].

type x_shell:

float

type x_ins:

float

param x_ins:

Insulation thickness [m].

type x_ins:

float

type k_shell:

float

param k_shell:

Shell thermal conductivity [W/mK].

type k_shell:

float

type k_ins:

float

param k_ins:

Insulation thermal conductivity [W/mK].

type k_ins:

float

type h_w:

float

param h_w:

Internal convective heat transfer coefficient (water side) [W/m²K].

type h_w:

float

type h_o:

float

param h_o:

External convective heat transfer coefficient (ambient side) [W/m²K].

type h_o:

float

type C_d_mix:

float

param C_d_mix:

Empirical discharge coefficient for buoyancy-driven mixing [-]. (Note: This parameter is retained for compatibility but is not used in the effective conductivity approach.)

type C_d_mix:

float

H, D, N

Geometry and discretization (D = 2*r0).

Type:

float, float, int

A

Cross-sectional area [m²].

Type:

float

dh

Layer height [m].

Type:

float

V

Per-node volume [m³].

Type:

float

UA

Node-to-ambient UA per node [W/K], shape (N,).

Type:

np.ndarray

K

Reference axial conduction equivalent between nodes [W/K] (based on molecular conductivity only, for reference).

Type:

float

C

Per-node thermal capacitance [J/K].

Type:

float

C_d_mix

Mixing discharge coefficient [-] (retained for compatibility).

Type:

float

g

Gravitational acceleration [m/s²].

Type:

float

beta

Volumetric expansion coefficient of water [1/K].

Type:

float

nu

Kinematic viscosity of water [m²/s].

Type:

float

alpha

Thermal diffusivity of water [m²/s].

Type:

float

Pr

Prandtl number [-].

Type:

float

k_molecular

Molecular thermal conductivity of water [W/m·K].

Type:

float

Ra_critical

Critical Rayleigh number for stable stratification (≈1708).

Type:

float

k_eff

Effective thermal conductivity between node pairs [W/m·K], shape (N-1,), updated during each time step.

Type:

np.ndarray

K_eff

Effective conduction coefficient between node pairs [W/K], shape (N-1,), updated during each time step.

Type:

np.ndarray

G_use, G_loop

Flow-related terms cached from the last update step.

Type:

float

effective_conductivity(T_upper, T_lower)[source]

Calculate effective thermal conductivity between two nodes based on temperature difference and Rayleigh number.

update_tank_temp(...)[source]

Advance temperatures by one time step using the TDMA scheme. Heater and optional external loop can be applied. Heater and loop node indices are 1-based in the public API.

info(as_dict=False, precision=3)[source]

Print or return a concise summary of model geometry and thermal properties.

Notes

  • Heater/loop node indices are 1-based (converted to 0-based internally).

  • External loop terms are added to the TDMA coefficients to represent directed advection across a node range.

  • The effective conductivity approach replaces the previous Boussinesq mixing flow model, providing a more physically consistent representation of heat transfer in stratified tanks.

__init__(H, N, r0, x_shell, x_ins, k_shell, k_ins, h_w, h_o, C_d_mix)[source]
effective_conductivity(T_upper, T_lower)[source]

Calculate effective thermal conductivity between two adjacent nodes.

Integrates molecular conduction and buoyancy-driven natural convection into a single effective conductivity using the Rayleigh–Nusselt approach.

Stable stratification (dT < 0, upper warmer):

Convection is suppressed; heat transfer is primarily by conduction. Nu ≈ 1.0 with a small correction term.

Unstable stratification (dT > 0, lower warmer):

Buoyancy drives natural convection, enhancing heat transfer. - Ra < 1e3: Nu = 1.0 (conduction-dominated) - Ra < 1e7: Nu = 0.2 · Ra^0.25 (laminar convection) - Ra ≥ 1e7: Nu = 0.1 · Ra^0.33 (turbulent convection)

Parameters:
  • T_upper (float) – Temperature of the upper node [K].

  • T_lower (float) – Temperature of the lower node [K].

Returns:

k_eff – Effective thermal conductivity [W/m·K].

Return type:

float

References

Incropera & DeWitt, Fundamentals of Heat and Mass Transfer, 7th ed. Bejan, Convection Heat Transfer, 4th ed.

update_tank_temp(T, dt, T_in, dV_use, T_amb, T0, heater_node=None, heater_capacity=None, loop_outlet_node=None, loop_inlet_node=None, dV_loop=0.0, Q_loop=0.0)[source]

Advance node temperatures by one time step using the TDMA scheme.

Parameters:
  • T (np.ndarray) – Current node temperature array [K], shape (N,).

  • dt (float) – Time step size [s].

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

  • dV_use (float) – Draw-off volumetric flow rate [m³/s].

  • T_amb (float) – Ambient temperature [K].

  • T0 (float) – Dead-state (reference) temperature for exergy [K].

  • heater_node (int, optional) – 1-based node index where the heater is located.

  • heater_capacity (float, optional) – Heater thermal output [W].

  • loop_outlet_node (int, optional) – 1-based node index where the external loop exits the tank.

  • loop_inlet_node (int, optional) – 1-based node index where the external loop enters the tank.

  • dV_loop (float, optional) – External loop volumetric flow rate [m³/s].

  • Q_loop (float, optional) – Heat input from the external loop [W].

Returns:

Updated node temperatures for the next time step [K].

Return type:

np.ndarray

info(as_dict=False, precision=3)[source]

Print or return a summary of tank geometry and thermal properties.

Parameters:
  • as_dict (bool) – If True, return as dict; otherwise print a formatted summary.

  • precision (int) – Number of significant digits for display.

enex_analysis.tdma module

TDMA (Tri-Diagonal Matrix Algorithm) solver and related utilities.

Provides:

  • TDMA: solve tri-diagonal systems via matrix inversion

  • _add_loop_advection_terms: inject forced-convection advection terms into TDMA coefficient arrays

enex_analysis.tdma.TDMA(a, b, c, d)[source]

Solve tri-diagonal matrix system using TDMA (Tri-Diagonal Matrix Algorithm).

Reference: https://doi.org/10.1016/j.ijheatmasstransfer.2017.09.057 [Appendix B - Eq.(B7)]

Parameters:
  • a (np.ndarray) – Lower diagonal elements (length N-1)

  • b (np.ndarray) – Main diagonal elements (length N)

  • c (np.ndarray) – Upper diagonal elements (length N-1)

  • d (np.ndarray) – Right-hand side vector (length N)

Returns:

Solution vector (next time step temperatures)

Return type:

np.ndarray

Notes

If boundary conditions are not None, additional thermal resistances are added to the leftmost and rightmost columns, and surface temperatures are recalculated considering boundary layer thermal resistance.

enex_analysis.visualization module

Visualization and summary output functions.

enex_analysis.visualization.print_simulation_summary(df, simulation_time_step, dV_ou_a_design)[source]

Print a comprehensive summary of simulation results.

Parameters:
  • df (pd.DataFrame) – Simulation result DataFrame.

  • simulation_time_step (int) – Time step [s].

  • dV_ou_a_design (float) – Design airflow rate of outdoor unit [m3/s].

Return type:

None

enex_analysis.visualization.plot_th_diagram(ax, result, refrigerant, T_cond_bound=None, T_evap_bound=None, fontsize=None, tick_pad=None)[source]

Plot T-h diagram on given axis.

Parameters:
  • ax (Axes)

  • result (dict[str, float])

  • refrigerant (str)

  • T_cond_bound (dict[str, float | str] | None)

  • T_evap_bound (dict[str, float | str] | None)

  • fontsize (float | None)

  • tick_pad (float | None)

Return type:

None

enex_analysis.visualization.plot_ph_diagram(ax, result, refrigerant, fontsize=None, tick_pad=None)[source]

Plot P-h diagram on given axis.

Parameters:
  • ax (Axes)

  • result (dict[str, float])

  • refrigerant (str)

  • fontsize (float | None)

  • tick_pad (float | None)

Return type:

None

enex_analysis.visualization.plot_ts_diagram(ax, result, refrigerant, T_cond_bound=None, T_evap_bound=None)[source]

Plot T-s diagram on given axis with super heating/cooling considered.

Parameters:
  • ax (Axes)

  • result (dict[str, float])

  • refrigerant (str)

  • T_cond_bound (dict[str, float | str] | None)

  • T_evap_bound (dict[str, float | str] | None)

Return type:

None

Module contents

enex_analysis package.

The shared thermodynamic/heat-pump physics models live in the vendored tmhp git submodule, which uses a src layout (tmhp/src/tmhp/*.py). Make that package importable both as the top-level tmhp (matching the convention used by the docs/scripts) and as the enex_analysis.tmhp subpackage, so internal modules can keep using from .tmhp.X import ... after the constants/physics refactor.