Source code for tmhp.integrations.energyplus_plugin

"""EnergyPlus Python Plugin adapter for the tmhp ASHPB.

Surrogates :class:`~tmhp.AirSourceHeatPumpBoiler` inside EnergyPlus as a
``PlantComponent:UserDefined`` device. Each plant-solver call hands the plugin
the loop inlet temperature, mass flow, specific heat, and load request, plus the
site outdoor drybulb temperature and relative humidity. The plugin solves the
refrigerant cycle with the public ``analyze_steady()`` seam and writes back the
outlet-temperature and mass-flow actuators, routing the system's electricity
to a metered output.

Metered electricity and delivered heat (what crosses the EnergyPlus boundary)
-----------------------------------------------------------------------------
The metered power is the **system total** ``E_tot`` of the solved cycle —
compressor **plus outdoor-fan** power (the plugin globals keep their historical
``tmhp_E_cmp*`` names). The heat handed to the plant loop and the metered power
always belong to the same operating state:

``q_loop``
    heat put into the loop, ``m_dot * cp * (T_out - T_in)``.
``E_meter = E_tot * q_loop / Q_cycle``
    the solved cycle runs a fraction ``q_loop / Q_cycle`` of the timestep.

Two situations make ``q_loop`` smaller than the heat ``Q_cycle`` of the solved
(continuously running) cycle:

* **Minimum-speed clamp.** Below its minimum compressor speed the machine cannot
  deliver the requested part load continuously. With the model's default
  ``Cd_cycling`` the cycle result is already the on/off mean of the
  minimum-speed machine (``capacity_clamped == "min"``, ``runtime_fraction [-]``
  below 1): ``Q_cycle`` equals the request and ``E_tot`` includes the cycling
  loss (``E_cycling_loss [W]``), so the duty fraction below is 1 and the loss is
  metered. Only a model built with ``Cd_cycling=None`` returns the continuous
  minimum-speed point (``Q_cycle`` > request); the plugin then treats it as
  on/off cycling itself: the time-averaged heat equals the load request and the
  electricity is scaled by the same duty fraction, with no cycling-degradation
  penalty. ``PlantComponent:UserDefined`` documents the
  ``Load Request for Plant Connection N`` as the *desired operating capacity* for
  a connection in a load-meeting mode, and the loop outlet temperature is
  ``T_in + q / (m_dot cp)``: supplying the clamped ``Q_cycle`` instead would
  overheat the loop and the storage tank relative to what EnergyPlus asked for.
* **Outlet limit** ``TOUT_MAX``. Heat that would push the outlet above the limit
  is not delivered, and the electricity that would have produced it is not metered.

Why ``analyze_steady`` (not ``step()``): EnergyPlus owns the storage-tank state
through ``WaterHeater:Mixed`` and asks the component for a *steady* answer each
timestep (given the inlet/outdoor conditions and the loop load, what is the
leaving temperature and the electric input). The dynamic ``step()`` kernel — and
its tank model — is instead what the FMU adapter
(:mod:`tmhp.integrations.fmu`) wraps. The two BES adapters therefore ride on
different seams of the same model.

Runtime: EnergyPlus runs Python plugins in its **embedded CPython**, so
``pyenergyplus`` is provided by the EnergyPlus install (not pip-installable) and
``tmhp`` + native deps (CoolProp/numpy/scipy) must be built for that
interpreter's ABI and pointed to via ``PythonPlugin:SearchPaths``. Verify with an
import-only smoke plugin first — a wrong-ABI CoolProp wheel fails silently.

Configuration (environment variables, all optional):

=====================================  ===========================================
``TMHP_ASHPB_REF``                     refrigerant (default ``R32``; e.g. R290, R410A)
``TMHP_ASHPB_CAPACITY``                nominal HP capacity in W (default ``15000``)
``TMHP_ASHPB_PRESET``                  named parameter preset (default empty = model defaults)
``TMHP_ASHPB_VDISP_CC``                compressor displacement in cm³ (required with preset)
``TMHP_ASHPB_FAN_M3S``                 rated outdoor fan flow in m³/s (required with preset)
``TMHP_UD_NAME``                       ``PlantComponent:UserDefined`` object name
                                       (default ``ASHPB_UserDefined``)
``TMHP_LOOP_DESIGN_VDOT``              design loop volume flow in m³/s (default ``0.003``)
``TMHP_EPLUS_ECMP_ENERGY_GLOBAL``      plugin global receiving timestep energy [J]
                                       (default ``tmhp_E_cmp_J``)
``TMHP_EPLUS_ECMP_POWER_GLOBAL``       optional plugin global receiving power [W]
                                       (default ``tmhp_E_cmp_W``)
``TMHP_PLUGIN_LOG``                    if set, append a per-call/tally log to this path
=====================================  ===========================================

IDF wiring (the "IDF wiring" section of
``docs/source/integrations/energyplus-python.rst`` lists every object): one
``PlantComponent:UserDefined`` named ``ASHPB_UserDefined`` with an init manager
bound to :class:`TmhpPlantInit` and a simulation manager bound to
:class:`TmhpPlantSurrogate`, a ``PythonPlugin:Variables`` global
``tmhp_E_cmp_J`` for summed energy metering, and optionally ``tmhp_E_cmp_W`` for
averaged power reporting. The legacy global ``tmhp_E_cmp`` is still accepted as
an energy sink for older IDFs.

API strings (actuator component type ``"Plant Connection 1"``; internal
variables ``"... for Plant Connection 1"``) are verified against EnergyPlus
24.2.0; reconfirm them for other releases.
"""

from __future__ import annotations

import atexit
import contextlib
import itertools
import math
import os
import uuid
from typing import Any

try:
    from pyenergyplus.plugin import EnergyPlusPlugin
except ModuleNotFoundError:  # pragma: no cover - exercised where EnergyPlus is absent

    class EnergyPlusPlugin:  # type: ignore[no-redef]
        """Minimal stand-in so pure adapter helpers stay testable outside E+."""

        def __init__(self) -> None:
            self.api: Any = None


from tmhp import AirSourceHeatPumpBoiler
from tmhp.integrations import _fmi_common

# --- Configuration (read once at import) ------------------------------------
REF = os.environ.get("TMHP_ASHPB_REF", "R32")
HP_CAPACITY = float(os.environ.get("TMHP_ASHPB_CAPACITY", "15000"))
PRESET = os.environ.get("TMHP_ASHPB_PRESET", "")
V_CMP_DISP_CC = float(os.environ.get("TMHP_ASHPB_VDISP_CC", "0"))
DV_FAN_A_RATED = float(os.environ.get("TMHP_ASHPB_FAN_M3S", "0"))
UD_NAME = os.environ.get("TMHP_UD_NAME", "ASHPB_UserDefined")
LOOP_DESIGN_VDOT = float(os.environ.get("TMHP_LOOP_DESIGN_VDOT", "0.003"))  # m³/s
ECMP_ENERGY_GLOBAL = os.environ.get("TMHP_EPLUS_ECMP_ENERGY_GLOBAL", "tmhp_E_cmp_J")
ECMP_POWER_GLOBAL = os.environ.get("TMHP_EPLUS_ECMP_POWER_GLOBAL", "tmhp_E_cmp_W")
ECMP_LEGACY_GLOBAL = "tmhp_E_cmp"
# None -> stdout only. Resolved once, so the exit summary lands in the same
# file even if a Python API host changes its working directory before exiting.
_LOG = os.path.abspath(os.environ["TMHP_PLUGIN_LOG"]) if os.environ.get("TMHP_PLUGIN_LOG") else None

MDOT_FLOOR = 0.05  # kg/s — below this the inlet flow is treated as "off"
TOUT_MAX = 95.0  # °C — clamp inside the liquid-water property range
RHO_WATER = 1000.0  # kg/m³ — sizing only
GUARD_WARNING_LIMIT = 5  # repeated warnings per failure reason before suppression
# The EPW data dictionary accepts relative humidity from 0 to 110 %, and
# EnergyPlus 24.2 passes such readings to Site Outdoor Air Relative Humidity
# unclipped. A reading from 100 to 110 % is saturated air and is used as 100 %.
EPW_RH_MAX_PERCENT = 110.0
# EnergyPlus interpolates hourly weather to the zone timestep; between two
# 110 % hours that can land a few ULP above 110 (110.00000000000001 at 15
# steps per hour), which is still the EPW endpoint.
EPW_RH_ROUNDING_PERCENT = 1e-9
_WEATHER_VARIABLES = {
    "t0": "Site Outdoor Air Drybulb Temperature",
    "rh_out": "Site Outdoor Air Relative Humidity",
}


def _ashpb_model_kwargs(
    *,
    ref: str,
    hp_capacity: float,
    preset: str = "",
    V_cmp_disp_cc: float = 0.0,
    dV_fan_a_rated: float = 0.0,
) -> dict[str, Any]:
    """Return constructor kwargs without requiring an EnergyPlus runtime."""
    return {
        "ref": ref,
        "hp_capacity": hp_capacity,
        **_fmi_common.preset_kwargs(
            preset,
            ref=ref,
            hp_capacity=hp_capacity,
            V_cmp_disp_cc=V_cmp_disp_cc,
            dV_fan_a_rated=dV_fan_a_rated,
        ),
    }


def _normalize_failure_reason(value: object) -> str | None:
    """Normalize model diagnostics for adapter tally keys."""
    if value is None or isinstance(value, str):
        return value
    return str(value)


def _finite_float_or_none(value: Any) -> float | None:
    """Parse a finite float from an EnergyPlus boundary value."""
    try:
        out = float(value)
    except (TypeError, ValueError):
        return None
    return out if math.isfinite(out) else None


def _is_finite(value: Any) -> bool:
    """Return whether *value* can safely cross the EnergyPlus boundary."""
    return _finite_float_or_none(value) is not None


def _is_positive_finite(value: Any) -> bool:
    """Return whether *value* is a usable positive finite number."""
    out = _finite_float_or_none(value)
    return out is not None and out > 0.0


def _cycle_electric_power(res: dict[str, Any]) -> float | None:
    """System electricity of a solved steady cycle [W]: ``E_tot``, else compressor + fan.

    ``None`` when no finite value can be formed.
    """
    e_tot = _finite_float_or_none(res.get("E_tot [W]"))
    if e_tot is not None:
        return e_tot
    e_cmp = _finite_float_or_none(res.get("E_cmp [W]"))
    if e_cmp is None:
        return None
    fan = _finite_float_or_none(res.get("E_ou_fan [W]"))
    return e_cmp + (0.0 if fan is None else fan)


def _has_usable_cycle_output(res: dict[str, Any]) -> bool:
    """Whether a steady result can actuate the EnergyPlus plant component."""
    return _is_positive_finite(_cycle_electric_power(res)) and _is_positive_finite(res.get("Q_ref_tank [W]"))


[docs] def delivered_heat_and_power( res: dict[str, Any], *, q_request: float, t_in: float, m_dot: float, cp: float ) -> tuple[float, float]: """Heat put into the loop [W] and the electricity metered for it [W]. ``q_request`` is the load EnergyPlus asked for (capped at the nominal capacity). The solved cycle delivers ``Q_cycle`` at ``E_tot``; the loop receives ``min(Q_cycle, q_request, m_dot * cp * (TOUT_MAX - t_in))`` and the machine is metered for the matching share of the timestep (see the module docstring). """ q_cycle = float(res["Q_ref_tank [W]"]) e_cycle = float(_cycle_electric_power(res)) # type: ignore[arg-type] headroom = max(0.0, m_dot * cp * (TOUT_MAX - t_in)) q_loop = min(q_cycle, q_request, headroom) return q_loop, e_cycle * (q_loop / q_cycle)
def _issue_severe(api: Any, state: Any, msg: str) -> None: """Report an EnergyPlus severe error when the runtime API is available.""" runtime = getattr(api, "runtime", None) issue_severe = getattr(runtime, "issue_severe", None) if callable(issue_severe): issue_severe(state, msg) def _issue_warning(api: Any, state: Any, msg: str) -> None: """Report an EnergyPlus warning when the runtime API is available.""" runtime = getattr(api, "runtime", None) issue_warning = getattr(runtime, "issue_warning", None) if callable(issue_warning): issue_warning(state, msg) else: _log(msg) _RH_OUTCOME_RANK = {"weather": 0, "clipped_to_100": 1, "default": 2} # Numbers the plant surrogates of this process. With a random run id it lets # the final summaries of several runs in one process (EnergyPlus Python API), # or of separate runs appended to one TMHP_PLUGIN_LOG file, be told apart; # process ids alone repeat across runs. _SURROGATE_RUNS = itertools.count(1) def _log_humidity_summary(run_id: str, counts: dict[str, int]) -> None: """Log the final outdoor-humidity counts of a run.""" text = " ".join(f"{name}={count}" for name, count in counts.items()) _log(f"[outdoor RH final] {run_id}: zone timesteps with a heating dispatch, warmup days excluded: {text}") def _log_final_humidity_summary(run_id: str, counts: dict[str, int], pid: int) -> None: """Shutdown hook: log the final counts in the process that ran the plugin. A child forked after the plugin was built inherits this hook and the run id; it stays silent so the run is summarized once. """ if os.getpid() == pid: _log_humidity_summary(run_id, counts) def _set_global_if_valid(ex: Any, state: Any, handle: int, value: float) -> None: """Write an EnergyPlus plugin global only when it was declared in the IDF.""" if handle != -1: ex.set_global_value(state, handle, value) def _log(msg: str) -> None: # A closed stdout at interpreter shutdown must not drop the file copy. with contextlib.suppress(OSError, ValueError): print(msg, flush=True) if _LOG: try: with open(_LOG, "a") as f: f.write(msg + "\n") except OSError: pass
[docs] class TmhpPlantInit(EnergyPlusPlugin): """One-shot sizing actuators so the plant loop dispatches load to the ASHPB. Bind to the ``PlantComponent:UserDefined`` *initialization* program-calling manager (E+ runs it once before plant sizing). """
[docs] def __init__(self) -> None: super().__init__() self._need = True self.h: dict[str, int] = {}
def _get_handles(self, state: Any) -> None: ac = self.api.exchange.get_actuator_handle self.h = dict( design_vdot=ac(state, "Plant Connection 1", "Design Volume Flow Rate", UD_NAME), mdot_min=ac(state, "Plant Connection 1", "Minimum Mass Flow Rate", UD_NAME), mdot_max=ac(state, "Plant Connection 1", "Maximum Mass Flow Rate", UD_NAME), cap_min=ac(state, "Plant Connection 1", "Minimum Loading Capacity", UD_NAME), cap_max=ac(state, "Plant Connection 1", "Maximum Loading Capacity", UD_NAME), cap_opt=ac(state, "Plant Connection 1", "Optimal Loading Capacity", UD_NAME), ) self._need = False def _valid(self, state: Any) -> bool: ok = True for k, v in self.h.items(): if v == -1: ok = False self.api.runtime.issue_severe(state, f"[TmhpInit] handle not found: {k}") return ok
[docs] def on_user_defined_component_model(self, state: Any) -> int: if not self.api.exchange.api_data_fully_ready(state): return 0 if self._need: self._get_handles(state) _log("[TmhpInit handles] " + ", ".join(f"{k}={v}" for k, v in self.h.items())) if not self._valid(state): return 1 ex = self.api.exchange ex.set_actuator_value(state, self.h["design_vdot"], LOOP_DESIGN_VDOT) ex.set_actuator_value(state, self.h["mdot_min"], 0.0) ex.set_actuator_value(state, self.h["mdot_max"], LOOP_DESIGN_VDOT * RHO_WATER) ex.set_actuator_value(state, self.h["cap_min"], 0.0) ex.set_actuator_value(state, self.h["cap_max"], HP_CAPACITY) ex.set_actuator_value(state, self.h["cap_opt"], 0.9 * HP_CAPACITY) return 0
[docs] class TmhpPlantSurrogate(EnergyPlusPlugin): """Per-call ASHPB driver: read loop inlet + outdoor, solve, actuate. Bind to the ``PlantComponent:UserDefined`` *simulation* program-calling manager. Exposes compressor electricity through the plugin global ``tmhp_E_cmp_J`` (declare it in ``PythonPlugin:Variables`` and meter it as summed joules). ``tmhp_E_cmp_W`` can be declared for averaged power output. """
[docs] def __init__(self) -> None: super().__init__() model_kwargs = _ashpb_model_kwargs( ref=REF, hp_capacity=HP_CAPACITY, preset=PRESET, V_cmp_disp_cc=V_CMP_DISP_CC, dV_fan_a_rated=DV_FAN_A_RATED, ) self.hp = AirSourceHeatPumpBoiler(**model_kwargs) self._need = True self._requested = False self.h: dict[str, int] = {} self._ncall = 0 self._nlog = 0 # The plant solver re-calls with identical inputs many times per timestep, # so memoize on rounded inputs to avoid recomputing the CoolProp-heavy cycle. self._cache: dict[tuple[float, float, float, float, float | None], dict[str, Any]] = {} self._warned_humidity = False # Zone timesteps with a heating dispatch (warmup days excluded) by the # humidity the solve used: the weather reading, a reading above 100 % # used as 100 %, or the model default after a missing or invalid # reading. Logged with the periodic tally and once when EnergyPlus # shuts the plugin interpreter down (the CLI calls Py_FinalizeEx). self._rh_timesteps = {"weather": 0, "clipped_to_100": 0, "default": 0} self._rh_timestep_key: tuple[int, int, int, int, int] | None = None self._rh_timestep_outcome = "" # Hold only the counters, not the plugin and its solve cache. self._run_id = f"run {uuid.uuid4().hex[:12]} (pid {os.getpid()} #{next(_SURROGATE_RUNS)})" atexit.register(_log_final_humidity_summary, self._run_id, self._rh_timesteps, os.getpid()) # Convergence tally over dispatched calls (cold-climate high-lift hours # may trip the pressure-ratio guard); dumped periodically to the log. self._ndispatch = 0 self._nconv = 0 self._reasons: dict[str | None, int] = {} self._tally_every = 5000 self._warning_counts: dict[str, int] = {}
def _solve( self, t_in: float, t0: float, q_target: float, m_dot: float, *, rh_out: float | None = None ) -> dict[str, Any]: """Reuse a steady result for rounded inputs and solve at the humidity bin center.""" # A 0.01 percentage point cache bin is finer than the percent-level EPW # humidity input and retains sub-percent changes from weather interpolation. rh_bin = None if rh_out is None else round(rh_out, 4) key = (round(t_in, 1), round(t0, 1), round(q_target, 0), round(m_dot, 4), rh_bin) res = self._cache.get(key) if res is None: res = self.hp.analyze_steady( T_tank_w=t_in, T0=t0, Q_ref_tank=q_target, m_dot_w=m_dot, RH_out=rh_bin, ) self._cache[key] = res return res def _read_outdoor_humidity(self, state: Any) -> float | None: """Read the weather percentage as a fraction, using the model default on bad data. Readings above 100 % up to the EPW limit of 110 % are used as 100 %. Each zone timestep outside warmup is counted once in the tally by the humidity the solve used. """ handle = self.h["rh_out"] ex = self.api.exchange raw = None # The flag is sticky and shared. Leave errors from other API calls intact. if handle != -1 and not ex.api_error_flag(state): raw = ex.get_variable_value(state, handle) if ex.api_error_flag(state): # A failed read returns zero. Clear this optional read's error so # EnergyPlus does not abort when the callback returns. ex.reset_api_error_flag(state) raw = None percent = _finite_float_or_none(raw) if percent is not None and 0.0 <= percent <= 100.0: self._count_humidity_timestep(state, "weather") return percent / 100.0 if percent is not None and 100.0 < percent <= EPW_RH_MAX_PERCENT + EPW_RH_ROUNDING_PERCENT: self._count_humidity_timestep(state, "clipped_to_100") return 1.0 self._count_humidity_timestep(state, "default") if not self._warned_humidity: self._warned_humidity = True _issue_warning( self.api, state, f"[TmhpSurrogate] missing or invalid outdoor relative humidity ({raw!r}); using the model default.", ) return None def _count_humidity_timestep(self, state: Any, outcome: str) -> None: """Count a zone timestep once, however often the plant solver calls within it. The key is the zone timestep, not the clock: ``current_time()`` moves with HVAC system substeps inside one zone timestep. """ ex = self.api.exchange if ex.warmup_flag(state): return key = ( ex.current_environment_num(state), ex.year(state), ex.day_of_year(state), ex.hour(state), ex.zone_time_step_number(state), ) if key != self._rh_timestep_key: self._rh_timestep_key = key self._rh_timestep_outcome = outcome self._rh_timesteps[outcome] += 1 return # A later call in the same timestep that fell back (or was clipped) # reclassifies it, so the counts never hide a fallback the log shows. if _RH_OUTCOME_RANK[outcome] > _RH_OUTCOME_RANK[self._rh_timestep_outcome]: self._rh_timesteps[self._rh_timestep_outcome] -= 1 self._rh_timesteps[outcome] += 1 self._rh_timestep_outcome = outcome def _log_humidity_summary(self) -> None: """Log the outdoor-humidity counts of the run so far.""" _log_humidity_summary(self._run_id, self._rh_timesteps) def _warn_guard_trip(self, state: Any, reason: str, t_in: float, t0: float, q_target: float) -> None: """Issue a bounded number of warnings for a thermodynamic guard.""" count = self._warning_counts.get(reason, 0) + 1 self._warning_counts[reason] = count if count > GUARD_WARNING_LIMIT: return suffix = " Further warnings for this reason are suppressed." if count == GUARD_WARNING_LIMIT else "" _issue_warning( self.api, state, f"[TmhpSurrogate] {reason}: condenser temperature is at/below loop inlet; " f"forcing zero heat, compressor power, and water flow " f"(T_in={t_in:.2f}C, T0={t0:.2f}C, Qtarget={q_target:.1f}W).{suffix}", ) def _get_handles(self, state: Any) -> None: ex = self.api.exchange iv, ac = ex.get_internal_variable_handle, ex.get_actuator_handle self.h = dict( t_in=iv(state, "Inlet Temperature for Plant Connection 1", UD_NAME), mdot=iv(state, "Inlet Mass Flow Rate for Plant Connection 1", UD_NAME), cp=iv(state, "Inlet Specific Heat for Plant Connection 1", UD_NAME), load=iv(state, "Load Request for Plant Connection 1", UD_NAME), t_out_act=ac(state, "Plant Connection 1", "Outlet Temperature", UD_NAME), mdot_act=ac(state, "Plant Connection 1", "Mass Flow Rate", UD_NAME), ) self.h.update( {field: ex.get_variable_handle(state, name, "Environment") for field, name in _WEATHER_VARIABLES.items()} ) # EnergyPlus 24.2 aborts a simulation if get_global_handle receives an # undeclared name. PluginGlobalVariable entries carry the name in key. declared_globals = { point.key.upper(): point.key for point in ex.get_api_data(state) if point.what == "PluginGlobalVariable" } for field, name in ( ("e_cmp_j", ECMP_ENERGY_GLOBAL), ("e_cmp_w", ECMP_POWER_GLOBAL), ("e_cmp_legacy", ECMP_LEGACY_GLOBAL), ): declared_name = declared_globals.get(name.upper()) self.h[field] = ex.get_global_handle(state, declared_name) if declared_name is not None else -1 self._need = False def _valid(self, state: Any) -> bool: ok = True for k, v in self.h.items(): if k in {"rh_out", "e_cmp_j", "e_cmp_w", "e_cmp_legacy"}: continue if v == -1: ok = False _issue_severe(self.api, state, f"[TmhpSurrogate] handle not found: {k}") if self.h.get("e_cmp_j", -1) == -1 and self.h.get("e_cmp_legacy", -1) == -1: ok = False _issue_severe( self.api, state, "[TmhpSurrogate] handle not found: energy global " f"{ECMP_ENERGY_GLOBAL!r} (or legacy {ECMP_LEGACY_GLOBAL!r})", ) return ok def _set_electric_outputs(self, state: Any, e_cmp_w: float, e_cmp_j: float) -> None: """Write EnergyPlus global outputs with explicit W/J semantics.""" ex = self.api.exchange _set_global_if_valid(ex, state, self.h.get("e_cmp_j", -1), e_cmp_j) _set_global_if_valid(ex, state, self.h.get("e_cmp_legacy", -1), e_cmp_j) _set_global_if_valid(ex, state, self.h.get("e_cmp_w", -1), e_cmp_w)
[docs] def on_user_defined_component_model(self, state: Any) -> int: """Solve a dispatched heating load, actuate the plant, and log the model result.""" ex = self.api.exchange if not ex.api_data_fully_ready(state): return 0 # Keep the request/lookup passes separate. The CLI also needs the IDF # Output:Variable declarations so the data is retained for the plugin. if not self._requested: for name in _WEATHER_VARIABLES.values(): ex.request_variable(state, name, "Environment") self._requested = True return 0 if self._need: self._get_handles(state) _log("[TmhpSurrogate handles] " + ", ".join(f"{k}={v}" for k, v in self.h.items())) if not self._valid(state): return 1 self._ncall += 1 t_in_raw = ex.get_internal_variable_value(state, self.h["t_in"]) mdot_raw = ex.get_internal_variable_value(state, self.h["mdot"]) cp_raw = ex.get_internal_variable_value(state, self.h["cp"]) q_req_raw = ex.get_internal_variable_value(state, self.h["load"]) t0_raw = ex.get_variable_value(state, self.h["t0"]) t_in = _finite_float_or_none(t_in_raw) mdot = _finite_float_or_none(mdot_raw) cp = _finite_float_or_none(cp_raw) q_req = _finite_float_or_none(q_req_raw) # loop heating load request [W] t0 = _finite_float_or_none(t0_raw) if t_in is None or mdot is None or mdot < 0.0 or cp is None or cp <= 0.0 or q_req is None or t0 is None: _issue_severe( self.api, state, "[TmhpSurrogate] invalid EnergyPlus boundary values: " f"T_in={t_in_raw!r}, mdot={mdot_raw!r}, cp={cp_raw!r}, " f"Qreq={q_req_raw!r}, T0={t0_raw!r}", ) safe_t_in = 0.0 if t_in is None else t_in ex.set_actuator_value(state, self.h["t_out_act"], safe_t_in) ex.set_actuator_value(state, self.h["mdot_act"], 0.0) self._set_electric_outputs(state, e_cmp_w=0.0, e_cmp_j=0.0) return 1 # No load requested -> component off (request no flow). if q_req < 1.0: ex.set_actuator_value(state, self.h["t_out_act"], t_in) ex.set_actuator_value(state, self.h["mdot_act"], 0.0) self._set_electric_outputs(state, e_cmp_w=0.0, e_cmp_j=0.0) return 0 # Heating requested. The loop hands mdot=0 until the component *requests* # flow, so set the mass-flow actuator to design flow when inlet flow is # zero (mirrors the E+ PlantComponent:UserDefined chiller example). m_dot = mdot if mdot > MDOT_FLOOR else LOOP_DESIGN_VDOT * RHO_WATER ex.set_actuator_value(state, self.h["mdot_act"], m_dot) timestep_raw = ex.system_time_step(state) timestep_h = _finite_float_or_none(timestep_raw) if timestep_h is None or timestep_h <= 0.0: _issue_severe( self.api, state, f"[TmhpSurrogate] invalid EnergyPlus system timestep: {timestep_raw!r}", ) ex.set_actuator_value(state, self.h["t_out_act"], t_in) ex.set_actuator_value(state, self.h["mdot_act"], 0.0) self._set_electric_outputs(state, e_cmp_w=0.0, e_cmp_j=0.0) return 1 q_target = min(q_req, HP_CAPACITY) rh_out = self._read_outdoor_humidity(state) res = self._solve(t_in, t0, q_target, m_dot, rh_out=rh_out) converged = bool(res.get("converged")) reason = _normalize_failure_reason(res.get("failure_reason")) self._ndispatch += 1 if converged and reason == "none": self._nconv += 1 else: self._reasons[reason] = self._reasons.get(reason, 0) + 1 if self._ndispatch % self._tally_every == 0: _log( f"[tally @ dispatch {self._ndispatch}] converged={self._nconv} " f"({100.0 * self._nconv / self._ndispatch:.1f}%) guard_trips={dict(self._reasons)} " f"outdoor_RH_timesteps={self._rh_timesteps} (heating-dispatch zone timesteps, warmup excluded)" ) guard_trip = reason == "t_cond_below_t_in" if not guard_trip and _has_usable_cycle_output(res): q, e_cmp = delivered_heat_and_power(res, q_request=q_target, t_in=t_in, m_dot=m_dot, cp=cp) t_out = t_in + q / (m_dot * cp) energy_j = e_cmp * 3600.0 * timestep_h else: q = e_cmp = energy_j = 0.0 t_out = t_in if guard_trip and reason is not None: self._warn_guard_trip(state, reason, t_in, t0, q_target) ex.set_actuator_value(state, self.h["t_out_act"], t_out) ex.set_actuator_value(state, self.h["mdot_act"], 0.0 if guard_trip else m_dot) self._set_electric_outputs(state, e_cmp_w=e_cmp, e_cmp_j=energy_j) if self._nlog < 40: self._nlog += 1 # Log what the model used so the design-day smoke test checks the # handoff to the cycle as well as the EnergyPlus weather read. rh_used = _finite_float_or_none(res.get("RH_out [-]")) rh_log = "default" if rh_out is not None: rh_log = "unavailable" if rh_used is None else f"{rh_used:.2%}" _log( f"[call {self._ncall:4d}] T_in={t_in:6.2f}C T0={t0:6.2f}C mdot={mdot:6.3f}kg/s " f"RH_out={rh_log} Qreq={q_req:8.1f}W -> converged={converged} reason={reason} " f"E_cmp={e_cmp:8.1f}W Q={q:8.1f}W T_out={t_out:6.2f}C" ) return 0