Simulation helpers¶
Per-step state, energy / exergy helpers, and the stdout summary tables emitted at the end of a dynamic run.
Per-step dynamic context¶
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 tmhp.dynamic_context.ControlState(is_on, Q_heat_source, dV_tank_w_in_ctrl, result=<factory>)[source]
Bases:
objectHeat-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 tmhp.dynamic_context.CycleSolveOutcome(success, x, failure_reason, detail=None)[source]
Bases:
objectOutcome of a boiler’s evaporator-approach search for one request.
successisTrueonly when the returned approachxgives a cycle that closes both heat exchangers and passesunphysical_cycle_detail(). Otherwisexis NaN andfailure_reasonsays why (cycle_invalid,pr_above_max,hx_not_convergedoroptimizer_failed);detailrefinescycle_invalidwhen the cycle existed but was not an operating point.- Parameters:
success (
bool)x (
float)failure_reason (
str)detail (
str|None)
- success: bool
- x: float
- failure_reason: str
- detail: str | None = None
- __init__(success, x, failure_reason, detail=None)
- Parameters:
success (
bool)x (
float)failure_reason (
str)detail (
str|None)
- class tmhp.dynamic_context.DutyLimit(T_zero_C, K, Q_min=0.0)[source]
Bases:
objectLargest duty a running compressor gives a mixed tank on an operating limit.
K * (T_zero_C - T)[W] at tank temperatureT[°C]: a limit on the condensing temperature of a compressor whose tank heat exchanger needs an approach proportional to the duty (T_zero_C: the tank temperature at which the limit leaves no duty;K[W/K]: the heat the exchanger carries per kelvin of approach).Q_min[W] is the smallest duty the compressor runs at continuously: where the limit leaves less (stop_C) it stops.- Parameters:
T_zero_C (
float)K (
float)Q_min (
float)
- T_zero_C: float
- K: float
- Q_min: float = 0.0
- duty(T_C)[source]
Duty the limit allows at tank temperature
T_C[W].K (T_zero_C - T_C), and at or belowstop_Cnever less thanQ_min. That is the line’s own value there; the bound only keeps the last digits from saying otherwise (stop_CisT_zero_C - Q_min / Kin floating point, and the line computed back from it falls a few 1e-11 W short ofQ_minfor most numbers), so that a compressor on the limit is never resolved below its smallest continuous duty.- Parameters:
T_C (
float)- Return type:
float
- knee_C(Q_on)[source]
Tank temperature above which the limit allows less than
Q_on[°C].- Parameters:
Q_on (
float)- Return type:
float
- property stop_C: float
Tank temperature at which the limit allows no more than
Q_min[°C].
- __init__(T_zero_C, K, Q_min=0.0)
- Parameters:
T_zero_C (
float)K (
float)Q_min (
float)
- tmhp.dynamic_context.DUTY_MATCH_RTOL: float = 0.001
Fraction by which a cycle may miss the duty asked of it and still count as delivering it, in reduced-duty charging.
A cycle asked for the condensing limit’s duty at a tank temperature on the limit delivers it to the solver’s last digits when that limit is the one that governs (measured ratio 1.000000 on the documented charges of the three boiler families), and so does a cycle asked for the nameplate duty below the limit. One that is off by more than this was held by another limit. Used where the stretch on the limit is qualified (
tmhp.compressor_envelope.condensing_stretch()) and for the cycles of a step resolved on the limit (resolve_step_operation()).
- class tmhp.dynamic_context.DynamicState(T_tank_w_K, tank_level, is_refilling, hp_is_on_prev, dV_tank_w_out_prev, hp_running_prev=False, hp_phase_age_s=inf, subsystem_state=<factory>)[source]
Bases:
objectCarried state threaded across
step()calls.This is exactly the state that
analyze_dynamicused to hold in loop-locals (T_tank_w_K,tank_level,is_refilling,hp_is_on_prev) plus the one cross-step coupling that previously lived as aself.dV_tank_w_outside-effect (dV_tank_w_out_prevhere).step()returns a freshDynamicStateeach call and reads none of these fromself, so a model can be advanced one timestep at a time by an external co-simulation master (FMI/EnergyPlus) and re-run independently.- T_tank_w_K
Tank water temperature carried into the next step [K].
- Type:
float
- tank_level
Fractional tank fill level (0–1).
- Type:
float
- is_refilling
Refill hysteresis latch.
- Type:
bool
- hp_is_on_prev
Call for heat at the end of the previous step (cycling hysteresis). A step whose cycle could not be solved keeps the call, so the next step retries instead of waiting for the tank to reach its lower bound.
- Type:
bool
- dV_tank_w_out_prev
Previous step’s tank draw-off flow [m³/s]; consumed by the next step’s refill decision.
- Type:
float
- hp_running_prev
Whether the compressor was running at the end of the previous step. Differs from
hp_is_on_prevwhen the call stands but the cycle could not be solved, or a minimum on/off time holds the compressor.- Type:
bool
- hp_phase_age_s
Time the compressor has been in its current running state (on or off) at the end of the previous step [s];
infat the start of a run. Read by the minimum on/off time rules.- Type:
float
- subsystem_state
State the subsystems carry from one step to the next, keyed by subsystem name (e.g.
{"stc": {"pump_on": True, ...}}for the collector-loop controller: pump latch, storage-limit hold, stagnation lock-out). Empty at the start of a run. Each value is a plain dict of bools and numbers, replaced (never mutated) every step, so aDynamicStatecan be kept, copied or pickled and a step re-run from it gives the same result. SeeSubsystemfor how a subsystem reads and writes its entry.- Type:
dict[str, dict]
- Parameters:
T_tank_w_K (
float)tank_level (
float)is_refilling (
bool)hp_is_on_prev (
bool)dV_tank_w_out_prev (
float)hp_running_prev (
bool)hp_phase_age_s (
float)subsystem_state (
dict)
- T_tank_w_K: float
- tank_level: float
- is_refilling: bool
- hp_is_on_prev: bool
- dV_tank_w_out_prev: float
- hp_running_prev: bool = False
- hp_phase_age_s: float = inf
- subsystem_state: dict
- __init__(T_tank_w_K, tank_level, is_refilling, hp_is_on_prev, dV_tank_w_out_prev, hp_running_prev=False, hp_phase_age_s=inf, subsystem_state=<factory>)
- Parameters:
T_tank_w_K (
float)tank_level (
float)is_refilling (
bool)hp_is_on_prev (
bool)dV_tank_w_out_prev (
float)hp_running_prev (
bool)hp_phase_age_s (
float)subsystem_state (
dict)
- class tmhp.dynamic_context.InStepRun(runtime_fraction, running_start, running_end, call_end, starts, phase_age_end_s, T_on_mean_C, heat_unavailable, T_on_first_C=None, limit_stop=False, reduced_fraction=0.0, T_reduced_mean_C=None, T_full_mean_C=None, limit_stop_C=None, reduced_withheld=False)[source]
Bases:
objectCompressor operation inside one step, resolved at thermostat events.
- runtime_fraction
Fraction of the step the compressor ran (0-1). Heat, power and flow rates of a running cycle are multiplied by it to give the step-average rates.
- Type:
float
- running_start
Whether the compressor was running at the start of the step.
- Type:
bool
- running_end
Whether it was running at the end of the step.
- Type:
bool
- call_end
Thermostat call for heat at the end of the step.
- Type:
bool
- starts
Off-to-on transitions of the compressor inside the step (a start at
t = 0counts when it was off at the end of the previous step).- Type:
int
- phase_age_end_s
Time the compressor has been in its end-of-step running state [s].
- Type:
float
- T_on_mean_C
Run-time-weighted mean tank temperature while the compressor ran [°C];
Noneif it did not run.- Type:
float | None
- T_on_first_C
Tank temperature when the compressor first ran in the step (the step start if it ran from there) [°C];
Noneif it did not run.- Type:
float | None
- heat_unavailable
The compressor was to run but had no heat to give (no cycle could be solved), so it did not; the call stands for the next step.
- Type:
bool
- limit_stop
The cut-out
T_limit_Cofsimulate_thermostat_step()stopped the compressor, or kept it from starting, while the thermostat (its call, or a minimum run time) would have had it run: a protection stop, not the thermostat reaching its upper bound.- Type:
bool
- reduced_fraction
Fraction of the step the compressor ran on the duty limit, below the duty it runs at otherwise (0 without a
duty_limit); part ofruntime_fraction.- Type:
float
- T_reduced_mean_C
Run-time-weighted mean tank temperature of that stretch [°C]: the limit’s duty at it is the stretch’s mean duty.
Nonewithout one.- Type:
float | None
- T_full_mean_C
Run-time-weighted mean tank temperature of the rest of the run, at the full duty [°C]; set only with a
duty_limit.- Type:
float | None
- limit_stop_C
The tank cut-out that stopped a run resolved with a
duty_limit[°C]: the lower of the boiling point and the tank temperature at which the limit leaves the smallest continuous duty, which the caller does not know before the step is resolved (in_step_stop_reason()names the stop from it).Nonewithout alimit_stop, and for a run resolved with the cut-out the caller gave (T_limit_C), who names it. It labels the run and is not part of comparing two runs.- Type:
float | None
- reduced_withheld
Reduced-duty charging was withheld in this step (
resolve_step_operation()): it was resolved without the duty limit, exactly as for a compressor that stops at the cut-out, and that cut-out, below the boiling point, acted in it – the compressor stopped, or stayed off, where it would otherwise have charged on. A stop at the boiling point is not marked. Likelimit_stop_Cit labels the run and is not part of comparing two.- Type:
bool
- Parameters:
runtime_fraction (
float)running_start (
bool)running_end (
bool)call_end (
bool)starts (
int)phase_age_end_s (
float)T_on_mean_C (
float|None)heat_unavailable (
bool)T_on_first_C (
float|None)limit_stop (
bool)reduced_fraction (
float)T_reduced_mean_C (
float|None)T_full_mean_C (
float|None)limit_stop_C (
float|None)reduced_withheld (
bool)
- runtime_fraction: float
- running_start: bool
- running_end: bool
- call_end: bool
- starts: int
- phase_age_end_s: float
- T_on_mean_C: float | None
- heat_unavailable: bool
- T_on_first_C: float | None = None
- limit_stop: bool = False
- reduced_fraction: float = 0.0
- T_reduced_mean_C: float | None = None
- T_full_mean_C: float | None = None
- limit_stop_C: float | None = None
- reduced_withheld: bool = False
- __init__(runtime_fraction, running_start, running_end, call_end, starts, phase_age_end_s, T_on_mean_C, heat_unavailable, T_on_first_C=None, limit_stop=False, reduced_fraction=0.0, T_reduced_mean_C=None, T_full_mean_C=None, limit_stop_C=None, reduced_withheld=False)
- Parameters:
runtime_fraction (
float)running_start (
bool)running_end (
bool)call_end (
bool)starts (
int)phase_age_end_s (
float)T_on_mean_C (
float|None)heat_unavailable (
bool)T_on_first_C (
float|None)limit_stop (
bool)reduced_fraction (
float)T_reduced_mean_C (
float|None)T_full_mean_C (
float|None)limit_stop_C (
float|None)reduced_withheld (
bool)
- tmhp.dynamic_context.EVENT_TIME_TOL_S: float = 1e-06
Time width [s] within which a switching event counts as at the step end (it then happens at the start of the next step). Event times carry the same root-solve noise (~1e-10 s for a 15 kW / 151 L tank per 1e-9 K), and without this width a stop or start right at a step boundary would be counted in one step or the next by platform.
- class tmhp.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:
objectPer-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)
- tmhp.dynamic_context.TEMPERATURE_TOL_K: float = 1e-06
Temperature width [K] within which the tank counts as at a thermostat bound. The tank temperature at a step boundary comes from an implicit root solve, so a tank that ends a step on a bound lands a few 1e-9 K on either side of it depending on the platform’s floating-point path. An exact comparison then turns the next step’s call – and with it
hp_is_onandhp_starts [-]– on or off by machine. 1e-6 K is far above that noise and far below anything a thermostat resolves.
- tmhp.dynamic_context.bound_tolerance(T_lower, T_upper)[source]
Width [K] for the bound comparisons of a
[T_lower, T_upper]band.TEMPERATURE_TOL_K, but at most a quarter of the band, so the “at the lower bound” and “at the upper bound” tests never overlap: with an overlap the lower test, checked first, would keep the call on at the upper bound and the compressor would run past it. A degenerate band (T_lower >= T_upper) gets no width (exact comparisons).- Parameters:
T_lower (
float)T_upper (
float)
- Return type:
float
- class tmhp.dynamic_context.Subsystem(*args, **kwargs)[source]
Bases:
ProtocolPluggable 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.
Carried state¶
A subsystem with memory between steps (a controller latch, a lock-out) does not keep it on its own instance: it is part of the run and travels in
DynamicState.subsystem_state[name].Read: during a step the host model holds the previous step’s states in
host._subsystem_state_in({}at the start of a run); the subsystem’s entry ishost._subsystem_state_in.get(name, {}). It must not be modified. The host’s hooks (_run_subsystems,_augment_results) read it there; a subsystem object stepped through this protocol has no reference to its host, so the hook that calls it hands the entry over.Write: the subsystem puts its next state, a new plain dict, under
SUBSYSTEM_STATE_KEY("carried_state") of the dict itsstep()returned, at the latest inassemble_results()(the state may depend on the solved tank temperature). The host gathers these withcollect_subsystem_state().
A
step()-driven host (ASHPB) threads the states through theDynamicStateit returns; a host that only offersanalyze_dynamic(GSHPB) keeps them for the run and clears them when a run starts. Either way a second run with the same inputs starts from empty state.- 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 the following keys:
'Q_contribution'(float) — net energy contribution to the tank [W].'E_subsystem'(float) — electrical power consumed [W].'T_tank_w_in_override_K'(float | None) — heated tank-inlet temperature [K] if the subsystem modifies the inlet (e.g. mains preheat);Noneif there is 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 bystep().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)
- class tmhp.dynamic_context.SubsystemExergy(columns, X_tot_add=0.0, X_in_tank_add=0.0, X_out_tank_add=0.0)[source]
Bases:
objectSubsystem-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)
- tmhp.dynamic_context.SUBSYSTEM_STATE_KEY: str = 'carried_state'
Key under which a subsystem’s step dict carries its next-step state.
- tmhp.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[tuple[float,float]]) – List of(start_hour, end_hour)operating windows.
- Return type:
bool
- tmhp.dynamic_context.collect_subsystem_state(previous, sub_states)[source]
Next
DynamicState.subsystem_statefrom this step’s subsystem dicts.Each subsystem whose step dict has a
SUBSYSTEM_STATE_KEYentry contributes a copy of it; a subsystem that reported none keeps its previous entry. A new dict is returned andpreviousis not modified, so the state a step was given can be stepped from again.- Parameters:
previous (
Mapping[str,dict])sub_states (
Mapping[str,Any])
- Return type:
dict[str,dict]
- tmhp.dynamic_context.delivered_tank_heat(result)[source]
Condenser heat a step puts into the tank [W].
The heat the solved cycle rejects (
Q_ref_tank [W]), and zero unless the compressor actually ran. Never the requested capacity: a request the cycle could not meet delivers nothing.- Parameters:
result (
Mapping[str,Any])- Return type:
float
- tmhp.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
- tmhp.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).Nonemeans always-full sentinel (no PSF).- Return type:
tuple[float|None,bool]
Notes
dV_tank_w_outis the draw expected over the step. The returned make-up is a step-average rate:tank_always_full=False: the refill valve is followed through the step (_refill_within_step()). It opens when the falling level reachestank_level_lower_boundand closes when it is back attank_level_upper_bound, at any point of the step, and admitsdV_tank_w_in_refillwhile open.prevent_simultaneous_flow: no make-up in a step that draws; otherwisedV_tank_w_in_refilluntil the tank is full.
Either way a step whose full-rate refill would overshoot the target takes the part that reaches it. It used to take none: with
dV_tank_w_in_refill·dtabove the tank volume (the default 1 L/s at any step above 151 s) the tank never refilled. The tank balance then limits both flows to what the tank can pass (limit_tank_flows()).
- tmhp.dynamic_context.in_step_stop_reason(run, T_limit_C, run_limit_s=inf)[source]
hp_stop_reasonof a step: why a cut-out stopped the compressor,Noneif none did.The stop is the one the step was resolved with (
run.limit_stop_C;T_limit_C, the cut-out the boiler passed, for a run that does not carry it). A tank cut-out below the boiling point, or a coil cut-out (a finiterun_limit_s), is the envelope stop (STOP_CONDENSING_LIMIT); otherwise it is the boiling point (STOP_BOILING_LIMIT). With reduced-duty charging the stop that acts is the lower of the boiling point and the tank temperature at which the condensing limit leaves the smallest continuous duty, which a boiler does not know before the step is resolved: the run says which it was. Such a stop is a normal end of the run (nofailure_reason): the heat pump has charged the tank as far as its compressor allows.- Parameters:
run (
InStepRun)T_limit_C (
float)run_limit_s (
float)
- Return type:
str|None
- tmhp.dynamic_context.resolve_step_operation(*, T_start_K, call_start, running_prev, phase_age_s, scheduled, T_lower, T_upper, dt, C_curr, C_next, C_tank, residual_free, solve_cycle, Q_request, min_on_time_s=0.0, min_off_time_s=0.0, T_limit_C=100.0, run_limit_s=inf, Q_hold=0.0, duty_line=None, min_duty=None, solve_cycle_at_duty=None, rate_keys=())[source]
Compressor operation in one step and the cycle it ran.
residual_free(T_K)is the boiler’s own implicit tank residual built with a zero heat-source rate; it supplies the heat the tank gains or loses from everything else (tank_free_heat_rate()), linearised betweenmin(T_start, T_lower)andmax(T_start, T_upper). The thermostat integratesC_curr·dT/dt(the start-of-step capacity); for a tank whose level changes in the step the free heat is taken in that temperature form, so the make-up enters asρc·V̇_in·(T_in - T)and the draw, which leaves at the tank temperature, does not changeT.C_nextis accepted for compatibility and not used.solve_cycle(T_C)returns the boiler’s cycle result at tank temperatureT_C(a running result, or an off-mode row with afailure_reason);Q_request[W] is the heat it is asked for.Two passes, one cycle solve:
the thermostat events with the compressor delivering
Q_request, which gives when it runs and the mean tank temperature while it does;the cycle solved once at that mean temperature (midpoint rule: the quasi-steady cycle the step’s run averages to; if it has no operating point there, at the temperature the run starts from), and the events again with the heat that cycle delivers (zero if it has no operating point).
solve_cycle(T_C, runtime_fraction)returns the boiler’s cycle result at tank temperatureT_C;runtime_fractionis the run time the first pass expects, for boilers whose source responds to the step-average load. Each step searches its operating point from scratch: starting from the previous step’s point would change which candidates the search evaluates, and so its optimum.T_limit_C(tank cut-out, default the boiling point),run_limit_sandQ_hold(coil cut-out of a multi-node tank and its holding heat) are passed tosimulate_thermostat_step(): a boiler gives its envelope stop, so the compressor stops there inside the step whatever its minimum run time.Reduced-duty charging (
duty_line,min_duty,solve_cycle_at_duty,rate_keysall given; a mixed tank). The boiler’s compressor does not stop where its requested duty meets an operating limit: it runs on at the largest duty the limit allows.duty_line = (T_zero_C, K)is that duty as a function of the tank temperature,K (T_zero_C - T)[W] (DutyLimit), andmin_duty()the smallest duty the compressor runs at continuously in this step’s conditions [W], orNonewhen reduced-duty charging is withheld in them (below); it is called – it costs cycle solves – only for a step that gets to the limit.T_limit_Cis the cut-out of the compressor that stops instead, as without these arguments (the tank temperature at which the nameplate duty meets the limit, or the boiling point); on the limit the cut-out is the limit’s stop, at the latest the boiling point. A step that gets to the limit is resolved with the events ofsimulate_thermostat_step()on that limit, and its run has up to two stretches, each with one cycle:at the full duty, the cycle
solve_cyclegives at the stretch’s mean tank temperature (as above);on the limit,
solve_cycle_at_duty(T_C, Q, runtime_fraction)at the stretch’s mean tank temperature and the limit’s duty there. The limit is linear in the tank temperature, so that is the stretch’s mean duty exactly, and the condensing pressure is the limit’s all along: only the duty varies over the stretch, and the cycle at its mean is the midpoint rule in that one variable.
The cycle returned is then the run-time-weighted mean of the two (
merge_running_rows()overrate_keys), whichstep_hp_result()averages over the step like any other. Each stretch’s cycle is given the run time that carries the step’s mean load at its own duty. A step that does not get to the limit is resolved exactly as without these arguments, with the cut-out at the limit’s knee. The round-off confirmation below (the implicit solve of the full step) assumes one heat rate for the step and is not applied to a step on the limit.The events take the limit’s duty for the whole stretch above the knee. That is right where this limit is the one that governs the stretch, and the caller says so for the step’s source conditions:
min_duty()returnsNonewhere it is not (another limit holds the compressor below this one’s duty somewhere on the stretch, or leaves it no operating point, or no duty runs below the request). Reduced-duty charging is then withheld: the step is resolved again from the start exactly as without these arguments – the compressor that stops atT_limit_C, the same events and the same cycle solves – and the run says so where that cut-out then acts (reduced_withheld;reduced_fractionis 0; with the duty its cycle delivers a withheld step may also end below the cut-out, and is then an ordinary step; and whereT_limit_Cis the boiling point the stop that acts is that one, which is not marked). A step whose knee lies at or above the boiling point never gets to the limit and is resolved as without these arguments. What the caller says of the step’s conditions does not depend on the step or on where in the stretch the tank is. One check of the step itself stands behind it, so that no step is credited with heat its cycles do not deliver and none under another limit is counted as on this one: each cycle of a step on the limit has to deliver the duty the events took for its stretch (the request below the knee, the limit’s duty at the stretch’s mean above it) toDUTY_MATCH_RTOL, and to name no limit as holding it but this one (the condensing limit:capacity_bindingis absent or"condensing_temperature"). A step in which one does not – it has no operating point, or another limit holds it although the caller gave a duty – is withheld the same way. That includes a full-duty cycle that fails outright: whether the compressor then runs at all is for the step resolved without these arguments to say, with its own cycle solves. That second check does depend on the step: its cycles are solved at the means of the step’s own stretches, which move with the step length and with the tank temperature the step starts from. Where the caller’s answer is right for the whole stretch the check never acts, and adds no dependence on the step to what the events and the closing balance have of their own. Where another limit acts on a part of the stretch the caller did not look at, a step is withheld or not by where its cycle lands, and the charge then depends on the step size (measured indocs/source/developer/reference-operating-limits.rst, Where it applies).A compressor stopped at the limit’s stop rests for its minimum rest time before it restarts (
duty_limitofsimulate_thermostat_step()).Returns the
InStepRunand the cycle result (Noneif the compressor never had to run in this step).When the linearised model puts a switching event within round-off of the step end, the implicit solve of the full step decides: a step the compressor runs through without its tank reaching the upper bound, or rests through without reaching the lower bound, keeps its single-rate result.
- Parameters:
T_start_K (
float)call_start (
bool)running_prev (
bool)phase_age_s (
float)scheduled (
bool)T_lower (
float)T_upper (
float)dt (
float)C_curr (
float)C_next (
float)C_tank (
float)Q_request (
float)min_on_time_s (
float)min_off_time_s (
float)T_limit_C (
float)run_limit_s (
float)Q_hold (
float)duty_line (
tuple[float,float] |None)min_duty (
Callable[[],float|None] |None)solve_cycle_at_duty (
Callable[[float,float,float],dict] |None)rate_keys (
tuple[str,...])
- Return type:
tuple[InStepRun,dict|None]
- tmhp.dynamic_context.scale_running_rates(result, fraction, keys)[source]
Turn a running cycle’s rates into step averages (in place).
keysare the heat, power and flow rates of the heat-pump circuit; each finite numeric value is multiplied byfraction. State quantities (temperatures, pressures, COP, efficiencies, speed) keep the running values. Addsruntime_fraction [-].- Parameters:
result (
dict)fraction (
float)keys (
tuple[str,...])
- Return type:
dict
- tmhp.dynamic_context.simulate_thermostat_step(*, T_start_C, call_start, running_prev, phase_age_s, scheduled, T_lower, T_upper, dt, C, free_heat, Q_on, min_on_time_s=0.0, min_off_time_s=0.0, T_limit_C=100.0, run_limit_s=inf, Q_hold=0.0, duty_limit=None, closing_heat=None)[source]
Resolve the on/off thermostat inside one step at its switching events.
The tank is one fully mixed node,
C·dT/dt = s(t)·Q_on + P(T), wheresis the compressor state andPthe heat rate from everything else (draw-off, envelope loss, subsystems), taken as the straight line through the two(T [°C], P [W])points infree_heat. Between events the temperature follows the exact solution of that linear equation; events are the tank reaching the lower bound (call on), the upper bound orT_limit_C(call off), and a minimum on/off time running out. The compressor delivers the constant condenser heatQ_on[W] while it runs;Q_on <= 0means no cycle exists, and a compressor asked to run then stays off (heat_unavailable).- Parameters:
T_start_C (
float) – Tank temperature at the start of the step [°C].call_start (
bool) – Thermostat call at the start of the step (hysteresis and schedule applied, asdetermine_heat_source_on_off()gives it).running_prev (
bool) – Compressor state at the end of the previous step and how long it had been in it [s].phase_age_s (
float) – Compressor state at the end of the previous step and how long it had been in it [s].scheduled (
bool) – Whether the operating schedule allows the heat pump in this step.T_lower (
float) – Hysteresis bounds [°C].T_upper (
float) – Hysteresis bounds [°C].dt (
float) – Step length [s].C (
float) – Tank heat capacity [J/K].min_on_time_s (
float) – Minimum compressor run and rest times [s]. A minimum run holds the compressor past the upper bound (up toT_limit_C); a minimum rest delays a start the call asks for.min_off_time_s (
float) – Minimum compressor run and rest times [s]. A minimum run holds the compressor past the upper bound (up toT_limit_C); a minimum rest delays a start the call asks for.T_limit_C (
float) – Tank cut-out [°C], for a tank whose water is the coil’s: it stops a running compressor whatever its minimum run time, and above it the compressor does not start. The call is the thermostat’s (T_lower,T_upper); the cut-out does not end it. While the call stands at the cut-out the compressor holds the tank there: it runs the share of the time that balances the tank’s free heat atT_limit_C(cycling on its protection, or a variable-speed unit at the duty the limit allows) until the call ends or the step does, as one run (one start at most). That is the limit of a restart with no differential (start as soon as the tank is below the cut-out, stop at it), which the fast-cycling limit below would reach after 1000 events; a tank above the cut-out cools to it first (an event). The default is the boiling point (constructors refuse bounds above 100 °C, so it acts when a minimum run time holds the compressor past the upper bound); GSHPB and WSHPB pass the tank temperature at which their compressor envelope stops them (tmhp.compressor_envelope.condensing_tank_cutout()), so the protection stop happens inside the step, not at a step boundary.run_limit_s (
float) – Cut-out of the water around a multi-node tank’s coil, which can be hotter than the meanTthis model follows: afterrun_limit_sof running in the step [s] (the time the boiler found the coil’s water to reach its envelope stop; 0: already there;inf: not in this step) the compressor stops, and while the call stands it holds that water there by givingQ_hold[W] (runningQ_hold / Q_onof the time; 0: it stays off for the rest of the step).Q_hold (
float) – Cut-out of the water around a multi-node tank’s coil, which can be hotter than the meanTthis model follows: afterrun_limit_sof running in the step [s] (the time the boiler found the coil’s water to reach its envelope stop; 0: already there;inf: not in this step) the compressor stops, and while the call stands it holds that water there by givingQ_hold[W] (runningQ_hold / Q_onof the time; 0: it stays off for the rest of the step).duty_limit (
DutyLimit|None) – A compressor that reduces its duty on an operating limit instead of stopping (an inverter on its condensing limit). Above the tank temperature at which the limit allowsQ_on(DutyLimit.knee_C()) the running compressor delivers the limit’s duty,K (T_zero - T), so the tank followsC dT/dt = K (T_zero - T) + P(T)– again a linear equation, solved exactly between events; the knee is an event. The tank cut-out is then where the limit leaves no more than the smallest continuous duty (DutyLimit.stop_C, never aboveT_limit_C; the knee when the floor is not belowQ_on). What a compressor stopped there does while the call stands depends on its minimum rest time. With one (min_off_time_s > 0) the stop is a real one: the compressor rests for that time while the tank cools, restarts (an event: a counted start, the phase age from it) and runs back to the cut-out, so the run time, the starts and the timers describe the same compressor. Without one it holds the tank there by cycling at the cut-out’s duty, which is what those rests and restarts tend to as the rest time goes to zero: a mean of on/off cycling without a differential, reported as one run (one start,running_endtrue,phase_age_end_scounting from that start although the compressor was on forruntime_fractionof the time). Either way, a tank that loses more at the cut-out than the duty the limit leaves there is not held and not stopped: the compressor runs on, and the tank settles below the cut-out where the limit’s duty is the loss. Above the cut-out the compressor never runs, so it never delivers less thanQ_minon the limit (a tank withinTEMPERATURE_TOL_Kabove the cut-out is at it). A called tank above the cut-out cools to it and is held from there; the heat of that hold in the step it begins in is the one the implicit balance closing the step needs to end at the cut-out (closing_heat), so that the next step finds the tank at the cut-out and the hold is one start (without it the step ended above the cut-out, by the loss the warmer tank had on the way, and the next step counted a stop and a start). The run reports the stretch on the limit separately (reduced_fraction,T_reduced_mean_C,T_full_mean_C): the mean duty of the stretch is the limit’s duty at its mean temperature, exactly, whatever the step. Mixed tanks only: not combined withrun_limit_s/Q_hold.None: the compressor deliversQ_onwhenever it runs.closing_heat (
Callable[[float],float] |None) – With aduty_limitonly: the heat [J] the compressor has to give in this step for the balance the caller closes the step with to end at a tank temperature [°C] (negative: without any heat the step ends above it). It decides whether a tank that cooled to the cut-out in this step is held in it, and with how much heat; the caller’s own balance is asked because it need not be the straight line offree_heat(resolve_step_operation()passes the boiler’s implicit tank residual).None: the implicit balance of that line,dt (-P(T)) - C (T_start - T).thermostat (A stop or a blocked start either cut-out causes while the)
also (would have run sets limit_stop (with a duty_limit)
limit_stop_C
gave). (the cut-out the limit)
the (More than 1000 switching events in one step (a band too narrow for)
limit (step) are closed by the fast-cycling)
rest (temperature it reached and the compressor runs the fraction of the)
there. (of the step that balances the tank)
free_heat (
tuple[tuple[float,float],tuple[float,float]])Q_on (
float)
- Return type:
InStepRun
- tmhp.dynamic_context.step_hp_result(run, cycle_result, off_row, keys)[source]
The heat-pump part of a step’s result row.
A compressor that ran reports its cycle with the rates in
keysaveraged over the step (scale_running_rates()); one that was to run but had no cycle reports the cycle’s off-mode failure row; otherwiseoff_row()gives the off-mode row. Every row carriesruntime_fraction [-]andhp_starts [-].- Parameters:
run (
InStepRun)cycle_result (
dict|None)keys (
tuple[str,...])
- Return type:
dict
- tmhp.dynamic_context.REDUCED_DUTY_FRACTION_KEY: str = 'reduced_duty_fraction [-]'
Row key of a boiler built with
condensing_limit_control="reduce_duty": the fraction of the step the compressor ran at reduced duty on the condensing limit (InStepRun.reduced_fraction; 0 when it did not). It is part ofruntime_fraction [-].
- tmhp.dynamic_context.REDUCED_DUTY_WITHHELD_KEY: str = 'reduced_duty_withheld'
None, or what withheld reduced-duty charging in a step that was therefore resolved ascondensing_limit_control="stop"resolves it and in which the nameplate cut-out acted (InStepRun.reduced_withheld;tmhp.compressor_envelope.condensing_stretch()has the values).- Type:
Row key of the same boilers
- tmhp.dynamic_context.STOP_BOILING_LIMIT: str = 'boiling_limit'
hp_stop_reasonof a step the boiling cut-out stopped inside.
- tmhp.dynamic_context.STOP_CONDENSING_LIMIT: str = 'condensing_limit'
hp_stop_reasonof a step the compressor envelope stopped inside (in_step_stop_reason()).
- tmhp.dynamic_context.T_WATER_BOIL_C: float = 100.0
Boiling point of the stored water at atmospheric pressure [°C].
The heat pump never drives a tank past it: the in-step thermostat treats it as an absolute cut-out on top of the upper set point. Constructors already refuse set points above 100 °C (
tmhp._validation); the cut-out matters when a minimum on-time holds the compressor past the set point.
- tmhp.dynamic_context.TANK_LEVEL_MIN: float = 0.001
Lowest fill level of a tank whose level varies [-].
A level-varying tank (
tank_always_full=False, orprevent_simultaneous_flow) keeps this much water: a draw that would take it lower is cut to the water above it plus the step’s make-up, and the cut is reported as unmet hot water (dV_mix_w_out_unmet [m3/s]). The value is the floor the tank heat capacity used to be clamped to; the clamp now has the water behind it, so it no longer creates energy.
- class tmhp.dynamic_context.TankStepFlows(alp, dV_tank_w_out, dV_tank_w_in, level_next, dV_mix_w_out, dV_mix_w_out_unmet)[source]
Bases:
objectTank-side flows of one step at the end-of-step tank temperature.
- alp
Mixing-valve hot share at the end-of-step tank temperature [-].
- Type:
float
- dV_tank_w_out
Hot water leaving the tank for the mixing valve [m³/s].
- Type:
float
- dV_tank_w_in
Make-up water entering the tank [m³/s].
- Type:
float
- level_next
End-of-step fill level [-].
- Type:
float
- dV_mix_w_out
Mixed water delivered at the set point [m³/s]: the demand, less what the tank could not supply.
- Type:
float
- dV_mix_w_out_unmet
Mixed-water demand the tank could not supply [m³/s] (a level-varying tank at
TANK_LEVEL_MIN).- Type:
float
- Parameters:
alp (
float)dV_tank_w_out (
float)dV_tank_w_in (
float)level_next (
float)dV_mix_w_out (
float)dV_mix_w_out_unmet (
float)
- alp: float
- dV_tank_w_out: float
- dV_tank_w_in: float
- level_next: float
- __init__(alp, dV_tank_w_out, dV_tank_w_in, level_next, dV_mix_w_out, dV_mix_w_out_unmet)
- Parameters:
alp (
float)dV_tank_w_out (
float)dV_tank_w_in (
float)level_next (
float)dV_mix_w_out (
float)dV_mix_w_out_unmet (
float)
- dV_mix_w_out: float
- dV_mix_w_out_unmet: float
- as_flow_state()[source]
The flows as the
flow_statedict the source boilers report from.dV_mix_w_outis the delivered mixed water anddV_mix_sup_w_inthe mains water the valve added to it.- Return type:
dict[str,float]
- tmhp.dynamic_context.limit_tank_flows(tank_level, dV_tank_w_in, dV_tank_w_out, dt, V_tank_full, level_min=0.001, level_max=1.0)[source]
Make-up and draw a tank can pass in one step, and its end level.
The draw takes no more than the water above
level_minplus the make-up over the step; the make-up adds no more than the room belowlevel_maxplus the draw. The end level istank_level + (dV_in - dV_out)·dt / V_tank_fulland stays within[level_min, level_max](a tank already belowlevel_minis not drawn from until the make-up lifts it).- Returns:
(dV_tank_w_in, dV_tank_w_out, level_next)[m³/s, m³/s, -].- Return type:
tuple[float,float,float]- Parameters:
tank_level (
float)dV_tank_w_in (
float)dV_tank_w_out (
float)dt (
float)V_tank_full (
float)level_min (
float)level_max (
float)
- tmhp.dynamic_context.merge_running_rows(full, f_full, reduced, f_reduced, rate_keys)[source]
Mean running cycle of a step that ran
f_fullof it on one cycle andf_reducedon another.Every finite rate in
rate_keys(heat, power, flow) is the run-time-weighted mean of the two cycles, so the row times the step’s run time is the step’s energy.cop_ref [-]andcop_sys [-]are the ratios of the merged heat and power. Every other quantity – temperatures, pressures, speed, efficiencies – is a state of one machine at one moment and has no mean: it is that of the cycle that ran longer (the full-duty one at a tie). The capacity keys are those ofreduced(the step ran below its request for part of the time) withQ_max [W]the mean running duty, soQ_max [W] * runtime_fraction [-]is the row’s step-average heat as on every reduced step.- Parameters:
full (
Mapping[str,Any])f_full (
float)reduced (
Mapping[str,Any])f_reduced (
float)rate_keys (
tuple[str,...])
- Return type:
dict
- tmhp.dynamic_context.tank_free_heat_rate(residual, T_K, *, T_start_K, C_curr, C_next, C_tank, dt, Q_heat_source)[source]
Tank heat rate at
T_Kfrom everything but the heat source [W].Inverts the implicit energy residual every boiler uses,
r(T) = [C_next·T - C_curr·T_start - dt·(Q_heat_source + P(T))] / C_tank, forP(T): draw-off enthalpy, envelope loss and subsystem heat (a subsystem residual that re-evaluates its physics atTis included). WithC_next = C_currit returns the temperature-form rateP(T) - (C_next_true - C_curr)·T/dtthat drivesC_curr·dT/dt(seeresolve_step_operation()).- Parameters:
T_K (
float)T_start_K (
float)C_curr (
float)C_next (
float)C_tank (
float)dt (
float)Q_heat_source (
float)
- Return type:
float
- tmhp.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_wall, V_tank_full, subsystems, sub_states, T_sur_K=None)[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.The energy residual is the conservative implicit balance
C_tank·(L1·T1 - L0·T0) = dt·(Q + ρc·(V̇_in·T_in - V̇_out·T1) - UA·(T1 - T_sur))withL1 = L0 + (V̇_in - V̇_out)·dt/V. An always-full tank keepsL1 = L0. A level-varying tank (ctrl.dV_tank_w_in_ctrlset) takesL1and both flows fromtank_step_flows()atT1, so the water the balance adds or removes is the water that flows; the draw stops atTANK_LEVEL_MINand the make-up at full. The envelope lossUA·(T1 - T_sur)does not depend on the level.Subsystem energy contributions and tank-inlet temperature overrides are read from
sub_states.- Parameters:
x (
list[float]) –[T_next_K, level_next]. For a level-varying tanklevel_nextenters only the mass residual (the energy residual uses the level its flows give).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_wall (
float) – Tank overall heat-loss coefficient [W/K] (shell/insulation envelope).V_tank_full (
float) – Tank full volume [m³].subsystems (
dict[str,Subsystem]) – Registered subsystem instances.sub_states (
dict[str,dict]) – Per-subsystem state dicts fromstep().T_sur_K (
float|None) – Surrounding temperature [K]. If None, defaults to ctx.T0_K.
- Returns:
[r_energy, r_mass].- Return type:
list[float]
- tmhp.dynamic_context.tank_step_flows(T_next_K, ctx, ctrl, dt, T_sup_w_K, T_mix_w_out_K, V_tank_full)[source]
Tank flows and end level of a step whose tank ends at
T_next_K.The mixing valve takes the hot share
alpof the demandctx.dV_mix_w_outfrom the tank at the end-of-step temperature (implicit, astank_mass_energy_residual()). An always-full tank (ctrl.dV_tank_w_in_ctrl is None) takes in what it gives and keeps its level. A level-varying tank takes inctrl.dV_tank_w_in_ctrland both flows passlimit_tank_flows(); a draw it cuts delivers proportionally less mixed water, at the same set point.- Parameters:
T_next_K (
float)ctx (
StepContext)ctrl (
ControlState)dt (
float)T_sup_w_K (
float)T_mix_w_out_K (
float)V_tank_full (
float)
- Return type:
TankStepFlows
- tmhp.dynamic_context.unphysical_cycle_detail(result, hp_capacity)[source]
Explain why a cycle state the solver accepted is not an operating point.
The boiler solvers accept a cycle once its compressor speed meets the requested duty (or clamps onto a speed bound). That acceptance says nothing about whether the state itself exists. This check rejects the states that cannot be a running machine;
Nonemeans the state passes."duty_or_power_undefined"Delivered heat or compressor power is non-finite or not positive. A running compressor does work on the refrigerant and the condenser rejects at least that work, so both must be positive numbers.
"discharge_state_undefined"The compressor discharge temperature or enthalpy is non-finite. The delivered heat is
m_dot * (h_discharge - h_liquid); without a discharge state that heat has no thermodynamic basis. A low overall efficiency at a high pressure ratio produces it:h_isen - h_suctionis divided byeta_ov(and multiplied by1 - f_loss) and the discharge enthalpy leaves the refrigerant’s equation-of-state range."min_speed_duty_above_capacity"The compressor clamped onto its speed floor (the request was below the duty available there) and yet delivers more than the nameplate
hp_capacity. Mass flow is proportional to speed, so atrps_min(below the speed at whichhp_capacityis rated) the compressor pumps the least refrigerant it can; delivering more heat than at the rated speed then needs a specific condensing duty several times the rated one. That is the signature of the same efficiency collapse, not of a real machine. The condenser cannot carry it either: its approach temperature was sized for the requested duty, so the surplus has no driving temperature difference across the tank heat exchanger.hp_capacityis the bound because it is the only capacity the model knows the machine to have; no tolerance is added beyond floating-point noise.
- Parameters:
result (
Mapping[str,Any])hp_capacity (
float)
- Return type:
str|None
- tmhp.dynamic_context.warn_if_tank_boiling(T_tank_K)[source]
Emit
TANK_BOILING_WARNINGwhen the solved tank is above 100 °C.- Parameters:
T_tank_K (
float)- Return type:
None
Energy & exergy helpers¶
Local helper functions for energy, entropy, and exergy analysis, plus a backward-compatibility facade over sibling modules.
Locally defined helpers:
Curve fitting:
linear_function,quadratic_function,cubic_function,quartic_functionFlow and mixing:
calc_mixing_valve_temp,calc_mixing_valve_flows,calc_Orifice_flow_coefficient,calc_boussinessq_mixing_flowAir-side heat exchanger:
calc_HX_perf_for_target_heatLumped tank:
update_tank_temperatureSolar thermal collector performance:
calc_stc_performanceBalance printing:
print_balance
For backward compatibility this module also re-exports selected APIs that now
live in dedicated modules: cop (COP correlations), g_function
(g-function and air-property helpers), hx_fan (fan UA / power),
heat_transfer (TDMA solver, LMTD, tank UA), thermodynamics (energy /
exergy flow), and uv_treatment. Import those symbols from their owning
module in new code.
- tmhp.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_rated=None, dV_fan_rated=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, UA_design=None, dV_fan_design=None, *, dV_fan_ref=None, dV_fan_min=None, dV_fan_max=None, custom_fan_curve=False, rho_air=None, w_a_in=None)[source]¶
Numerically solve for the air-side flow rate of an ε-NTU heat exchanger.
Given a target heat transfer duty, find the airflow that delivers it, accounting for the velocity dependence of UA via the Wang et al. (2000) fin-and-tube correlation (UA ∝ velocity^0.71).
The air heat capacity rate is
c_a * rho_air * dV_fan.rho_air[kg/m³] is the density of the air the fan moves;"inlet"takes dry air at the inlet temperatureT_a_in_Cand one standard atmosphere (tmhp.air_properties.air_density()), andNone(default) keeps standard air,constants.rho_a(15 °C). UA follows the volume flow in either case.Wet cooling coil (
w_a_ingiven). With the humidity ratio of the entering airw_a_in[kg water / kg dry air] the coil also condenses water where its surface is below the air’s dew point (apparatus dew point / bypass factor model, the family EnergyPlus uses for DX cooling coils). The surface is taken at the refrigerant saturation temperatureT_e– as the dry coil already does through the overallUA– and the air leaves on the straight line from its inlet state to saturated air atT_e, a fractioneps = 1 - exp(-UA / C)of the way (Lewis number 1: heat and water vapour are transferred with the same effectiveness):\[Q_s = C\,\varepsilon\,(T_{in} - T_e), \qquad Q_l = C\,\varepsilon\,\frac{h_{fg}}{c_a}\,\max\bigl(0,\; w_{in} - w_{sat}(T_e)\bigr)\]The target duty is the total
Q_s + Q_l, what the refrigerant takes up. The coil is therefore the dry coil with its driving temperature difference enlarged bywet_coil_latent_difference(); where the surface is at or above the dew point that term is zero and every number is the dry coil’s. Assumptions: the sameUAwet and dry (no wet-surface enhancement, no fin-efficiency change),Cthe heat capacity rate of dry air,h_fgthe latent heat of water atT_e(water_latent_heat()), and the condensate leaves atT_e; the sensible cooling of the vapour that condenses is left out (about 1 % of the latent heat). A surface below 0 °C is not frosted: condensation continues withw_satover ice.w_a_inis ignored for a coil that heats the air (T_ref_sat_KaboveT_a_in_C).The leaving air is never wetter than saturated. Where the straight line passes above the saturation curve – entering air close to saturation, or a surface far below the dew point – the leaving state is moved onto the curve at the same enthalpy (
saturated_leaving_state()): the total heat and the airflow are unchanged, the leaving air is warmer and drier than on the line, and more of the heat is latent.- Parameters:
Q_ref_target (float) – Target heat transfer rate [W] (always positive).
T_a_in_C (float, optional) – Air-side inlet temperature [°C].
T_ref_sat_K (float, optional) – Refrigerant saturation temperature [K] on the constant-temperature side.
A_cross (float) – Heat-exchanger cross-sectional area [m²].
UA_rated (float) – Rated UA [W/K].
dV_fan_rated (float) – Rated fan volumetric flow rate [m³/s].
is_active (bool) – Active flag.
exponent (float) – UA scaling exponent (default: 0.71).
(optional) (# Legacy aliases)
T_ou_a_in_C (float, optional) – Backward-compat alias for
T_a_in_C.T_ref_evap_sat_K (float, optional) – Backward-compat alias for
T_ref_sat_K.T_ref_cond_sat_l_K (float, optional) – Unused; kept only to preserve the older function signature.
- Returns:
Dictionary with the following keys:
dV_fan— required air-side flow rate [m³/s]UA— overall heat-transfer coefficient at the solution point [W/K]T_a_mid_C— air temperature between the heat exchanger and the fan [°C]Q_air— heat-transfer rate at the operating point [W]epsilon— effectiveness at the operating point [–]C_air— air heat capacity rate at the operating point [W/K]converged— whether the solver converged
With
w_a_ingiven,Q_airis the total heat (sensible plus latent) and the dictionary also hasQ_sensibleandQ_latent[W],w_a_mid(humidity ratio of the air leaving the coil [kg/kg]),m_dot_condensate[kg/s] anddT_latent[K] (wet_coil_latent_difference()).All numeric values are
np.nanwhenis_active=False.- Return type:
dict
- tmhp.enex_functions.calc_Orifice_flow_coefficient(D0, D1)[source]¶
Calculate the orifice flow coefficient based on diameters.
Flow configuration:
--------------- -> | D0 D1 -> -> | ---------------
- Parameters:
D0 (float) – Pipe diameter [m]
D1 (float) – Hole diameter [m]
- Returns:
C_d – Orifice flow coefficient (dimensionless)
- Return type:
float
Notes
This is a simplified calculation. A more complete implementation should be based on physical equations.
- tmhp.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.
- tmhp.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
- tmhp.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
- tmhp.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]¶
Compute the performance of a solar thermal collector (STC).
Adapted from the
SolarAssistedGasBoiler.system_updatelogic in the legacyenex_engine.py.- 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 to the STC (equal to the tank temperature) [K].
T0_K (float) – Reference / ambient temperature [K].
A_stc_pipe (float) – STC pipe area [m²].
alpha_stc (float) – Absorptance [-].
h_o_stc (float) – Outer convective heat-transfer coefficient [W/m²K].
h_r_stc (float) – Air-gap radiative heat-transfer coefficient [W/m²K].
k_ins_stc (float) – Insulation thermal conductivity [W/mK].
x_air_stc (float) – Air-gap thickness [m].
x_ins_stc (float) – Insulation thickness [m].
dV_stc (float) – STC volumetric flow rate [m³/s].
E_pump (float) – Pump electrical input [W].
is_active (bool, optional) – Active flag (default: True). When
False, returns a dict filled withnp.nan(exceptT_stc_w_out_KandT_stc_w_in_K, which are set to the inlet temperature).
- Returns:
I_sol_stc— total incident irradiance [W/m²]Q_sol_stc— absorbed solar heat [W]Q_stc_w_in— inlet enthalpy flow relative toT0_K[W]Q_stc_w_out— outlet enthalpy flow relative toT0_K[W]ksi_stc— dimensionless efficiency parameter [-]T_stc_w_out_K— outlet water temperature [K]T_stc_w_final_K— outlet temperature including pump heat gain [K]T_stc_w_in_K— inlet water temperature (echoed back) [K]T_stc_K— mean absorber-plate temperature [K]Q_l_stc— absorber-plate heat loss [W]
- Return type:
dict
Notes
All variable names are suffixed with
_stcto mark them as STC-specific.Heat losses are reported as
Q_l_stc.Entropy and exergy quantities are intentionally not computed here; do them as a post-processing step on the result CSV if needed.
- tmhp.enex_functions.cubic_function(x, a, b, c, d)[source]¶
Cubic function: y = a*x³ + b*x² + c*x + d
- tmhp.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)
- tmhp.enex_functions.quartic_function(x, a, b, c, d, e)[source]¶
Quartic function: y = a*x⁴ + b*x³ + c*x² + d*x + e
- tmhp.enex_functions.update_tank_temperature(T_tank_w_K, Q_gain, UA_tank_wall, 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_wall (float) – Overall tank heat-loss coefficient [W/K] (shell/insulation envelope).
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
- tmhp.enex_functions.G_FLS(t, ks, as_, rb, H)[source]¶
Calculate the g-function for finite line source (FLS) model.
This function calculates the g-function used in ground source heat pump analysis. Scalar results are cached by the input values in a bounded cache.
- Parameters:
t (
float|ndarray) – Positive time or times [s], in any order.ks (
float) – Ground thermal conductivity [W/mK]as (float) – Ground thermal diffusivity [m²/s]
rb (
float) – Borehole radius [m]H (
float) – Borehole height [m]as_ (
float)
- Returns:
g-function value [mK/W]. Scalar and zero-dimensional inputs return a float. Array inputs return a flat array, including arrays of length one.
- Return type:
float|ndarray
- tmhp.enex_functions.air_dynamic_viscosity(T_K)[source]¶
Calculate air dynamic viscosity using Sutherland’s formula.
- Parameters:
T_K (float) – Temperature [K]
- Returns:
float – Dynamic viscosity [Pa·s]
Reference (Sutherland’s formula for air)
mu = mu0 * (T/T0)^1.5 * (T0 + S) / (T + S)
where mu0 = 1.716e-5 Pa·s at T0 = 273.15 K, S = 110.4 K
- tmhp.enex_functions.air_prandtl_number(T_K)[source]¶
Calculate air Prandtl number.
- Parameters:
T_K (float) – Temperature [K]
- Returns:
float – Prandtl number [-]
Note (Pr ≈ 0.71 for air at typical temperatures (20-50°C))
Temperature dependence is weak, so using constant value.
- tmhp.enex_functions.calc_ASHP_cooling_COP(T_a_int_out, T_a_ext_in, Q_r_int, Q_r_max, COP_ref)[source]¶
Calculate the Coefficient of Performance (COP) for an Air Source Heat Pump (ASHP) in cooling mode.
Reference: https://publications.ibpsa.org/proceedings/bs/2023/papers/bs2023_1118.pdf
- Parameters:
T_a_int_out (float) – Indoor air temperature [K]
T_a_ext_in (float) – Outdoor air temperature [K]
Q_r_int (float) – Indoor heat load [W]
Q_r_max (float) – Maximum cooling capacity [W]
COP_ref (float) – Reference COP at standard conditions
- Returns:
COP value
- Return type:
float
Note
COP is calculated based on: - PLR: Part Load Ratio - EIR: Energy input to cooling output ratio
- tmhp.enex_functions.calc_ASHP_heating_COP(T0, Q_r_int, Q_r_max)[source]¶
Calculate the Coefficient of Performance (COP) for an Air Source Heat Pump (ASHP) in heating mode.
Reference: https://www.mdpi.com/2071-1050/15/3/1880
- Parameters:
T0 (float) – Environmental temperature [K]
Q_r_int (float) – Indoor heat load [W]
Q_r_max (float) – Maximum heating capacity [W]
- Returns:
COP value
- Return type:
float
Note
COP is calculated based on PLR (Part Load Ratio).
- tmhp.enex_functions.calc_energy_flow(G, T, T0)[source]¶
Calculate energy flow rate.
- Parameters:
G (float or pd.Series) – Heat capacity flow rate (mass_flow * Cp) [W/K].
T (float or pd.Series) – Current temperature [K].
T0 (float or pd.Series) – Reference/dead state temperature [K].
- Returns:
Energy flow rate [W].
- Return type:
float or pd.Series
- tmhp.enex_functions.calc_exergy_flow(G, T, T0)[source]¶
Calculate exergy flow rate.
- Parameters:
G (float or pd.Series) – Heat capacity flow rate (mass_flow * Cp) [W/K].
T (float or pd.Series) – Current temperature [K].
T0 (float or pd.Series) – Reference/dead state temperature [K].
- Returns:
Exergy flow rate [W].
- Return type:
float or pd.Series
- tmhp.enex_functions.calc_fan_power_from_dV_fan(dV_fan, fan_params, vsd_coeffs, is_active=True)[source]¶
Electrical power [W] at the bounded fan operating point.
ASHRAE Appendix G Method 2 uses its unchanged empirical coefficients only over 0.15–1.0 of reference airflow. See calc_fan_operating_point for actual flow and limit flags. The default single-zone surrogate has a 10% electrical floor; custom settings may explicitly supply an independent
power_min_ratio.- Parameters:
dV_fan (
float)fan_params (
dict)vsd_coeffs (
dict|None)is_active (
bool)
- Return type:
float
- tmhp.enex_functions.calc_GSHP_COP(T_a_iu_in_K, T_f_out_K, dV_a_ratio, mode)[source]¶
Calculate COP for a Ground Source Heat Pump.
Uses the EnergyPlus
Coil:*:WaterToAir:EquationFitmodel (Equation-Fit Method),COP = COP_ref · CAP_ratio / PWR_ratio.References
EnergyPlus Engineering Reference, Ch. 16.5.10.2 (Eq. 16.412–16.418, Tang 2005). Dataset: TCH072_GLHP (ClimateMaster 6-ton, Ground Loop HP), source:
EnergyPlus/datasets/WaterToAirHeatPumps.idf.Rated conditions (from IDF comment, 15% methanol antifreeze):
Cooling: 70.29 kBtu/h @ 77 °F (25 °C) entering water, EER = 14.35
Heating: 56.14 kBtu/h @ 32 °F (0 °C) entering water, COP = 3.42
- Parameters:
T_a_iu_in_K (float) – Indoor air inlet dry-bulb temperature [K] (= T_a_room). For cooling, internally converted to wet-bulb (T_wb) via CoolProp assuming RH = 50%.
T_f_out_K (float) – Source-side inlet water temperature [K] — water returning from the borehole to the heat pump (
T_w,inin EnergyPlus notation).dV_a_ratio (float) – Air flow ratio while the compressor runs,
V_a / V_a,rated[-] (fitted range 0.75–1.25). It is not a part-load ratio: the curve describes full-load operation and a part load is met by cycling.mode (str) – “cooling” or “heating”
- Returns:
Full-load COP (dimensionless), always positive inside the fitted domain; 0.0 for any other
mode.- Return type:
float
- Raises:
EquationFitRangeError – (a
ValueError) when the entering-air temperature, the entering water temperature or the air-flow ratio is outside the fitted domainGSHP_EQFIT_DOMAIN. The curves are not extrapolated.
- tmhp.enex_functions.calc_refrigerant_exergy(df, ref, T0_K, P0=101325)[source]¶
Calculate refrigerant state-point exergy using pre-computed properties.
Uses the entropy (
s_ref_*) and enthalpy (h_ref_*) columns already present indf(produced bycalc_ref_state) to compute specific exergy and exergy flow rate for each refrigerant state point.Dead-state properties (h0, s0) are evaluated at (T0, P0) for the given refrigerant using CoolProp (vectorized via unique T0 values).
- Parameters:
df (
DataFrame) – DataFrame containing pre-computed enthalpyh_ref_* [J/kg], entropys_ref_* [J/(kg·K)], and mass-flowm_dot_ref [kg/s]columns.ref (
str) – CoolProp refrigerant identifier (e.g.'R410A').T0_K (
Series) – Dead-state (environment) temperature per row [K].P0 (
float) – Dead-state pressure [Pa] (default101325).
- Returns:
dfwith columns added per state point:x_ref_{name} [J/kg],X_ref_{name} [W].- Return type:
DataFrame
Notes
Exergy equation: x = (h − h0) − T0·(s − s0) [J/kg]
Exergy flow: X = ṁ · x [W]
Rows with NaN enthalpy/entropy propagate NaN naturally.
- tmhp.enex_functions.calc_UA_from_dV_fan(dV_fan, dV_fan_rated=None, A_cross=None, UA=None, exponent=0.71, *, dV_fan_ref=None)[source]¶
Calculate velocity-dependent UA via lumped scaling (Wang et al., 2000).
- Parameters:
dV_fan (
float) – Current fan flow rate [m³/s].dV_fan_rated (
float|None) – Rated fan flow rate [m³/s].A_cross (
float|None) – Heat exchanger cross-sectional area [m²].UA (
float|None) – Rated UA value [W/K].exponent (
float) – Exponent for velocity scaling. Default is 0.71 for a 1-row configuration.
- Returns:
Scaled UA value [W/K].
- Return type:
float
Notes
Instead of the Dittus-Boelter tube-side exponent (0.8), this uses a simplified lumped exponent (default 0.71). This derivation assumes a 1-row plain fin-and-tube configuration (N=1) where the Colburn j-factor is proportional to Re^-0.29, leading to h ∝ V^0.71. Multi-row coils may use exponents between 0.5 and 0.8 depending on configuration. Reference: Wang et al. (2000), DOI: 10.1016/S0017-9310(99)00333-6
- Parameters:
dV_fan_ref (
float|None)
- tmhp.enex_functions.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
- tmhp.enex_functions.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_switchingtimes perperiod_sec, each activation lastingexposure_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 usecalc_uv_lamp_energy()/dt.- Return type:
float
- tmhp.enex_functions.chi(s, rb, H, z0=0)[source]¶
Helper function for G-function calculation.
- Parameters:
s (float) – Integration variable
rb (float) – Borehole radius [m]
H (float) – Borehole height [m]
z0 (float, optional) – Reference depth [m] (default: 0)
- Returns:
chi function value
- Return type:
float
- tmhp.enex_functions.convert_electricity_to_exergy(df)[source]¶
Copy all electricity columns (
E_*) to exergy columns (X_*).Electrical energy is 100 %% pure exergy, so
X = Efor all electricity-consumption columns.The function searches for columns matching the pattern
E_xxx [W]and creates correspondingX_xxx [W]columns.- Parameters:
df (
DataFrame) – DataFrame withE_xxx [W]columns.- Returns:
dfwithX_xxx [W]columns added.- Return type:
DataFrame
- tmhp.enex_functions.f(x)[source]¶
Helper function for G-function calculation.
- Parameters:
x (float) – Input value
- Returns:
f(x) = x*erf(x) - (1-exp(-x²))/√π
- Return type:
float
- tmhp.enex_functions.generate_entropy_exergy_term(fluid, T, P, Q, T0, P0, phase='gas')[source]¶
Calculate entropy, enthalpy, and exergy.
- Parameters:
fluid (
str) – Fluid name.T (
float) – Temperature [K].P (
float) – Pressure [Pa].Q (
float) – Quality (0 to 1).T0 (
float) – Dead state temperature [K].P0 (
float) – Dead state pressure [Pa].phase (
Literal['gas','liquid','twophase']) – Fluid phase. Default is ‘gas’.
- Returns:
Entropy [J/kg-K], Enthalpy [J/kg], Exergy [J/kg].
- Return type:
tuple[float,float,float]
- tmhp.enex_functions.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
On/off cycling below the minimum capacity¶
On/off cycling below the minimum continuous capacity.
A variable-speed compressor modulates down to its minimum speed and no further. A request below what the unit delivers there is met by switching the compressor on and off, and every start costs something: the refrigerant has to be redistributed and the coils brought back to their working temperatures before the capacity is there, while the compressor already draws power. EN 14825 states that loss as a degradation of the continuous-operation COP at the minimum capacity, as a function of the capacity ratio
Two forms are in the standard, and both are here:
units delivering to air (air-to-air, water-to-air; cooling and heating) – the degradation coefficient
Cd, default 0.25:COP_cyc = COP_min * (1 - Cd * (1 - CR))units delivering to water (air-to-water, water/brine-to-water) – the degradation coefficient
Cc, default 0.9:COP_cyc = COP_min * CR / (Cc * CR + (1 - Cc))
The ratio COP_cyc / COP_min is the part-load factor PLF. The unit
delivers CR of the minimum capacity while drawing CR / PLF of the
power it draws there (the power fraction).
What the two forms describe¶
Air. The loss is in the start: the compressor runs longer than the heat it delivers accounts for. The runtime fraction – the share of the time the compressor runs – is
CR / PLF, the same number as the power fraction.Water. The standard takes the start-up loss of a hydronic unit as negligible; what it charges is the power the unit keeps drawing while the compressor is off (controls, crankcase heater, circulation).
Ccis one minus that off-state power over the power drawn while running, so the mean input isP_min * (CR + (1 - Cc) * (1 - CR)), which isP_min * CR / PLF. The compressor runs forCRof the time: the runtime fraction isCR, the power fraction is larger by the off-state draw. The default 0.9 is an off-state draw of a tenth of the running input; a unit with a measured standby powerP_offhasCc = 1 - P_off / P_min. A request of exactly zero is the unit switched off, not on standby: no power.
The coefficients are the defaults the standard prescribes when a unit has not been tested for them; a tested value replaces them without any other change.
How a result row is averaged¶
apply_cycling() turns the continuous minimum-speed operating point into
the mean over the cycling period:
heat and flow rates are multiplied by
CR– the delivered heat equals the request, and the refrigerant cycle and both secondary streams stay in balance with it. Power that only moves the delivered heat (an indoor fan) belongs here: it runs while heat is delivered, and its heat is part of the delivery;the electrical powers of the refrigeration machine (compressor, outdoor fan, source-side pump) are multiplied by the power fraction
CR / PLF;temperatures, pressures, speed and efficiencies keep the values of the running machine.
The electrical energy the machine draws beyond CR times its continuous
power is the cycling loss; it is reported, and it is the only place where the
mean row is not the running row scaled by one number. It is not part of any
heat flow of the row: the refrigerant duties of the mean row are the running
duties times CR, on the source side as on the delivery side.
report_cycling() is the same step for a solved row of any family (it
decides whether the row cycles). The boilers use it for analyze_steady
only (report_boiler_cycling(), steady_cycling()): in a dynamic run
their tank thermostat already switches the compressor, which then runs at its
nominal duty for part of a step, so nothing is left to average there.
- tmhp.cycling.CD_AIR_DEFAULT = 0.25¶
EN 14825 default degradation coefficient of a unit delivering to air [-].
- tmhp.cycling.CC_WATER_DEFAULT = 0.9¶
EN 14825 default degradation coefficient of a unit delivering to water [-].
- tmhp.cycling.CAPACITY_RATIO_KEY = 'capacity_ratio [-]'¶
Requested heat over the capacity at the minimum compressor speed [-].
- tmhp.cycling.PART_LOAD_FACTOR_KEY = 'part_load_factor [-]'¶
Mean COP over the continuous COP at the minimum compressor speed [-].
- tmhp.cycling.RUNTIME_FRACTION_KEY = 'runtime_fraction [-]'¶
Fraction of the time the compressor runs [-] (the boilers’ step key too).
- tmhp.cycling.MIN_CAPACITY_KEY = 'Q_min [W]'¶
Heat delivered in continuous operation at the minimum compressor speed [W].
- tmhp.cycling.CYCLING_LOSS_KEY = 'E_cycling_loss [W]'¶
Mean electrical power drawn beyond the continuous power times
CR[W].
- class tmhp.cycling.CyclingDegradation(coefficient=0.25, sink='air')[source]¶
Bases:
objectEN 14825 degradation of the COP while the compressor cycles on and off.
- Parameters:
coefficient (
float) –Cdforsink="air"(0 <= Cd < 1; 0 is loss-free cycling) orCcforsink="water"(0 < Cc <= 1; 1 is loss-free cycling).sink (
Literal['air','water']) – Which of the two EN 14825 forms applies: the medium the unit delivers its heat (or cooling) to.
- coefficient: float = 0.25¶
- sink: Literal['air', 'water'] = 'air'¶
- part_load_factor(capacity_ratio)[source]¶
COP_cyc / COP_minat a capacity ratio (1.0 at or aboveCR = 1).- Parameters:
capacity_ratio (
float)- Return type:
float
- power_fraction(capacity_ratio)[source]¶
Mean electrical input over the input at the minimum speed,
CR / PLF(0 atCR = 0).- Parameters:
capacity_ratio (
float)- Return type:
float
- runtime_fraction(capacity_ratio)[source]¶
Fraction of the time the compressor runs (0 at
CR = 0).CR / PLFforsink="air", where the loss is run time that delivers no heat;CRforsink="water", where the loss is the power drawn while the compressor is off (see the module docstring).- Parameters:
capacity_ratio (
float)- Return type:
float
- state(Q_request, Q_min)[source]¶
Cycling state for a request below the minimum continuous capacity.
Q_requestandQ_minare magnitudes [W]. A request at or aboveQ_minis continuous operation:CR = PLF = runtime fraction = 1.- Parameters:
Q_request (
float)Q_min (
float)
- Return type:
- __init__(coefficient=0.25, sink='air')¶
- Parameters:
coefficient (
float)sink (
Literal['air','water'])
- class tmhp.cycling.CyclingState(capacity_ratio, part_load_factor, runtime_fraction)[source]¶
Bases:
objectWhere a cycling unit sits between off and continuous minimum-speed operation.
- Parameters:
capacity_ratio (
float)part_load_factor (
float)runtime_fraction (
float)
- capacity_ratio: float¶
Requested heat over the capacity at the minimum compressor speed [-].
- part_load_factor: float¶
Mean COP over the continuous COP at the minimum compressor speed [-].
- runtime_fraction: float¶
Fraction of the time the compressor runs [-].
- property cycling: bool¶
- property power_fraction: float¶
Mean electrical input of the machine over its continuous input,
CR / PLF.
- __init__(capacity_ratio, part_load_factor, runtime_fraction)¶
- Parameters:
capacity_ratio (
float)part_load_factor (
float)runtime_fraction (
float)
- tmhp.cycling.resolve_cycling(value, sink)[source]¶
Constructor argument -> degradation model.
Noneswitches cycling off (the unit is reported running continuously at its minimum speed, delivering more than the request); a number is the coefficient of the form that belongs tosink; aCyclingDegradationis used as given.- Parameters:
value (
CyclingDegradation|float|None)sink (
Literal['air','water'])
- Return type:
CyclingDegradation|None
- tmhp.cycling.apply_cycling(result, state, *, delivered_key, rate_keys, power_keys, delivery_power_keys=(), total_power_key='E_tot [W]')[source]¶
Average a continuous minimum-speed row over the cycling period (in place).
rate_keys– heat and flow rates,delivered_keyamong them – anddelivery_power_keys– power that runs only while heat is delivered, such as an indoor fan – are multiplied by the capacity ratio;power_keys– the refrigeration machine – by the power fractionCR / PLF(the runtime fraction of a unit delivering to air).total_power_keyis reduced by what the powers in both groups lost. Adds the cycling keys:Q_min [W]is the magnitude of the continuous delivery the row came in with,E_cycling_loss [W]whatpower_keysdraw beyond the capacity ratio times their continuous value. COP columns are left to the caller, which knows how they are defined.- Parameters:
result (
dict)state (
CyclingState)delivered_key (
str)rate_keys (
Iterable[str])power_keys (
Iterable[str])delivery_power_keys (
Iterable[str])total_power_key (
str)
- Return type:
dict
- tmhp.cycling.continuous_keys(result, state=CyclingState(capacity_ratio=1.0, part_load_factor=1.0, runtime_fraction=1.0), Q_min=nan)[source]¶
Write the cycling keys of a row that was not averaged (in place).
- Parameters:
result (
dict)state (
CyclingState)Q_min (
float)
- Return type:
dict
- tmhp.cycling.report_cycling(result, cycling, request, *, delivered_key, rate_keys, power_keys, delivery_power_keys=(), total_power_key='E_tot [W]')[source]¶
Write the cycling keys of a solved row; average it if the unit cycles (in place).
The row cycles when it is a running operating point on the compressor’s speed floor, or at the smallest duty the envelope admits (
capacity_clamped == "min"), that delivers more than therequestand a degradation model is given: it is then averaged withapply_cycling(). Every other row – continuous operation, the off state, a failed solve, cycling switched off (cycling=None) – is left as it is and gets the keys ofcontinuous_keys()(Q_min [W]is the continuous delivery of a row on the speed floor, NaN elsewhere). Returns whether the row was averaged; COP columns and sums the caller derives from the averaged terms are left to the caller.- Parameters:
result (
dict)cycling (
CyclingDegradation|None)request (
float)delivered_key (
str)rate_keys (
Iterable[str])power_keys (
Iterable[str])delivery_power_keys (
Iterable[str])total_power_key (
str)
- Return type:
bool
- tmhp.cycling.report_boiler_cycling(result, cycling, request, *, rate_keys, power_keys, source_heat_key=None, hp_capacity=nan)[source]¶
report_cycling()for a boiler’s steady row (heat to the tank,Q_ref_tank [W]).An averaged row also gets back what a boiler row derives from the averaged terms: both COPs (the heat to the tank over the compressor input and over the total input),
PLR_delivered [-](withhp_capacity), the source loop’s net heatQ_bhe [W](source_heat_keyless the pump power) andE_cmp_plus_pmp [W], each where the row has it.- Parameters:
result (
dict)cycling (
CyclingDegradation|None)request (
float)rate_keys (
Iterable[str])power_keys (
Iterable[str])source_heat_key (
str|None)hp_capacity (
float)
- Return type:
bool
- tmhp.cycling.steady_cycling(duty_arg)[source]¶
Decorate a boiler’s
analyze_steadywith the part-load report.The decorated method is solved as before; its result row is then handed to the model’s
_report_part_load(result, request)with the caller’sduty_arg. It sits outside the envelope’s duty reduction (tmhp.compressor_envelope.steady_envelope()), whose trial solves must see the continuous rows.- Parameters:
duty_arg (
str)- Return type:
Callable[[TypeVar(_F, bound=Callable[...,Any])],TypeVar(_F, bound=Callable[...,Any])]
Frost and defrost of an outdoor coil¶
Frost on the outdoor coil of an air-source heat pump, and its defrost.
In heating the outdoor coil runs below the outdoor air. When its surface is below 0 degC and colder than the air’s dew point, water vapour deposits on it as frost: the air passages narrow, the evaporating pressure falls, and both capacity and power drop until the unit stops heating to melt the frost. A catalogue or a certified rating at 2 degC or -7 degC is the mean over those frosting and defrosting periods, not the frost-free steady state a cycle model computes.
The correction here is the one EnergyPlus applies to its DX heating coils
(Coil:Heating:DX:SingleSpeed; Engineering Reference, “Frost Adjustment
Factors” and “Defrost Operation”), which it takes from DOE-2.1E (Miller and
Jaster 1985). For on-demand defrost:
with no correction when the outdoor dry bulb is above the maximum temperature
for defrost operation (5 degC). t_frac is the fraction of the compressor’s
runtime spent defrosting. Reverse-cycle defrost also cools the room while it
runs, an extra heating load of
Five things differ from EnergyPlus. The first three change the correction – the onset of frosting with the outdoor temperature and with the outdoor humidity, here, and the load on the coil, in the next section:
Onset. In EnergyPlus the correction is a switch at the maximum outdoor temperature for defrost operation: at 5.0 degC and the default humidity the capacity multiplier is 0.771, at 5.1 degC it is 1, and the system COP of a unit steps by a quarter across a tenth of a kelvin. That limit is a setting of the defrost controller, not a temperature at which a coil frosts over: the coil-temperature correlation is at -4.5 degC there, and it puts a 0 degC coil at 10.5 degC outdoor. A coil does not frost all at once either. Near the onset its surface is close to freezing, so frost forms on part of it and for part of the time, and what a rating measures falls off gradually. Here the limit keeps its EnergyPlus meaning – no frost above
T_out_max(5 degC) – and the correction grows from nothing there to its full sizetransition_K(3 K) below, at 2 degC: the frosting rating condition of EN 14511 (A2: 2 degC dry bulb, 1 degC wet bulb), which is also where the default humidity comes from. In between it applies to the sharewof the runtime that rises linearly from zero to one:\[ \begin{align}\begin{aligned}t_{frac} &\leftarrow w\,t_{frac}\\\text{capacity multiplier} &= 1 - w\,\left(1 - 0.875\,(1 - t_{frac})\right)\\\text{power multiplier} &= 1 - w\,\left(1 - 0.954\,(1 - t_{frac})\right)\end{aligned}\end{align} \]– the mean of a unit that frosts for the share
wof its runtime and runs frost-free for the rest. Above 5 degC nothing differs from EnergyPlus, nor at and below 2 degC at the rated load in air whose frost point is the band of the next item above the coil or more (at 2 degC and 50 % relative humidity it is not: the COP multiplier is 0.983 here and 0.912 in EnergyPlus);transition_K=0restores the switch.Air too dry to frost the coil. The factors 0.875 and 0.954 are what a coil loses, on average, between two defrosts: the frost that builds up on it. EnergyPlus applies them wherever the outdoor temperature is below the limit – also to air that cannot deposit on the coil, where \(\Delta\omega\) sits on its floor of 1e-6: at -5 degC and 50 % relative humidity the defrost time is 0.01 % of the runtime and the COP is still multiplied by 0.917. The rating conditions the factors describe are humid (EN 14511: wet bulb 1 K below the dry bulb, 84 % at 2 degC and 75 % at -7 degC); a cold dry winter is not, and there the fixed losses add 8 to 9 % to the electricity of every sub-zero hour. A coil warmer than the frost point of the air collects no frost, so here the correction ends there: with the coil of the correlation at
T_coil, the frost point of the air atT_fpand \(\Delta\omega = \omega_{out} - \omega_{sat}(T_{coil})\) (positive exactly whenT_fpis aboveT_coil),\[ \begin{align}\begin{aligned}s &= \min\left(1,\; \frac{\max(0,\, T_{fp} - T_{coil})}{\min(\Delta T_{band},\, -T_{coil})}\right)\\t_{frac} &= \frac{\max(0, \Delta\omega)}{\max(0, \Delta\omega) + 0.01446}\\\text{capacity multiplier} &= (1 - 0.125\,s)(1 - t_{frac}), \qquad \text{power multiplier} = (1 - 0.046\,s)(1 - t_{frac})\end{aligned}\end{align} \]– no correction when the frost point of the air is at or below the coil temperature (\(\Delta\omega \le 0\)), the fixed losses in full when it is
frost_point_band_K(3 K) or more above it, and linearly in the frost point in between: a coil is not at one temperature, so near the onset part of it frosts. No measurement fixes the width of that band. 3 K is the width this module already uses for the onset with the outdoor temperature, and it leaves the rating conditions that give a wet bulb at the full correction (EN 14511 A2 and A-7, AHRI 210/240 H2, and the default 84 % down to -20 degC), so wherever the air is as humid as a test room the result is EnergyPlus unchanged. The band ends at 0 degC whatever its width (the denominator above:T_coilis below 0 degC): air with a dew point at or above freezing leaves all the frost a coil can take. Only the frost point of the air itself enters, so the share is defined wherever the air state is, at any pressure. A coil at or above 0 degC is not corrected, as in EnergyPlus; with the default limit of 5 degC the coil of the correlation is at -4.5 degC or colder and never reaches that step, which a higherT_out_maxor a givenT_coil_Cnear 0 degC does.frost_point_band_K=0switches the fixed losses at the frost point;Noneis EnergyPlus (the fixed losses whatever the deposition).
The other two are there so that no input is added:
Defrost power. EnergyPlus asks for a curve of defrost power per unit of rated capacity. Here the compressor is taken to draw, while it defrosts, the power it draws while it heats:
E_defrost = t_frac * E_cmp.Outdoor humidity. EnergyPlus reads it from the weather file. Here it is an optional input; without it the relative humidity is 84 %, the value of the EN 14511 rating condition A2 (dry bulb 2 degC, wet bulb 1 degC).
The coil temperature is the correlation above, not the evaporating temperature
a cycle model solves: the constants 0.01446, 0.875 and 0.954 were fitted with
that estimate, and the solved saturation temperature is a different quantity
(colder than the fin surface, and dependent on load). A caller that wants its
own coil temperature passes T_coil_C; the physical condition that the coil
be below 0 degC is checked either way.
The load on the coil¶
The EnergyPlus correction is a function of the outdoor temperature and
humidity alone: a unit at a third of its load is corrected like one flat out.
Its coil-temperature correlation 0.82 T_out - 8.589 is that of a unit
running flat out. The difference between the air and the coil surface is what
drives the heat into the coil, so at a load ratio r it is taken r
times as large: T_coil = T_out - r (0.18 T_out + 8.589). A lightly loaded
coil is warmer and takes less water out of the air. This is on by default
(DefrostModel.load_weighted); load_weighted=False is EnergyPlus at
every load. No constant is added.
The load ratio. The difference of the correlation itself shrinks with the
outdoor temperature (10.1 K at 8.3 degC, 5.9 K at -15 degC): it carries the
capacity decline of the unit it describes. r is therefore the frost-free
duty over what that unit delivers at the same outdoor temperature,
Q_rated (0.18 T_out + 8.589) / (0.18 * 7 + 8.589) with the nameplate
Q_rated declared at 7 degC (EN 14511 A7, ISO 5151 H1), and at most 1
(DefrostModel.reference_capacity(), DefrostModel.load_ratio()). In
other words the coil sits (duty / Q_rated) * 9.85 K below the air, never
more than the correlation says. Against the nameplate alone, a unit delivering
0.6 of it at -15 degC because that is its capacity there would be read as
part-loaded. The ratio depends on the correction it gives (the duty is the
request over the capacity multiplier), so the two are solved together
(DefrostModel.frost_state_at_duty()); a unit cycling on its speed floor
is loaded by what the running machine delivers, and so is one held at its
capacity ceiling: the frost of a request the unit cannot meet is that of the
ceiling duty, not of the request (the models keep the request’s state where
the ceiling’s would deliver more than was asked, which takes a frost-point
band of zero or none).
The frost drive. The humidity ratio the air can leave on the coil as frost
– what it holds, up to saturation at 0 degC, less saturation at the coil
temperature (a coil at or above 0 degC counts as 0 degC: it collects water,
not frost) – is a share phi(r) of the rated-load drive. The rated-load
\(\Delta\omega\) and the two fixed losses (1 - 0.875,
1 - 0.954) are multiplied by it:
At r = 1, phi = 1 and the result is the rated-load correction
unchanged at every outdoor state; it goes to no correction continuously as
the load falls and the coil rises to the air’s frost point.
Air too dry to frost the rated-load coil. The fixed losses carry the onset
share s of the rated-load coil as well as phi: 1 - 0.125 s phi
and 1 - 0.046 s phi. Where the air cannot deposit even on the rated-load
coil (at 60 % relative humidity below -18.4 degC, at 84 % below -39.1 degC)
there is no correction at any load, and the approach to it is continuous in
the outdoor state and in the load. A part-loaded coil at or above the frost
point of the air is not corrected either: the drive of the load term is cut
at zero, not at the EnergyPlus floor. Without the frost-point band
(frost_point_band_K=None) that floor shows through: there is no drive in
dry air for the load to scale, the fixed losses stay at every load, and at
half load and 60 % humidity the COP multiplier falls from 0.997 at -15 degC
to 0.917 at -18.4 degC – more correction in drier, colder air. A band of
zero, or one much narrower than the default, keeps one thing of that form:
where the air can barely frost the rated-load coil the fixed losses switch
between none and all over a small range of load, so the load a request
resolves to can step from a part-loaded coil to the rated-load one. The form
without the band steps too, though not at the same requests; only
frost_point_band_K=None reproduces it request for request. At one
atmosphere the default band has no such step.
What it assumes. The air flow over the coil does not follow the load. A unit that slows its outdoor fan with the compressor has a colder coil than this, so the part-load frost here is a lower bound.
How a result row is averaged¶
A request Q has to be met by the mean over frosting and defrost, so the
frost-free cycle is solved at the larger duty
(Q + Q_defrost) / capacity multiplier. apply_defrost() then turns
that frost-free row into the mean:
heat and flow rates are multiplied by
heat_factor(delivered heat over frost-free heat), so the delivered heat is the request and the refrigerant cycle stays in balance with it. Power that only moves the delivered heat (an indoor fan) is averaged with it;compressor power is multiplied by
power multiplier + t_frac(heating, then defrosting) and outdoor-fan power by the power multiplier;temperatures, pressures, speed and efficiencies keep the frost-free values.
The air-to-air model does this inside its analyze_steady; a boiler’s
analyze_steady is decorated with steady_defrost(), which solves the
frost-free row through the model’s own part-load and envelope handling and
hands it to the model for averaging. For a boiler the heat a reverse-cycle
defrost takes comes out of the water it heats.
- tmhp.defrost.T_OUT_MAX_DEFROST_C = 5.0¶
Maximum outdoor dry-bulb temperature for defrost operation [degC] (EnergyPlus default).
- tmhp.defrost.FROST_TRANSITION_K = 3.0¶
Width of the outdoor-temperature band below
T_out_maxover which the frost correction grows to its full size [K]: from the EnergyPlus limit (5 degC, no frost above) to the frosting rating condition of EN 14511 (A2, 2 degC dry bulb).
- tmhp.defrost.FROST_POINT_BAND_K = 3.0¶
Width of the band of frost points above the coil temperature over which the fixed frosted-coil losses grow to their full size [K]. No measurement fixes it: it is the width of the temperature onset above (
FROST_TRANSITION_K), and it keeps the rating conditions that give a wet bulb (EN 14511 A2, A-7; AHRI 210/240 H2) and the default humidity down to -20 degC at the full correction. See “Air too dry to frost the coil” in the module docstring.
- tmhp.defrost.LOAD_RATIO_ATOL = 1e-09¶
Two load ratios closer than this are the same load [-]. Not a physical constant:
DefrostModel.frost_state_at_duty()finds its ratio to 1e-12, and a duty read back from a solved row differs from the one asked for in its last digits.
- tmhp.defrost.RH_OUT_DEFAULT = 0.84¶
EN 14511 A2 (2 degC dry bulb, 1 degC wet bulb).
- Type:
Outdoor relative humidity used when none is given [-]
- tmhp.defrost.T_RATING_HEATING_C = 7.0¶
Outdoor dry bulb at which a nameplate heating capacity is declared [degC]: the standard rating condition of EN 14511 (A7) and ISO 5151 (H1, 7 degC dry bulb / 6 degC wet bulb). The load ratio of
load_weightedrefers the nameplate to it (DefrostModel.reference_capacity()).
- tmhp.defrost.DEFROST_FRACTION_KEY = 'defrost_fraction [-]'¶
Fraction of the compressor’s runtime spent defrosting [-].
- tmhp.defrost.FROST_CAPACITY_FACTOR_KEY = 'frost_capacity_factor [-]'¶
Heating capacity multiplier of the frosted coil, defrost time included [-].
- tmhp.defrost.FROST_POWER_FACTOR_KEY = 'frost_power_factor [-]'¶
Input power multiplier of the frosted coil, defrost time included [-].
- tmhp.defrost.DEFROST_POWER_KEY = 'E_defrost [W]'¶
Mean compressor power spent defrosting [W].
- tmhp.defrost.DEFROST_LOAD_KEY = 'Q_defrost [W]'¶
Mean heat a reverse-cycle defrost takes from the room [W].
- tmhp.defrost.RH_OUT_KEY = 'RH_out [-]'¶
Outdoor relative humidity the frost correction used [-].
- class tmhp.defrost.DefrostModel(T_out_max=5.0, RH_out=0.84, transition_K=3.0, load_weighted=True, frost_point_band_K=3.0)[source]¶
Bases:
objectEnergyPlus / DOE-2.1E frost adjustment with on-demand reverse-cycle defrost.
- Parameters:
T_out_max (
float) – Outdoor dry-bulb temperature above which the coil does not frost [degC].RH_out (
float) – Outdoor relative humidity (0-1) used when a call does not give one.transition_K (
float) – Width of the band belowT_out_maxover which the correction grows linearly from nothing to its full size [K]; in full at and belowT_out_max - transition_K.0is the EnergyPlus switch atT_out_max.load_weighted (
bool) – Estimate the coil temperature at the load ratio of the request instead of at the rated load, and scale the deposition and the fixed frosted losses with the frost drive that is left (frost_state_at_duty; “The load on the coil” in the module docstring). The ratio is the frost-free duty over the capacity the correlation’s unit has at that outdoor temperature (reference_capacity); at a ratio of one the result is the rated-load correction unchanged. On by default;Falseis the rated-load correction at every load.frost_point_band_K (
float|None) – Width of the band of frost points above the coil temperature over which the fixed frosted-coil losses (1 - 0.875,1 - 0.954) grow from nothing to their full size [K]. Air whose frost point is at or below the coil of the correlation is not corrected at all. The band ends at 0 degC, so any finite width is valid.0switches the fixed losses at the frost point;Noneis EnergyPlus: the fixed losses apply whatever the air can deposit.
- T_out_max: float = 5.0¶
- RH_out: float = 0.84¶
- transition_K: float = 3.0¶
- load_weighted: bool = True¶
- frost_point_band_K: float | None = 3.0¶
Share of the runtime the coil frosts at outdoor dry bulb
T_out_C[-].0 above
T_out_max, 1 at and belowT_out_max - transition_K, linear in between. Withtransition_K = 0it is 1 at and belowT_out_max(the EnergyPlus switch).- Parameters:
T_out_C (
float)- Return type:
float
- frost_state(T_out_C, RH_out=None, *, T_coil_C=None, P_Pa=101325.0, load_ratio=None)[source]¶
Frost correction at outdoor dry bulb
T_out_Cand relative humidityRH_out(0-1).T_coil_Creplaces the coil-temperature correlation0.82 T_out - 8.589. No frost aboveT_out_max; below it the correction grows to its full size acrosstransition_K(frost_share()). No frost on a coil at or above 0 degC either, nor (withfrost_point_band_K) on one at or above the frost point of the air; the fixed losses grow to their full size across that band (_frost_onset()).load_ratio(0-1, withload_weighted) scales the difference between the air and the coil of that correlation, and with it the frost drive of the rated-load state (_frost_drive_ratio());None, and a ratio of one or more, are the rated load.- Parameters:
T_out_C (
float)RH_out (
float|None)T_coil_C (
float|None)P_Pa (
float)load_ratio (
float|None)
- Return type:
- frost_state_at_duty(T_out_C, RH_out, Q_request, Q_rated, *, P_Pa=101325.0)[source]¶
Frost correction for a request of
Q_request[W] on a unit ratedQ_rated[W].Without
load_weightedthis isfrost_state(). With it the coil temperature is estimated at the load ratio of the frost-free duty the request needs (load_ratio(): that duty over what the correlation’s unit delivers at this outdoor temperature, at most 1). The duty depends on the correction, so the ratioris the root ofr = load_ratio(gross_duty(frost_state(r))), which lies between the request’s own ratio and 1: more load means a colder coil, more frost and a larger duty still. A request whose own load leaves the coil without frost is answered there; one the rated-load state cannot deliver is answered with the rated-load state.- Parameters:
T_out_C (
float)RH_out (
float|None)Q_request (
float)Q_rated (
float)P_Pa (
float)
- Return type:
- static reference_capacity(Q_rated, T_out_C)[source]¶
Capacity at which the coil-temperature correlation holds at
T_out_C[W].The correlation
T_coil = 0.82 T_out - 8.589puts the coil0.18 T_out + 8.589below the air: 10.1 K at 8.3 degC, 7.1 K at -8.3 degC, 5.9 K at -15 degC. That difference is what drives the heat into the coil, so its fall with the outdoor temperature is the fall of the capacity of the unit the correlation describes – one that runs flat out and delivers less as it gets colder. Relative to the nameplate, declared atT_RATING_HEATING_C, that capacity isQ_rated (0.18 T_out + 8.589) / (0.18 * 7 + 8.589). A load ratio taken against the nameplate itself would read a unit that delivers 0.6 of its nameplate at -15 degC because that is all it has as a part-loaded one, and count the decline twice.- Parameters:
Q_rated (
float)T_out_C (
float)
- Return type:
float
- classmethod load_ratio(duty, Q_rated, T_out_C)[source]¶
Load ratio of a frost-free
duty[W] atT_out_C: overreference_capacity(), at most 1.A unit that delivers the reference capacity or more has the coil of the correlation (ratio 1: the rated-load state, EnergyPlus unchanged).
- Parameters:
duty (
float)Q_rated (
float)T_out_C (
float)
- Return type:
float
- static defrost_load(frost, T_out_C, Q_rated)[source]¶
Mean heat a reverse-cycle defrost takes from the room [W] (>= 0).
- Parameters:
frost (
FrostState)T_out_C (
float)Q_rated (
float)
- Return type:
float
- static gross_duty(frost, Q_request, Q_defrost)[source]¶
Frost-free duty [W] whose mean over frosting and defrost is
Q_request.- Parameters:
frost (
FrostState)Q_request (
float)Q_defrost (
float)
- Return type:
float
- __init__(T_out_max=5.0, RH_out=0.84, transition_K=3.0, load_weighted=True, frost_point_band_K=3.0)¶
- Parameters:
T_out_max (
float)RH_out (
float)transition_K (
float)load_weighted (
bool)frost_point_band_K (
float|None)
- class tmhp.defrost.FrostState(active, defrost_fraction, capacity_multiplier, power_multiplier, T_coil_C=nan, humidity_ratio_difference=nan, RH_out=nan, frost_share=1.0, frost_drive_ratio=1.0, load_ratio=1.0, frost_onset=1.0)[source]¶
Bases:
objectFrost correction at one outdoor condition.
- Parameters:
active (
bool)defrost_fraction (
float)capacity_multiplier (
float)power_multiplier (
float)T_coil_C (
float)humidity_ratio_difference (
float)RH_out (
float)frost_share (
float)frost_drive_ratio (
float)load_ratio (
float)frost_onset (
float)
- active: bool¶
Whether the outdoor coil frosts here.
- defrost_fraction: float¶
Fraction of the compressor’s runtime spent defrosting [-].
- capacity_multiplier: float¶
Heating capacity multiplier,
0.875 (1 - t_frac)when frosting all the time [-].
- power_multiplier: float¶
Input power multiplier,
0.954 (1 - t_frac)when frosting all the time [-].
- T_coil_C: float = nan¶
Outdoor coil temperature the correction used [degC].
- humidity_ratio_difference: float = nan¶
Humidity ratio of the outdoor air above saturation at the coil [kg/kg].
- RH_out: float = nan¶
Outdoor relative humidity the correction used [-].
0 above
T_out_max, rising to 1 across the transition below it. The three figures above are the mean of frosting for this share and frost-free operation for the rest.- Type:
Share of the runtime the coil frosts [-]
- frost_drive_ratio: float = 1.0¶
Frost drive of the coil at this load over that of the rated-load coil [-] (
phi): the share of the rated-load deposition and of the fixed frosted losses (1 - 0.875, 1 - 0.954) that applies. 1 at the rated load.
- load_ratio: float = 1.0¶
the rated-load correlation).
- Type:
Load ratio the coil temperature was estimated at [-] (1
- frost_onset: float = 1.0¶
Share of the fixed frosted losses the frost point of the air leaves [-] (
s): 0 with a frost point at or below the rated-load coil, 1 with onefrost_point_band_Kor more above it (and without the band).
- __init__(active, defrost_fraction, capacity_multiplier, power_multiplier, T_coil_C=nan, humidity_ratio_difference=nan, RH_out=nan, frost_share=1.0, frost_drive_ratio=1.0, load_ratio=1.0, frost_onset=1.0)¶
- Parameters:
active (
bool)defrost_fraction (
float)capacity_multiplier (
float)power_multiplier (
float)T_coil_C (
float)humidity_ratio_difference (
float)RH_out (
float)frost_share (
float)frost_drive_ratio (
float)load_ratio (
float)frost_onset (
float)
- tmhp.defrost.NO_FROST = FrostState(active=False, defrost_fraction=0.0, capacity_multiplier=1.0, power_multiplier=1.0, T_coil_C=nan, humidity_ratio_difference=nan, RH_out=nan, frost_share=0.0, frost_drive_ratio=1.0, load_ratio=1.0, frost_onset=0.0)¶
nothing is corrected.
- Type:
No frost
- tmhp.defrost.resolve_defrost(value)[source]¶
Constructor argument -> frost model:
None/Falseoff,Truethe default model.- Parameters:
value (
DefrostModel|bool|None)- Return type:
DefrostModel|None
- tmhp.defrost.frost_free_keys(result, frost=FrostState(active=False, defrost_fraction=0.0, capacity_multiplier=1.0, power_multiplier=1.0, T_coil_C=nan, humidity_ratio_difference=nan, RH_out=nan, frost_share=0.0, frost_drive_ratio=1.0, load_ratio=1.0, frost_onset=0.0))[source]¶
Write the frost keys of a row that was not corrected (in place).
- Parameters:
result (
dict)frost (
FrostState)
- Return type:
dict
- tmhp.defrost.apply_defrost(result, frost, *, heat_factor, Q_defrost, rate_keys, compressor_power_key='E_cmp [W]', outdoor_power_keys=(), delivery_power_keys=(), total_power_key='E_tot [W]')[source]¶
Average a frost-free row over frosting and defrost (in place).
rate_keysanddelivery_power_keys(power that runs only while heat is delivered, such as an indoor fan) are multiplied byheat_factor; the compressor power bypower multiplier + t_frac;outdoor_power_keysby the power multiplier.total_power_keyis reduced by what those powers lost. Adds the frost keys. COP columns are left to the caller.- Parameters:
result (
dict)frost (
FrostState)heat_factor (
float)Q_defrost (
float)rate_keys (
Iterable[str])compressor_power_key (
str)outdoor_power_keys (
Iterable[str])delivery_power_keys (
Iterable[str])total_power_key (
str)
- Return type:
dict
- tmhp.defrost.steady_defrost(duty_arg, outdoor_arg='T0', humidity_arg='RH_out')[source]¶
Decorate a boiler’s
analyze_steadywith the frost correction.The decorated method is the frost-free solve (with its part-load report and its duty reduction). A request with a frosting outdoor coil is handed to the model’s
_steady_over_frost(frost, solve, request, T_out), wheresolve(duty)is that frost-free solve at another duty; every other row is solved as before and gets the frost keys of a row that was not corrected (_write_frost_free). The model supplies_frost_state(request, T_out, RH_out), which isNO_FROSTwhen its frost model is off, and_frost_state_of_running(result, frost, T_out), the frost state of the machine a frost-free row actually runs (the same state unless a load-weighted model finds the running machine more loaded than the request). It sits outermost: the trial solves of the duty reduction and the cycling mean must see frost-free rows.- Parameters:
duty_arg (
str)outdoor_arg (
str)humidity_arg (
str)
- Return type:
Callable[[TypeVar(_F, bound=Callable[...,Any])],TypeVar(_F, bound=Callable[...,Any])]
- tmhp.defrost.saturation_humidity_ratio(T_C, P_Pa=101325.0)[source]¶
Humidity ratio of saturated air at
T_C[kg water / kg dry air] (over ice below 0 degC).- Parameters:
T_C (
float)P_Pa (
float)
- Return type:
float
- tmhp.defrost.humidity_ratio(T_C, RH, P_Pa=101325.0)[source]¶
Humidity ratio of moist air at dry bulb
T_Cand relative humidityRH(0-1).- Parameters:
T_C (
float)RH (
float)P_Pa (
float)
- Return type:
float
- tmhp.defrost.frost_point(T_C, W, P_Pa=101325.0)[source]¶
Frost point (dew point above 0 degC) of moist air at dry bulb
T_Cwith humidity ratioW[degC].The temperature at which air of this humidity ratio is saturated – over ice below 0 degC, as
saturation_humidity_ratio().- Parameters:
T_C (
float)W (
float)P_Pa (
float)
- Return type:
float
Operating-limit warnings and summaries¶
Telling the caller that the machine could not do what it was asked.
A heat pump model that is asked for a point outside the machine’s operating
range answers correctly – the row is the off state with a failure_reason,
or a running row that delivers less than the request (capacity_clamped ==
"max") – but an answer in a result key is easy to miss. This module turns
those answers into one kind of warning, OperatingLimitWarning, worded
for the person who made the call:
Steady calls (
steady_notice(), around everyanalyze_steady): one warning for the final result of a call whose compressor was asked to run and either does not run or delivers less than asked. It names the machine and the call, what was requested and what is delivered, the limit in words with its value, and what removes it. The trial solves a call makes on the way (duty reduction, frost mean, smallest-duty search, coupled solvers) never warn.Dynamic runs (
dynamic_notice(), around everyanalyze_dynamic): nothing per step; one warning at the end of the run with the number of steps the compressor was called but did not run (by reason, with the first time), the steps it ran below the request, and what that did to the service (tank temperature and hot water, or unmet load). The same totals are indf.attrs["operating_limits"](summarize_operating_limits()).One table (
LIMITS): what eachfailure_reason/capacity_bindingmeans and what to do about it. The warnings and the documentation page failure_reason semantics both take their wording from it.
Repetition. A sweep of thousands of points must not print thousands of
lines, so a steady warning is issued once per model and limit: the first
point a model is stopped by discharge_temp_above_max is reported in full, later ones are
not (reset_notices() starts over). Nothing is lost – every row carries
failure_reason, capacity_clamped and capacity_binding – and a
caller who wants every point reported says so with the standard filter:
warnings.simplefilter("always", tmhp.OperatingLimitWarning) # every point
warnings.simplefilter("error", tmhp.OperatingLimitWarning) # stop at the first
warnings.simplefilter("ignore", tmhp.OperatingLimitWarning) # none
Python’s own once-per-location memory is not relied on: it is cleared every
time any code enters warnings.catch_warnings(), which the solvers (and
NumPy, SciPy, pandas) do all the time.
- tmhp.operating_limits.LIMITS: tuple[Limit, ...] = (Limit(reason='discharge_temp_above_max', binding='discharge_temperature', meaning='the compressor discharge temperature is above its protection limit T_dis_max, even with the suction superheat taken to 0 K and wet suction', remedy='Reduce the temperature lift (a lower tank or supply temperature, or a warmer source), or use a refrigerant that discharges cooler (R290, R134a) or the efficiency map of the actual compressor. T_dis_max=<°C> sets the limit of another compressor.'), Limit(reason='condensing_temp_above_max', binding='condensing_temperature', meaning='the condensing temperature is above T_cond_max, the top of the compressor envelope', remedy='Lower the temperature the heat is delivered at (the tank set points of a boiler), or use a refrigerant with a higher limit (R290, R134a). T_cond_max=<°C> sets the limit of another compressor.'), Limit(reason='pr_above_max', binding='pressure_ratio', meaning='the compressor pressure ratio is above PR_cycle_max, the single-stage limit', remedy='Reduce the temperature lift (a lower tank or supply temperature, or a warmer source). PR_cycle_max=<ratio> sets the limit of another compressor.'), Limit(reason='source_fluid_freezing', binding='source_fluid_freezing', meaning='the source-loop liquid would run below its operating limit, its freezing point plus 3 K', remedy="Fill the loop with an antifreeze mixture, or a stronger one (source_fluid='MEG-30%'), or take less heat from the source."), Limit(reason='hx_not_converged', binding=None, meaning='a heat exchanger cannot carry the duty inside its flow range and the approach temperatures the search admits', remedy='Reduce the request, or enlarge the heat exchanger that is short (its UA or its largest flow); failure_detail names the fan limit on the air-source boiler.'), Limit(reason=None, binding='outdoor_coil', meaning="the outdoor coil is short of the evaporator duty at the fan's largest airflow", remedy='Reduce the request, or give the outdoor coil and fan of the actual unit (UA_ou_rated, dV_fan_a_max).'), Limit(reason=None, binding='source_heat_exchanger', meaning='the source heat exchanger cannot absorb the evaporator duty at the approach temperatures the search admits', remedy='Reduce the request, raise the source temperature or flow, or enlarge the source heat exchanger.'), Limit(reason=None, binding='cycle', meaning='a coil is at its largest airflow and the widest approach temperature the search admits', remedy='Reduce the request, or size the machine for it (hp_capacity scales the coils and the compressor).'), Limit(reason='compressor_max_speed', binding='compressor', meaning='the compressor is at its maximum speed (rps_max)', remedy='Size the machine for the load (hp_capacity), or reduce the request.'), Limit(reason='cycle_invalid', binding=None, meaning='no refrigerant cycle closes at this condition (for example a condensing temperature at or above the critical point), or the solved cycle is not an operating point', remedy="Check the temperatures against the refrigerant's range and reduce the lift or the request; failure_detail names the check where there is one."), Limit(reason='t_cond_below_t_in', binding=None, meaning='the condensing temperature is at or below the water entering the condenser, so no heat can flow to the water', remedy='Check the tank and water-loop temperatures given for this point.'), Limit(reason='optimizer_failed', binding=None, meaning='the operating-point search did not settle: a numerical failure, not a limit of the machine', remedy='Treat the point as unsolved (a neighbouring condition usually solves), and report a condition that fails repeatedly.'), Limit(reason='pressure_ratio_limit', binding=None, meaning='the cycle is invalid and its pressure ratio is at PR_cycle_min or PR_cycle_max (ground-coupled solve)', remedy='Reduce the temperature lift (a lower tank or supply temperature, or a warmer source).'), Limit(reason='compressor_min_speed', binding=None, meaning='the request is below what the compressor delivers at its minimum speed, and on/off cycling is switched off (Cd_cycling=None)', remedy='Leave on/off cycling on (the default Cd_cycling), or lower rps_min.'), Limit(reason='compressor_capacity_limit', binding=None, meaning="the delivered duty differs from the request for another reason than the compressor's speed limits (ground-coupled solve)", remedy="Reduce the request, or check the compressor's speed range against it."), Limit(reason='compressor_speed_limit', binding=None, meaning='the compressor-speed solve did not converge (ground-coupled solve)', remedy='Treat the point as unsolved (a neighbouring condition usually solves), and report a condition that fails repeatedly.'), Limit(reason='load_hx_capacity_insufficient', binding=None, meaning='the load-side heat exchanger (indoor coil or tank condenser) cannot transfer the duty', remedy='Reduce the request, or enlarge the load-side heat exchanger.'), Limit(reason='ground_hx_capacity_insufficient', binding=None, meaning='the ground heat exchanger cannot supply the evaporator duty at any approach temperature the search admits', remedy='Reduce the request, or enlarge the borefield or its flow.'))¶
Every operating limit a result can name, with its meaning and remedy.
- class tmhp.operating_limits.Limit(reason, binding, meaning, remedy)[source]¶
Bases:
objectOne operating limit, in words.
reasonis thefailure_reasonof a point the limit stops andbindingthecapacity_bindingof a point it only reduces (either may beNone).meaningcompletes “Limit: …” andremedy“What to do: …” in a warning; the documentation prints the same two sentences.- Parameters:
reason (
str|None)binding (
str|None)meaning (
str)remedy (
str)
- reason: str | None¶
- binding: str | None¶
- meaning: str¶
- remedy: str¶
- __init__(reason, binding, meaning, remedy)¶
- Parameters:
reason (
str|None)binding (
str|None)meaning (
str)remedy (
str)
- exception tmhp.operating_limits.OperatingLimitWarning[source]¶
Bases:
UserWarningThe machine was asked for something it does not deliver.
Issued when a compressor that was called does not run (the result is the off state with a
failure_reason), runs below the requested duty (capacity_clamped == "max"), or – at construction – when a set point lies above what the compressor envelope reaches.tmhp.dhw.DHWUnmetWarning(hot water not delivered at the set point) is a subclass, so one filter on this class covers them all.
- tmhp.operating_limits.dynamic_notice(function)[source]¶
Decorate an
analyze_dynamic: no operating-limit warning per step, one summary at the end.The run is made inside
silenced(); the returned frame then getsattrs["operating_limits"]and, if a step was stopped or limited, oneOperatingLimitWarning(warn_if_operating_limited()).- Parameters:
function (
TypeVar(_F, bound=Callable[...,Any]))- Return type:
TypeVar(_F, bound=Callable[...,Any])
- tmhp.operating_limits.limit_for(reason=None, binding=None)[source]¶
The
Limitbehind afailure_reasonor acapacity_binding.A value the table does not know (a reason of a user’s own solver, say) gets a generic entry that names it and points at the documentation.
- Parameters:
reason (
str|None)binding (
str|None)
- Return type:
- tmhp.operating_limits.note_refusal(reason, duty=nan, value=None, detail=None)[source]¶
Leave what a solve knows about the point it refuses for the warning of the call it belongs to.
Called by a model where it turns a request into the off state:
reasonis thefailure_reason,dutythe duty that was solved [W], andvaluethe quantity that broke the limit at that duty (a discharge temperature, a pressure ratio). It never warns: the call that owns the result (steady_notice()) decides whether the refusal is what the caller gets, and words it.- Parameters:
reason (
str)duty (
float)value (
float|None)detail (
str|None)
- Return type:
None
- tmhp.operating_limits.reset_notices(model)[source]¶
Forget which limits
modelhas already been reported for: the next occurrence warns again.- Parameters:
model (
Any)- Return type:
None
- tmhp.operating_limits.silenced()[source]¶
No operating-limit warning from the
analyze_steadycalls made inside the block.For code that calls a model’s
analyze_steadymany times as a step of its own calculation and reports the outcome itself (a dynamic run, a search). The rows are unchanged.- Return type:
Iterator[None]
- tmhp.operating_limits.steady_notice(delivered_key='Q_ref_tank [W]')[source]¶
Decorate an
analyze_steadyso that its final result is what the caller is warned about.Outermost decorator. The decorated method runs inside a scope in which nothing warns about operating limits: its own trial solves, and any
analyze_steadyit calls on the way. When it returns, a row whose compressor was asked to run and does not (failure_reasonother than"none"), or runs short of the request (capacity_clamped == "max"), is reported once (OperatingLimitWarning,steady_message()). A call made from inside another such scope (a dynamic run, anotheranalyze_steady) only returns its row.verbose=False, where the method has that argument, switches the warning off for the call.- Parameters:
delivered_key (
str)- Return type:
Callable[[TypeVar(_F, bound=Callable[...,Any])],TypeVar(_F, bound=Callable[...,Any])]
- tmhp.operating_limits.summarize_operating_limits(df, dt_s, *, T_tank_w_lower_bound=None)[source]¶
What the operating limits did to a dynamic run, from its result frame.
Works on the frame of any family’s
analyze_dynamicand on rows collected fromstep(). A step counts asoff when the compressor was called but did not run:
failure_reasonis not"none"andhp_is_onis false;limited when it ran below the request:
capacity_clamped == "max"and the running duty is short ofQ_request [W]by more than 0.1 %.
- Parameters:
df (
Any) – Dynamic result (failure_reason,hp_is_on,capacity_clamped,capacity_binding,Q_request [W],Q_max [W]and, by family,Q_unmet [W]or the tank and hot-water columns).dt_s (
float) – Time step of the result [s].T_tank_w_lower_bound (
float|None) – Lower thermostat set point of a boiler [°C], for the time the tank spent below it.None: not evaluated (NaN).
- Returns:
Common keys:
kind:"boiler"(a tank is heated) or"space"(a load is met);steps [-]: steps of the run;off_steps [-],off_time [h]: called but did not run;off_reasons:{failure_reason: {"steps [-]", "first_time [s]"}}, most frequent first;limited_steps [-],limited_time [h]: ran below the request;limited_bindings:{capacity_binding: {"steps [-]", "first_time [s]"}}.
"space"addsQ_request [kWh](load asked for, heating and cooling as magnitudes),Q_unmet [kWh]andunmet_fraction [-]."boiler"addsQ_below_request [kWh](heat by which the running duty of the limited steps fell short of the requested duty, over their run time),T_tank_w_min [°C],time_below_lower_setpoint [h]andQ_dhw_unmet [kWh](NaN without the hot-water columns).- Return type:
dict[str,Any]
- tmhp.operating_limits.warn_if_operating_limited(df, dt_s, who, model=None)[source]¶
Summarise a dynamic result, attach the summary, and warn once if a step was stopped or limited.
The summary (
summarize_operating_limits()) is stored indf.attrs["operating_limits"]and returned;Nonefor a frame withoutfailure_reason(nothing to summarise).modelgives the lower tank set point of a boiler. Call it on the rows collected fromstep()to get the reportanalyze_dynamicgives.- Parameters:
df (
Any)dt_s (
float)who (
str)model (
Any)
- Return type:
dict[str,Any] |None
Standard conditions: operating_range()¶
Standard rating conditions, and whether a model runs at them: operating_range().
Every system model has a method operating_range() that solves a short list
of standard test conditions with analyze_steady and returns one table row
per condition: whether the compressor runs there, whether it delivers the
requested duty or a reduced one, whether it cycles on and off, the
failure_reason of a point it cannot run, its cop_sys [-], and the
limit in words. It answers questions like “does the default R32 ASHPB run at
A-7/W55?” before a simulation is set up:
import tmhp
hp = tmhp.AirSourceHeatPumpBoiler(ref="R32")
table = hp.operating_range()
table[["condition", "T_tank_w [°C]", "runs", "meets_request", "failure_reason", "cop_sys [-]"]]
The check is a method and not part of construction because it solves the cycle at every condition: an air-source model is built in a few milliseconds, and solving its standard conditions takes a few tenths of a second, 30 to 140 times as long (the measured times are in the documentation, failure_reason semantics). The constructor’s own set-point check (a boiler’s upper tank set point above what its compressor envelope reaches) looks at the settings; this method solves operating points.
Conditions¶
A condition is a StandardCondition. The default lists below follow the
condition names and temperatures of EN 14511-2 (test conditions for rating)
and EN 14825 (part-load conditions for seasonal performance); the brine-to-air
cooling point follows ISO 13256-1 (ground-loop heat pumps). The name gives the
source side first and the load side second: A outdoor air (dry bulb),
B brine and W water entering the source heat exchanger, then W
water leaving the heat pump (boilers) or the indoor air (space heat pumps).
The default request is the nameplate duty hp_capacity; any condition can
be asked at part load (StandardCondition.at_part_load()), and a caller can
pass a list of their own.
Which model input a standard temperature is¶
Outdoor air is
T0(ASHP, ASHPB). The standard’s wet bulb, where it gives one, becomesRH_out(the frost correction of a heating point).Brine or source water entering the heat pump is
T_source(GSHPB, WSHPB). GSHP has no such argument: its source is the fluid leaving the borefield, the model stateT_bhe_f_out, which the table sets to the condition’s brine temperature on its copy of the model (below). A GSHP with ground-flow control (ground_flow_controlother than constant flow) solves its source from the borehole wall instead, so a brine temperature cannot be imposed:operating_range()refuses it (ValueError) rather than report a condition it did not solve.Leaving water (the
W35ofA7/W35) is not an input of the boiler models: their sink is the tank waterT_tank_wthat enters the plate condenser. The table hands them the water EN 14511 enters with: the leaving water less the standard’s temperature rise (en14511_water_rise(): 5 K up to 45 °C leaving, 8 K at 55 °C, 10 K at 65 °C). The air-source boiler takes the flow that carries the requested duty at that rise (m_dot_w,en14511_condenser_water()); the liquid-source boilers have no per-call flow, so their water enters at the leaving water less the rise of their own rated circulation flow (m_dot_w_rated). A boiler built without circulating water (m_dot_w_rated=0) is solved with its tank at the leaving water.sink_offset_Kreplaces the rise: the water enters that much below the leaving water at the boiler’s rated circulation flow (sink_offset_K=0solves the tank water at the named temperature – a stricter point, since the water then leaves hotter than the standard’s). The table prints both temperatures.Indoor air is
T_a_room(ASHP, GSHP).T0of GSHP, GSHPB and WSHPB is the dead state of the exergy columns only; the table gives it the source-side temperature.
Silence and state¶
The solves make no OperatingLimitWarning: what a warning would
say is the limit column, worded by the same generator
(tmhp.operating_limits.steady_message()). They do not count as the
“reported once per model and limit” of a later analyze_steady call. Each
condition is solved on a shallow copy of the model, so what a solve writes
on the model (GSHPB’s analyze_steady sets T_bhe_f_out_K to its
T_source, for one) stays on the copy.
- tmhp.standard_conditions.AIR_TO_AIR: tuple[StandardCondition, ...] = (StandardCondition(name='A7/20', mode='heating', source_side_C=7.0, load_side_C=20.0, outdoor_wet_bulb_C=6.0, part_load=1.0, basis='EN 14511-2 standard rating condition, heating (indoor 20 °C)'), StandardCondition(name='A2/20', mode='heating', source_side_C=2.0, load_side_C=20.0, outdoor_wet_bulb_C=1.0, part_load=1.0, basis='EN 14511-2 application rating condition; EN 14825 condition B (+2 °C)'), StandardCondition(name='A-7/20', mode='heating', source_side_C=-7.0, load_side_C=20.0, outdoor_wet_bulb_C=-8.0, part_load=1.0, basis='EN 14511-2 application rating condition; EN 14825 condition A (-7 °C)'), StandardCondition(name='A-15/20', mode='heating', source_side_C=-15.0, load_side_C=20.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 application rating condition (no wet bulb given)'), StandardCondition(name='A35/27', mode='cooling', source_side_C=35.0, load_side_C=27.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 standard rating condition, cooling: outdoor 35 °C (24 °C wet bulb), indoor 27 °C (19 °C wet bulb); the model is sensible-only, so the wet bulbs are not inputs'))¶
outdoor dry bulb / indoor dry bulb.
- Type:
Air-to-air conditions (ASHP)
- tmhp.standard_conditions.AIR_TO_WATER: tuple[StandardCondition, ...] = (StandardCondition(name='A7/W35', mode='heating', source_side_C=7.0, load_side_C=35.0, outdoor_wet_bulb_C=6.0, part_load=1.0, basis='EN 14511-2 standard rating condition, low-temperature application (30/35 °C)'), StandardCondition(name='A2/W35', mode='heating', source_side_C=2.0, load_side_C=35.0, outdoor_wet_bulb_C=1.0, part_load=1.0, basis='EN 14511-2 application rating condition'), StandardCondition(name='A-7/W35', mode='heating', source_side_C=-7.0, load_side_C=35.0, outdoor_wet_bulb_C=-8.0, part_load=1.0, basis='EN 14511-2 application rating condition; EN 14825 condition A (-7 °C)'), StandardCondition(name='A7/W55', mode='heating', source_side_C=7.0, load_side_C=55.0, outdoor_wet_bulb_C=6.0, part_load=1.0, basis='EN 14511-2 standard rating condition, medium-temperature application (47/55 °C)'), StandardCondition(name='A2/W55', mode='heating', source_side_C=2.0, load_side_C=55.0, outdoor_wet_bulb_C=1.0, part_load=1.0, basis='EN 14511-2 application rating condition'), StandardCondition(name='A-7/W55', mode='heating', source_side_C=-7.0, load_side_C=55.0, outdoor_wet_bulb_C=-8.0, part_load=1.0, basis='EN 14511-2 application rating condition; EN 14825 condition A (-7 °C), fixed outlet'), StandardCondition(name='A-10/W55', mode='heating', source_side_C=-10.0, load_side_C=55.0, outdoor_wet_bulb_C=-11.0, part_load=1.0, basis='EN 14825 operation limit TOL of the average climate (-10 °C), fixed outlet'), StandardCondition(name='A-15/W55', mode='heating', source_side_C=-15.0, load_side_C=55.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 application rating condition (no wet bulb given)'))¶
outdoor dry bulb (wet bulb) / leaving water.
- Type:
Air-to-water heating conditions (ASHPB)
- tmhp.standard_conditions.BRINE_TO_AIR: tuple[StandardCondition, ...] = (StandardCondition(name='B0/20', mode='heating', source_side_C=0.0, load_side_C=20.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 standard rating condition, brine-to-air heating; ISO 13256-1 ground loop'), StandardCondition(name='B25/27', mode='cooling', source_side_C=25.0, load_side_C=27.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='ISO 13256-1 ground-loop cooling (liquid entering 25 °C, indoor 27 °C)'))¶
brine leaving the borefield / indoor dry bulb.
- Type:
Brine-to-air conditions (GSHP)
- tmhp.standard_conditions.BRINE_TO_WATER: tuple[StandardCondition, ...] = (StandardCondition(name='B0/W35', mode='heating', source_side_C=0.0, load_side_C=35.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 standard rating condition, low-temperature application (brine 0/-3 °C)'), StandardCondition(name='B0/W55', mode='heating', source_side_C=0.0, load_side_C=55.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 standard rating condition, medium-temperature application (47/55 °C)'), StandardCondition(name='B-5/W45', mode='heating', source_side_C=-5.0, load_side_C=45.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 application rating condition'))¶
brine entering / leaving water.
- Type:
Brine-to-water heating conditions (GSHPB)
- tmhp.standard_conditions.COLUMNS: tuple[str, ...] = ('condition', 'mode', 'basis', 'part_load [-]', 'T_source_side [°C]', 'T_load_side [°C]', 'T_tank_w [°C]', 'RH_out [-]', 'inputs', 'runs', 'meets_request', 'Q_request [W]', 'Q_delivered [W]', 'Q_max [W]', 'Q_min [W]', 'capacity_clamped', 'capacity_binding', 'runtime_fraction [-]', 'cop_sys [-]', 'failure_reason', 'failure_detail', 'limit')¶
Columns of an
operating_range()table, the same for every family.
- tmhp.standard_conditions.EN14511_WATER_RISE_K: tuple[tuple[float, float], ...] = ((45.0, 5.0), (55.0, 8.0), (65.0, 10.0))¶
Water temperature rise across the condenser of an EN 14511 rating [K] at a leaving-water temperature [°C].
The low-, medium-, high- and very-high-temperature applications: 30/35 and 40/45 °C (5 K), 47/55 °C (8 K) and 55/65 °C (10 K);
en14511_water_rise()interpolates linearly between them and holds the ends.
- class tmhp.standard_conditions.StandardCondition(name, mode, source_side_C, load_side_C, outdoor_wet_bulb_C=None, part_load=1.0, basis='')[source]¶
Bases:
objectOne test condition: temperatures, mode and requested part load.
- Parameters:
name (
str) – Condition name in the standards’ notation, source side first:"A-7/W55","B0/W35","A7/20".mode (
str) – Heating for every boiler condition; the space heat pumps have both.source_side_C (
float) – Outdoor-air dry bulb (A), or brine or water entering the source heat exchanger (B,W) [°C]. In cooling it is the side the heat is rejected to.load_side_C (
float) – Water leaving the heat pump (boilers; the water entering it is solved the EN 14511 rise below it) or the indoor air (space heat pumps) [°C].outdoor_wet_bulb_C (
float|None) – Outdoor wet bulb [°C] of an air-source heating condition, passed to the model asRH_out.None: the standard gives none, or the model does not use it; the model’s default humidity applies.part_load (
float) – Requested duty as a share of the nameplatehp_capacity(> 0).basis (
str) – Where the condition comes from.
- name: str¶
- mode: str¶
- source_side_C: float¶
- load_side_C: float¶
- outdoor_wet_bulb_C: float | None = None¶
- part_load: float = 1.0¶
- basis: str = ''¶
- at_part_load(part_load)[source]¶
The same condition with the request at
part_loadof the nameplate duty.- Parameters:
part_load (
float)- Return type:
- property outdoor_humidity: float | None¶
Outdoor relative humidity (0-1) of the dry and wet bulb at 101325 Pa;
Nonewithout a wet bulb.
- __init__(name, mode, source_side_C, load_side_C, outdoor_wet_bulb_C=None, part_load=1.0, basis='')¶
- Parameters:
name (
str)mode (
str)source_side_C (
float)load_side_C (
float)outdoor_wet_bulb_C (
float|None)part_load (
float)basis (
str)
- tmhp.standard_conditions.WATER_TO_WATER: tuple[StandardCondition, ...] = (StandardCondition(name='W10/W35', mode='heating', source_side_C=10.0, load_side_C=35.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 standard rating condition, low-temperature application (10/7 °C)'), StandardCondition(name='W10/W55', mode='heating', source_side_C=10.0, load_side_C=55.0, outdoor_wet_bulb_C=None, part_load=1.0, basis='EN 14511-2 standard rating condition, medium-temperature application (47/55 °C)'))¶
source water entering / leaving water.
- Type:
Water-to-water heating conditions (WSHPB)
- tmhp.standard_conditions.en14511_condenser_water(T_leaving_C, duty)[source]¶
Water entering a condenser [°C] and its flow [kg/s] at an EN 14511 leaving-water temperature.
The flow carries
duty[W] at the standard’s rise (en14511_water_rise()):m_dot_w = duty / (c_w rise), and the water enters atT_leaving_C - rise. These are theT_tank_wandm_dot_woftmhp.AirSourceHeatPumpBoiler.analyze_steady().- Parameters:
T_leaving_C (
float)duty (
float)
- Return type:
tuple[float,float]
- tmhp.standard_conditions.en14511_water_rise(T_leaving_C)[source]¶
Water temperature rise across a boiler’s condenser at an EN 14511 leaving-water temperature [K].
5 K up to 45 °C leaving, 8 K at 55 °C, 10 K at 65 °C, linear in between (
EN14511_WATER_RISE_K): the water enters atT_leaving_C - en14511_water_rise(T_leaving_C).- Parameters:
T_leaving_C (
float)- Return type:
float
- tmhp.standard_conditions.operating_range(model, family, conditions=None, *, sink_offset_K=None)[source]¶
Solve rating conditions with
model.analyze_steadyand tabulate whether the machine runs at each.The implementation behind every model’s
operating_range()method; call the method.- Parameters:
model (
Any) – A system model (ASHP, GSHP, ASHPB, GSHPB, WSHPB).family (
str) – The model’s kind, which selects the default conditions and how a condition becomesanalyze_steadyarguments.conditions (
Iterable[StandardCondition] |None) – Conditions to solve; the family’s default list (AIR_TO_WATER, …) when omitted.sink_offset_K (
float|None) – Boilers: the water enters the condenser this far below the condition’s leaving water [K], at the boiler’s rated circulation flow (0 solves the tank water at the named temperature).None(default) is the EN 14511 rise (en14511_water_rise(); the air-source boiler at the flow that carries the duty at it). Not used by the space heat pumps.
- Returns:
One row per condition, in order, with the columns
COLUMNS:condition,mode,basis,part_load [-]: the condition.T_source_side [°C],T_load_side [°C]: its temperatures as named (leaving water for a boiler, indoor air for a space heat pump).T_tank_w [°C]: the tank water a boiler was solved with, the water entering its condenser (T_load_sideless the EN 14511 rise orsink_offset_K, see the module notes; NaN for a space heat pump).RH_out [-]: the outdoor humidity passed (NaN: the model default).inputs: the keyword arguments given toanalyze_steady(on a shallow copy of the model; GSHP: withT_bhe_f_outatT_source_side).runs: the compressor runs (hp_is_onandfailure_reason == "none").meets_request: it runs and delivers the request (within 0.1 %).Q_request [W],Q_delivered [W]: requested and delivered duty, signed as the model signs them (a space heat pump’s heating is below zero);Q_deliveredisQ_ref_tank [W]orQ_ref_iu [W]of the row.Q_max [W],Q_min [W],capacity_clamped,capacity_binding,runtime_fraction [-],cop_sys [-],failure_reason,failure_detail: the result keys of the row (see Result keys).capacity_clamped == "max"is a reduced duty,"min"an on/off mean (runtime_fraction [-]below 1).limit: what anOperatingLimitWarningwould say about the point – the call, the limit in words with its value, and what removes it – orNonewhen the point meets its request or is an on/off mean.
- Return type:
DataFrame
Simulation summary tables¶
Simulation summary output functions.
- tmhp.simulation_summary.print_dhw_service_summary(df, simulation_time_step)[source]¶
Print the hot-water service of a boiler dynamic result.
Requested, delivered and unmet hot-water heat [kWh], the number of draw steps left short and the coldest delivery (
tmhp.dhw.summarize_dhw_service()). Works on the result of any boiler model or combination; prints nothing for a frame withoutQ_dhw_request [W]/Q_dhw_unmet [W].- Parameters:
df (
DataFrame) – Simulation result DataFrame.simulation_time_step (
float) – Time step [s].
- Return type:
None
- tmhp.simulation_summary.print_operating_limit_summary(df, simulation_time_step, T_tank_w_lower_bound=None)[source]¶
Print what the operating limits did to a dynamic result.
The steps on which the compressor was called but did not run, by
failure_reason, the steps on which it ran below the request, bycapacity_binding, and what that left unserved (tmhp.operating_limits.summarize_operating_limits()), followed by what to do about each limit. Works on the result of any model; prints nothing for a frame withoutfailure_reason.- Parameters:
df (
DataFrame) – Simulation result DataFrame.simulation_time_step (
float) – Time step [s].T_tank_w_lower_bound (
float|None) – Lower thermostat set point of a boiler [°C], for the time the tank spent below it.None: not printed.
- Return type:
None
- tmhp.simulation_summary.print_simulation_summary(df, simulation_time_step, dV_ou_a_design)[source]¶
Print a comprehensive summary of simulation results.
A boiler result also gets the hot-water service section (
print_dhw_service_summary()): requested, delivered and unmet heat and the number of draw steps left short. A result with afailure_reasoncolumn gets the operating-limit section (print_operating_limit_summary()): steps on which the compressor was called but did not run, or ran below the request.- Parameters:
df (
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