Reinforcement learning (RL) represents an encouraging optimal control strategy for multi-energy management systems. Because it operates without an a priori model, RL diminishes both initial and continuous project-specific engineering demands while adeptly capturing enhanced representations of inherent system dynamics. Nevertheless, standard RL lacks guarantees for constraint satisfaction, which can lead to multiple hazardous interactions within the operational environment. This study introduces two innovative online, model-free safe RL techniques, termed SafeFallback and GiveSafe, which effectively separate the formulation of safety constraints from the RL architecture. These approaches ensure strict adherence to hard constraints throughout both the training phase and the execution of the (near- )optimal policy. Crucially, this is achieved without solving a mathematical program, thereby reducing computational overhead and allowing for greater flexibility in defining constraint functions. Through a simulated case study involving multi-energy systems, we demonstrate that both proposed methods initiate with substantially greater utility than both a standard RL baseline and an Optlayer baseline (94.6% and 82.8% versus 35.5% and 77.8%, respectively). Furthermore, the SafeFallback approach can even surpass the performance of the standard RL baseline (102.9% versus 100%). We conclude that these methodologies are robust safety-constraint mechanisms that extend well beyond RL applications, as evidenced by their ability to maintain hard-constraint guarantees even when employing random policies.
As technologies facilitating sector coupling reach maturity and see widespread deployment, energy systems are growing progressively more interconnected. This integration enables unified control strategies that can significantly improve the holistic efficiency and functionality of these multi-energy, multi-carrier, multi-commodity, or multi-utility frameworks. Moreover, such systems facilitate the exploitation of operational flexibility (e.g., controllable loads and storage) across and within distinct energy carriers. Generally, these integrated control mechanisms [1] are driven by economic, environmental, or combined objective functions, making them inherently multi-objective.
Achieving optimal or Pareto-optimal operational states in these multi-energy networks requires precise set-points to secure and sustain the target objectives (such as minimizing energy expenditures or CO2-equivalent emissions) while simultaneously satisfying all operational constraints [2]. Because flexibility deployment is highly dynamic and creates interdependencies across consecutive time intervals, it is essential to optimize over multiple time horizons. Furthermore, maintaining the stability of the multi-energy system necessitates the careful management of various uncertainties, including fluctuations in pricing, weather conditions, and energy demand.
Recent studies have evaluated both model-predictive control (MPC) and reinforcement learning (RL) within the framework of multi-energy management [3]. Research by Ceusters et al. [3] demonstrated that RL-driven energy management systems do not depend on an initial model and can surpass linear MPC frameworks post-training. Despite this, standard RL (Figure 1a) executes numerous potentially hazardous exploratory actions in its environment, a trait that is impermissible for many practical applications. In multi-energy systems, for instance, failing to respect fundamental energy balance constraints could lead to severe under- or over-production. For most power networks, such imbalances might trigger breaches of maximum grid power capacity limits—a critical concern given the anticipated widespread adoption of electric vehicles. Furthermore, these imbalances pose acute risks for isolated energy setups disconnected from centralized district heating or larger distribution grids, which lack supplementary oversight. In those scenarios, imbalances frequently degrade end-user comfort, manifesting as heating failures or power blackouts.
Consequently, the objective of this research is to guarantee that all interactions with the target environment (specifically, a multi-energy system in our analysis) comply with a predefined set of safety constraints, regardless of the distinct (optimal) control methodology applied (Figure 1b). By pursuing this architectural decoupling rather than engineering a dedicated safe RL algorithm, we ensure that subsequent, potentially superior optimization models can be seamlessly integrated in the future.

Figure 1. Comparison of block diagrams: the viability of the actions proposed by the RL agent, given a specific state, is continuously evaluated against pre-established constraint functions that serve as a safety mechanism, thereby protecting the system from dangerous (control) interventions. It is assumed here that ongoing unconstrained error management (namely, reducing the variance between a monitored process variable and the target set-point) is handled by proportional-integral-derivative (PID) controllers.
To the best of our understanding, the primary contributions of this work include:
· An online, model-free safe RL technique that ensures strict hard-constraint satisfaction—as opposed to soft or chance constraints—while yielding notably superior initial utility;
· An architectural decoupling of the safety constraint definitions from the underlying RL framework, enabling the effortless substitution of future, theoretically superior optimization algorithms;
· The achievement of hard-constraint guarantees without relying on the solution of a mathematical program, which consequently lowers computational demands and affords greater adaptability in formulating constraint functions (as derivative data is unnecessary);
· The practical demonstration of an energy management system governed by safe RL within a comprehensive multi-energy simulation platform.
Over the past few years, a multitude of studies have suggested applying RL across a variety of energy system applications. This body of research has been systematically reviewed by scholars such as Cao et al. [4], Yang et al. [5], and Perera and Kamalaruban [6], and further contextualized for the notably complex domain of multi-energy systems by Zhou [7]. Most of these use cases fall within the wider scope of energy management. In the context of multi-energy systems, practical demonstrations of RL-driven energy management frameworks include the pioneering work of Rayati et al. [8]. They utilized Q-learning [9] to manage energy within a simulated residential multi-energy structure, later incorporating demand-side management features [10]. Subsequently, Mbuwir et al. [11] successfully implemented RL (Q-learning) for a battery management setup within a comparable simulated residential environment, incorporating a fallback policy to override the RL agent whenever constraints were breached. Additionally, Wang et al. [12] combined a path-tracking interior point technique with an RL algorithm (Q-learning) to develop a bi-level interactive decision-making framework involving multiple agents in a regional multi-energy context. Ahrarinouri et al. [13] similarly introduced a multi-agent RL (Q-learning) methodology for energy management in simulated residential multi-energy systems. Concurrently, Ye et al. [14] applied a deep RL algorithm, specifically a deep deterministic policy gradient (DDPG) [15], enhanced with a prioritized experience replay mechanism, to a simulated residential multi-energy setup.
Furthermore, Xu et al. [16] presented a scheduling framework for industrial multi-energy systems that employs an RL (Q-learning)- based differential evolution strategy to dynamically determine the most effective mutation mechanism and its corresponding parameters. Along similar lines, Zhu et al. [17] implemented an energy management system powered by multi-agent counterfactual soft actor-critic (mCSAC) [18] deep RL for a simulated multi-energy industrial complex. Zhou et al. [19] introduced a data-driven stochastic energy management approach utilizing deep reinforcement learning, integrating prioritized experience replay to bolster training efficiency and algorithm convergence. Additionally, Ceusters et al. [3] formulated both on-policy and off-policy model-free RL methodologies for multi-objective scenarios. Utilizing proximal policy optimization (PPO [20]) and twin delayed deep deterministic policy gradient (TD3 [21]), they evaluated these against a linear MPC framework, with both approaches rooted in foundational optimal control theory. Their findings across two distinct simulated multi-energy environments indicated that RL agents can equal or exceed the performance of MPC. Meanwhile, Zhang et al. authored a sequence of studies [22-24] focusing on the (near-)optimal scheduling of an integrated energy system (i.e., multi-energy system) via deep reinforcement learning for both single- and multi-objective scenarios, which Zhang et al. [25] subsequently broadened to encompass distributed multi-energy systems via multi-agent deep reinforcement learning.
By its very nature, RL relies on interacting with an environment. It is crucial to implement sufficient safeguards to prevent the breach of environment-specific constraints, not only during active online training but also during the pure execution of a finalized policy (such as post-offline training). Whether explicitly acknowledged or not, the studies largely omitted or severely downplayed these specific environmental restrictions, thereby constraining their applicability in real-world scenarios. Breaching operational constraints in practical settings can trigger severe negative consequences, including financial deficits, compromised comfort, and potentially, physical injury to humans. Consequently, safe RL is designed to: “learn policies that maximize the expectation of the return in problems in which it is important to ensure reasonable system performance and/or respect safety constraints during the learning and/or deployment processes,” according to the definition provided by García and Fernández [26].
Through an extensive review extending beyond energy management, García and Fernández [26] evaluated the broader applications of safe RL, categorizing the methodologies into two primary strategies: (1) adjusting the optimality criteria by integrating a safety margin, and (2) altering the exploration phase by utilizing external knowledge or risk-based metrics for guidance. More recently, Dulac-Arnold et al. [27] outlined nine critical obstacles that must be surmounted to deploy RL in practical, real-world contexts, specifically highlighting the risk of safety constraint violations—a concern echoed by Nweye et al. [28]. Additionally, Brunke et al. [29] conducted a comprehensive examination of safe learning spanning both control theory and RL domains. They specifically detailed: (1) control techniques based on learning that begin with an a priori model to refine policies amidst dynamic system uncertainties securely; (2) safe RL methods that require neither an upfront model nor predefined constraints, though they lack definitive safety guarantees (despite promoting operational safety and robustness); and (3) methodologies that issue safety certifications for any acquired control policy.
As an early endeavor to merge hard-constraint adherence with RL within energy infrastructures, Venayagamoorthy et al. [30] introduced an intelligent dynamic energy management framework for a smart microgrid. This system utilized an action-dependent heuristic dynamic programming model that functions as an adaptive critic-based controller. To iteratively enhance the dispatch solution, they incorporated an evolutionary algorithm, systematically discarding any proposed candidate actions that failed the critical load fulfillment requirement, based on established power-balancing protocols and a rudimentary decision-tree management scheme. Additionally, Zhang et al. [31] conceptualized a bi-level power management architecture for interconnected microgrids operating within electrical distribution networks. At the primary tier, a cooperative agent leverages an adaptive, model-free RL algorithm to determine the optimal retail price indicators for the microgrids. At the secondary tier, individual model-based microgrid controllers execute a constrained mixed-integer nonlinear program informed by the price data supplied by the RL agent. Similarly, Zhao et al. [32] developed a knowledge-augmented RL structure that pairs a low-fidelity analytical model with an RL agent to manage cooperative wind farm controls. Should the RL agent select a naive action, a constrained alternative is computed by running an optimization process against the analytical model. Nonetheless, all these methodologies remain heavily dependent on prior physical models integrated into secondary optimization routines. Such architectures inherit a hypothesized transition function and an isolated objective function (distinct from the primary reward signal, potentially introducing bias) alongside constraint parameters—rather than relying exclusively on constraint functions.
Recently, and independently of our research, Park et al. [33] created an innovative RL algorithm heavily influenced by OptLayer [34], termed distance-based incentive/penalty Q-learning (DIP-QL). Demonstrated on a microgrid control scenario, this method similarly circumvents the need for an a priori transition function, relying exclusively on constraint parameters to establish strict hard-constraint assurances. However, their proposed technique fundamentally depends on a deep Q-learning algorithm as its backbone. In contrast, our approach advocates for the complete decoupling of constraint management from the core RL algorithm, enabling the seamless integration of subsequent, theoretically superior optimization models, as our framework is not restricted solely to RL applications.
An analysis of existing literature reveals that RL is a highly promising and frequently recommended approach for a broad spectrum of energy system applications (along with other fields not addressed herein), particularly concerning energy management systems. Furthermore, transitioning RL toward real-world deployment is highly complex and demands meticulous focus on operational safety. Various safe (reinforcement) learning methodologies are available, categorized by their safety assurances (from weakest to strongest): (1) soft-constraint satisfaction, (2) chance-constraint satisfaction, and (3) hard-constraint satisfaction. To the best of our awareness, however, no prior work has introduced and validated a model-free safe RL approach that seamlessly integrates all of the following attributes: (i) the provision of hard-constraint guarantees—superseding both soft- and chance-constraint compliances—across multiple variables; (ii) total architectural separation from the RL (modeled as a Markov Decision Process) formulation; (iii) functional reliability throughout the training of a (near) optimal policy (accommodating both greedy exploitation and exploratory actions) as well as during the deployment phase of any generalized policy (such as offline trained RL agents or random actors); (iv) the avoidance of having to solve a mathematical program; and (v) empirical demonstration within the context of multi-energy system energy management.
Adhering to the conventional RL definition of the state-value function while expanding it to subject it to constraints, the primary objective is to determine a policy π, which functions as a mapping of states, 𝑠 ∈ 𝑆, to actions, 𝑎 ∈ (𝑠),v that maximizes an expected sum of discounted rewards and is subject to constraint sets X and U:
(1a)
(1b)
(1c)
(1d)
Where Eπ represents the expected value, executed under policy π, concerning the associated rewards R and costs 𝑐 (which is explicitly delineated here to clarify negative reward penalties triggered when suggested actions breach predefined constraints)—adjusted by the discount factor 𝛾 across an infinite sum at any given time step t. The precise computational procedures are detailed in Algorithms 1 and 2.
It should be noted that Eq. 1a represents a discrete1 time-invariant, infinite-horizon stochastic optimal control problem, consistent with the observations of Ceusters et al. [3]. However, it diverges from conventional RL paradigms due to the inclusion of a priori constraint functions embedded within sets X and U. While techniques lacking a priori constraint parameters do exist, the current state-of-the-art for such methods maxes out at safety level 2 (chance-constraint satisfaction). In contrast, our approach ensures safety level 3 (hard-constraint satisfaction), adhering to the classification by Brunke et al. [29]. Instead of designing a singular, highly specialized safe RL algorithm, we advocate for dissociating the a priori constraint function architecture from the primary (RL) agent. This separation ensures that any (new RL) algorithm can be utilized—while consistently guaranteeing hard-constraint satisfaction. Even though the computational logic of these proposed algorithms remains theoretically straightforward, their practical efficacy will be subsequently demonstrated on a multi-energy system (specifically incorporating a non-grid-connected thermal system).
Our initial proposed approach depends on a predefined safe fallback policy, πsafe. This policy can generally be established using conventional control theory, often consisting of rigid, hard-coded rules, such as a straightforward rule-based framework. Additionally, assuming the constraint functions are already defined, we can easily verify whether the chosen actions 𝑎 taken in state s comply with the necessary constraint parameters. If these conditions are met, the selected actions a are classified as safe actions. These are subsequently implemented within the environment, yielding observations of the ensuing state s′, the reward r, and the done signal d. This sequence forms the standard experience tuple (𝑠, 𝑎𝑠𝑎𝑓𝑒, 𝑟, 𝑠′, 𝑑) utilized by the RL agent. Conversely, should the chosen action a fail the constraint verification, it is superseded by the safe action 𝑎𝑠𝑎𝑓𝑒 dictated by the predefined safe fallback policy πsafe. In this scenario, two distinct experience tuples are generated: the standard tuple (𝑠, 𝑎𝑠𝑎𝑓𝑒, 𝑟, 𝑠′, 𝑑) and an additional tuple (𝑠, 𝑎, 𝑟 - 𝑐, 𝑠′, 𝑑), which records the invalid action alongside an associated negative reward (or cost, c). Algorithm 1 outlines the corresponding pseudo-code.

Algorithm1. SafeFallback
The second approach we introduce eliminates the need for a predetermined safe fallback policy. Instead, it relies entirely on the RL agent itself to output safe actions 𝑎𝑠𝑎𝑓𝑒, which are continuously evaluated against the established constraint conditions. Should the chosen actions a in state s successfully clear the constraint verification, these safe actions 𝑎𝑠𝑎𝑓𝑒 are deployed within the environment, generating the conventional experience tuple (𝑠, 𝑎𝑠𝑎𝑓𝑒, 𝑟, 𝑠′, 𝑑). However, if the constraints are breached, the RL agent is presented with the experience tuple (𝑠, 𝑎, 𝑐, 𝑠, 𝑑). Consequently, because the invalid action is not implemented, the system does not advance to the subsequent state, and a cost c (representing a negative reward) is applied. Following this, the RL agent must formulate a new action a, prompting another constraint evaluation. This loop continues until an action successfully clears the verification process, designating it as a safe action 𝑎𝑠𝑎𝑓𝑒. This verified action is then enacted in the environment, yielding a standard experience tuple. Algorithm 2 details the relevant pseudo-code, while Figure 2 illustrates this process conceptually as a Markov Chain.

Algorithm 2. GiveSafe
It is important to note that within this framework, the cost c should ideally be structured as an informative function (a shaped cost), given that the agent gains no advantage from a shaped reward if the constraint verification fails.

Figure 2. Markov Chain of Algorithm 2. When the selected action is infeasible (does not satisfy the constraints), that unsafe action is not executed in the environment, so no transition to the next state St+1 is observed, and a cost Ct is given. When the selected actions are feasible (satisfy the constraints), those safe actions are executed in the environment, so a transition to the next state St+1 is observed with probability 𝑝(𝑠𝑡+1 ∣ 𝑠𝑡, 𝑎𝑡) and a reward Rt is given.
We employed a multi-energy system simulation model created by Ceusters et al. [3]. This model was selected because it permits the safe testing of critical operational parameters (such as verifying that all energy requirements are met) without the adverse consequences or dangers associated with breaching real-world constraints. The simulation was built using Modelica [35], which facilitates straightforward modeling of expected real-world system behaviors through multiphysics, first-principles equations, complemented by its object-oriented design, fundamental components, and access to highly specialized libraries.
Subsequently, this Modelica model was exported as a co-simulation functional mock-up unit (FMU), reflecting the approach in Ref. [36]. It was then integrated into a Python-based OpenAI gym environment [37], mirroring the methodology detailed in Refs. [3] and [38]. Figure 3 displays the architectural layout of this toolchain. It should be noted that the Differential Algebraic Equations solver is embedded within the co-simulation FMU. Furthermore, the do_step() function from PyFMI [39] was utilized instead of simulate. As observed in Ref. [3], this choice provides a substantial enhancement in processing speed when properly initialized.

Figure 3. Architecture of the toolchain.
The multi-energy framework examined in this study closely resembles the architecture presented by Ceusters et al. [3], except that the gas turbine (backup generator) is omitted. The structural configuration is as follows (Figure 4):
Proceeding from left to right and top to bottom, the system incorporates: an electrical transformer, a wind turbine, a photovoltaic (PV) array, a natural gas boiler, a heat pump (HP), a combined heat and power (CHP) generator, a thermal energy storage system (TESS), and a battery energy storage system (BESS). The physical dimensions and capacities of this multi-energy network are also derived from [3] and are outlined in Table 1.

Figure 4. Structure of the simulated multi-energy system.
Although the dynamic simulation comprises a highly intricate set of differential-algebraic equations (totaling 2.548 equations with a corresponding number of variables [3]), it omits any simulated regulatory control mechanisms (such as the PID controllers illustrated in Figure 1). For this case study, we abstract this control layer. Consequently, any actions initiated within the simulation remain static throughout the designated control horizon (15 min), and continuous unconstrained error correction (the ongoing reduction of the discrepancy between a target set-point and an observed process variable) is excluded. We consider this abstraction reasonable—and it is consistently applied across all evaluated energy management algorithms to ensure fair comparison—though it introduces a control deviation of roughly 5%. This margin of error was identified through independent simulations running on a shortened 5 s control horizon.
Table 1. Dimensions of the multi-energy system.
Energy asset | Input | Output | Enom | Pmin | Pnom |
Transformer | elec | elec |
| -∞ | +∞ |
Wind turbine | wind | elec |
| 1.5% | 0.8 MWe |
Solar PV | solar | elec |
| 0% | 1.0 MWe |
Boiler | CH4 | heat |
| 10% | 2.0 MWth |
Heat pump | elec | heat |
| 25% | 1.0 MWth |
CHP | CH4 | heat |
| 50% | 1.0 MWth |
Empty Cell | CH4 | elec |
| 50% | 0.8 MWe |
TESS | heat | heat | 3.5 MWh | −0.5 MWth | +0.5 MWth |
BESS | elec | elec | 2.0 MWh | −0.5 MWe | +0.5 MWe |
In this specific case study, the constraint functions defined in Eqs. 1c, 1d take the following form (refer to the note regarding modelling effort associated with Eq. 3c:
(2a)
(2b)
(2c)
(2d)
(2e)
(2f)
Here, , , and signify the thermal power outputs of the natural gas boiler, heat pump, combined heat and power (CHP) unit, and thermal energy storage system (TESS), respectively. Similarly, , and indicate the electrical power consumption or output for the heat pump, CHP, and battery energy storage system (BESS). All of these are bounded by their respective minimum and maximum capacity limits (Table 1). Additionally, , and function as binary indicators used to toggle the operational state of these assets (necessary because their minimum operating powers exceed zero). As a result, they do not necessitate an independent constraint verification process.
Assuming the electrical grid connection is robust enough to handle capacity demands, the electrical energy balance is continuously satisfied. In contrast, ensuring strict adherence to the thermal energy balance (Eq. 2f) requires dedicated oversight to guarantee hard-constraint compliance. We exclude any supplementary operational constraints in this analysis (such as ramp-up/ramp-down limits, or mandated minimum run/idle times), since energy balance conditions are generally recognized as the primary limiting factors in energy management scenarios. Expanding the thermal energy balance and easing the strict equality constraint (converting it into an inequality constraint) yields:
(3a)
(3b)
(3c)
In this context, At represents the (control) actions, η stands for energy efficiencies, COP denotes the coefficient of performance, SOC indicates the state of charge, and T refers to an array of specific thermal metrics (specifically, for the boiler return temperature, for the heat pump evaporator temperature, for the heat pump condenser temperature, for ambient air temperature, and for the mean temperature within the layered hot water storage tank). The tolerance parameter Qtol is established at 15,0% of the aggregate during the assessment timeframe. While we recognize this percentage is somewhat elevated, it was selected to restrict computational overhead. It is important to emphasize that deriving precise models for the various functions f (.) in Eq. 3c is generally complex. Consequently, we presume access to a historical data archive, allowing us to apply supervised learning (specifically, a Random Forest Regression technique) to map the relationship between thermal power and applied actions directly (i.e. = f ()). This method accommodates the integration of relevant external variables X_asset^t. To accurately reflect practical real-world applications, this training dataset is produced via the simulation environment rather than extracted directly from the fundamental differential algebraic equations.
Table 2. Safety layer model metrics with test_size of 0.25. Mean Absolute Error (MAE), Normalized Mean Absolute Error (NMAE) by range, i.e., NMAE = MAE/range(actual values).
Energy asset | NMAE | MAE | R2-score |
Boiler | 0.34% | 7.2 kW | 99.92% |
Heat pump | 0.62% | 6.1 kW | 99.74% |
CHP | 0.38% | 4.3 kW | 99.86% |
TESS | 1.37% | 12.9 kW | 96.22% |
BESS | 0.46% | 4.6 kW | 99.43% |
As detailed, Algorithm 1 depends on a predetermined safe fallback policy πsafe. This can take the form of any feasible, albeit potentially suboptimal, strategy that adheres to the system constraints and is generally formulated by subject matter experts. Within the context of our case study, this manifests as a straightforward priority rule.

Algorithm 3. Safe fallback policy
It should be noted that, for the sake of clarity, this policy is articulated using thermal power outputs; however, it is ultimately translated into the specific control actions and during the transition from Eq. 3a to Eq. 3b.
The fully observable discrete-time Markov decision process (MDP) is structured as the tuple ⟨𝑆, 𝐴, 𝑃𝑎, 𝑅𝑎⟩, defined as follows:
(4a)
(4b)
(4c)
(4d)
Here, represents the required thermal energy, signifies the required electrical energy, denotes the electrical power supplied by the wind turbine, indicates the electrical power generated by the solar panels, is the market price for electricity (specifically, the day-ahead spot market price), defines the state-of-charge for the TESS, is the state-of-charge for the BESS, ht stands for the current hour, and dt indicates the current day of the week. All these variables are captured at the tth interval, collectively forming the state-space S. The corresponding action-space A encompasses the operational set-points for the various assets: for the natural gas boiler, for the heat pump, for the CHP system, for the TESS, and for the BESS. These set-points are strictly bounded by their specific minimum and maximum power constraints, as detailed in Table 1.
The primary objective of the energy management agent is dictated by the reward function Ra (in this context, aiming to maximize a negative value, effectively minimizing its positive counterpart, aligning with Eq. 1a). This objective incorporates the negative impact of energy expenses and comfort deterioration at the tth time-step, scaled by the respective weights a and b. Additionally, a penalty cost c is imposed whenever constraint violations are anticipated.3 Comfort deterioration is mathematically represented as | - 𝑄𝑡|, where 𝑄𝑡 stands for the total thermal energy generated. Within the Modelica framework, it is presumed that both electrical power and natural gas supplies can be fully satisfied via robust connections to infinitely large external utility grids. It is important to note that the comfort penalty remains restricted by the tolerance bounds set in Eq. 3c. Consequently, this component of the reward function acts as a precise calibration tool. It helps further reduce comfort loss within allowable limits (steering the RL agents toward more reliable operational choices) and compensates for any inherent inaccuracies within the constraint models themselves (Table 2 ).
Financial energy expenses are calculated in EUR, utilizing a scalarization multiplier of 𝑎 = 1∕10. Conversely, comfort loss is measured in Watts with a multiplier of 𝑏 = 1∕5𝑒5. The penalty variable is defined as c = 1 for algorithm 1, whereas algorithm 2 utilizes 𝑐 = -50 + (10 𝐢𝐟 > 0.5 𝐞𝐥𝐬𝐞 0). The framework operates on a 15-min discrete-time control horizon. Furthermore, the state-space S undergoes normalization, and all executable variables in the action-space A are proportionally adjusted to fit within a [+1, -1] range. The scalarization weights applied here align with those established by Ceusters et al. [3].
For the learning architecture, we implemented a twin delayed deep deterministic policy gradient (TD3) agent—widely recognized as a cutting-edge RL methodology—sourced from the stable baseline library [40]. The selected hyperparameters for this setup are cataloged in Table 3. These values were established following a hyper-parameter optimization process, akin to the procedures in [3], spanning both Algorithms 1 and 2.
Crucially, these RL agents do not require an initial “offline” pre-training phase dependent on historical data. Instead, they undergo safe “online” training (executed within a simulated setting). Consequently, the RL agents begin operations devoid of any preexisting environmental insight, dynamically constructing their own training dataset (experience tuples) through active engagement with the environment (represented by the multi-energy system in this study).
Table 3. TD3 hyper-parameters.
Hyper-parameters (TD3) | Optsafe | Unsafe | Algorithm 2 | Algorithm 1 |
Gamma | 0.7 | 0.9 | 0.95 | 0.7 |
Learning rate | 0.000583 | 0.0003833 | 0.000119 | 0.000583 |
Batch size | 16 | 100 | 16 | 16 |
Buffer size | 1e6 | 1e5 | 1e5 | 1e6 |
Training frequency | 1e0 | 2e3 | 1e1 | 1e0 |
Gradient steps | 1e0 | 2e3 | 1e1 | 1e0 |
Noise type | normal | normal | normal | normal |
Noise standard deviation | 0.183 | 0.329 | 0.791 | 0.183 |
The effectiveness of our proposed techniques, Algorithms 1 and 2, is assessed by evaluating their ability to minimize energy costs while adhering to thermal comfort constraints. These are benchmarked against an unrestricted (and potentially hazardous) RL agent, the OptLayer RL agent introduced by Pham et al. [34] (noted in related literature), and both safe and unsafe random agents. The random agents function as baseline learning metrics for their respective algorithms (indicating the amount of learning achieved through safe environmental interaction) and represent the baseline performance before any training phase. Consequently, these random agents are not proposed as practical optimal controllers. The experimental setup utilizes a one-year training period, a 15-min control horizon (meaning the energy management RL agent can choose new actions every 15 simulated minutes4), and a one-week evaluation phase within a day-ahead electricity market framework. Inherent uncertainties (such as fluctuations in demand, pricing, or renewable generation) are naturally managed by the RL agent through its formulation as a discrete time-invariant infinite-horizon stochastic optimal control problem (refer to Ref. [3] for the transformation from a continuous time-varying stochastic system). The model-predictive controller discussed in Ref. [3] is excluded from this comparison, as our approach allows for direct constraint formulation within the methodology.
The simulation outcomes regarding the objective values (rewards) are presented in Table 4, displaying both absolute figures and values relative to the unrestricted RL benchmark. The tolerance for the inequality constraint, Eq. 3c, is expressed as a proportion of the total demand (where 0% indicates strict equality constraint fulfillment, meaning all thermal demands are met, including energy routed to thermal storage).
The data in Table 4 demonstrates that Algorithm 1 (SafeFallback: 102.9%) surpasses Algorithm 2 (GiveSafe: 98.2%) and the standard unsafe TD3 baseline (100%), although it slightly trails OptLayer (104.0%). This outcome is logical, given that employing the predefined safe fallback policy yields the greatest utility before any training (94.6% in contrast to 82.8%, 35.5%, and 77.8%), highlighting the value of the embedded expert knowledge. This supplementary expert insight (inherent to the safe fallback policy of Algorithm 1 itself—see πsafe) also manifests in an initially elevated constraint tolerance (7.0%), which eventually stabilizes at a satisfactory 10.1% (well below the 15% maximum threshold established in Eq. 3c). Algorithm 2 and OptLayer exhibit higher initial constraint tolerances (15.0% and 15.6%, respectively) but ultimately converge to comparable levels (10,0% and 10,4%). Unsurprisingly, the SafeFallback policy (πsafe) inherently maintains the strictest constraint tolerance (6.3%). The elevated tolerance observed in SafeFallback Random (and consequently SafeFallback TD3 before training) is attributable to its capacity to randomly select safe actions, which remain constrained by the 15% upper limit. Thus, as designed, both proposed techniques offer substantially greater safety than the unconstrained vanilla TD3 benchmark, which begins with a massive 146.0% constraint tolerance and only improves to 21.0% (reflecting an unsafe training process devoid of hard-constraint guarantees, an unacceptable condition in real-world scenarios, but useful here strictly as a baseline). It is worth noting that OptLayer initially breaches the 15% maximum limit set in Eq. 3c. This violation occurs because OptLayer relies on solving a mixed-integer quadratic problem to determine the closest feasible actions. Furthermore, OptLayer employs linear analytical approximations rather than the surrogate functions f (.) from Eq. 3c associated with the metrics in Table 2, due to a lack of derivative data.
Table 4. 5-run average policy performance with a training budget of 15 years’ worth of time steps per run (i.e. 525.150 time steps per run).
EMS algorithm | Constraint | Objective value | |
Tolerance | Relative | Absolute | |
Unsafe TD3 | 21.0% | 100.0% | −5.043 |
Unsafe Random | 146.0% | 35.5% | −14.223 |
OptLayer TD3 | 10.4% | 104.0% | −4.850 |
OptLayer Random | 15.6% | 77.8% | −6.481 |
SafeFallback TD3 | 10.1% | 102.9% | −4.899 |
SafeFallback Random | 7.0% | 94.6% | −5.331 |
SafeFallback (πsafe) | 6.3% | 96.5% | −5.228 |
GiveSafe TD3 | 10.0% | 98.2% | −5.137 |
GiveSafe Random | 15.0% | 82.8% | −6.089 |
The training trajectories of the TD3 agents (implementing Algorithms 1, 2, OptLayer, and a baseline lacking any safety layer—indicated as UnSafe) are illustrated in Figure 5. The starting (time step 0) and concluding (time step 525.150) data points correspond to the values detailed in Table 4. We note an initially rapid learning phase, minimal variance, and steady (marginally improving) efficacy as the agent interacts more extensively with the environment. Furthermore, Algorithm 1 (SafeFallback), Algorithm 2 (GiveSafe), and OptLayer exhibit substantially superior initial performance (before training at time step 0) when contrasted with the vanilla unsafe TD3 agent. This advantage stems from the integration of preliminary expert knowledge, supplied via the known safe fallback policy and the safety constraint equations. The unsafe RL agent requires approximately 35.000 time steps (1 year) to match OptLayer’s starting performance (−6.481). It takes roughly 50.000 time steps (1 year and 5 months) to equal Algorithm 2’s starting benchmark (−6.089), and about 85.000 time steps (2 years and 5 months) to reach Algorithm 1’s initial level (−5.331). Additionally, OptLayer’s baseline performance falls below that of Algorithms 1 and 2; it eclipses Algorithm 2 after roughly 18.575 time steps (6 months) and surpasses Algorithm 1 after approximately 30.000 time steps (10 months). The performance disparity remains notable against Algorithm 2 (5.8%), whereas Algorithm 1 achieves a comparable final performance (1.1%).

Figure 5. 5-run average learning curves with a training budget of 15 years’ worth of time steps per run (i.e. 525.150 time steps per run). Note that the y-axis is zoomed in

Figure 6. 5-run average cost curve (i.e., constraint tolerance) with a training budget of 15 years’ worth of time steps per run (i.e., 525.150 time steps per run). Note that the -axis is zoomed in
Figure 6 illustrates the cost trajectories (constraint tolerances) for the respective TD3 agents. The vanilla TD3 agent demonstrates a sharp initial drop in constraint tolerance but never achieves the 15% safety boundary mandated by Eq. 3c. Conversely, Algorithms 1 and 2 strictly maintain compliance below this threshold (validating their capacity for hard-constraint satisfaction during the training phase). At the same time, OptLayer marginally exceeds it, as previously discussed. The safe methods exhibit a more gradual convergence in constraint tolerance, settling at a consistent level (∼ 10%) following roughly 3 years (∼ 1𝑒5 time steps). Consequently, if the L_comfort^t variable were removed, the constraint tolerance would drift toward the 15% maximum limit, because a pure cost-minimization strategy would aggressively curtail expensive energy usage (in the absence of constraints or the L_comfort^t factor, all controllable energy assets would shut down during periods of positive energy pricing). This dynamic explains why we see both downward-trending cost curves (initiating above the convergence threshold) and an upward-trending cost curve (initiating below the threshold).
It is crucial to acknowledge, however, that the success of Algorithm 1 (SafeFallback), Algorithm 2 (GiveSafe), and OptLayer — in terms of both overall utility (objective value) and cost control (constraint tolerance) — hinges on the precise definition of the actual constraints, specifically the accurate modeling of Eq. 3c within this study. Establishing this precision can be complex, particularly regarding the TESS and the HP components. If the pre-trained functions for the TESS and HP within the safety layer are replaced with more rudimentary (linear) analytical equations (identical to those used in OptLayer), performance degrades. For instance, under Algorithm 1, the initial objective value shifts from −5.331 to −5.431, and the initial constraint tolerance worsens from 7,0% to 7,6%. This degradation can be partially offset, however, by artificially reducing the Qtol parameter in Eq. 3c.
Nonetheless, deploying an RL agent for training within a genuine safety-critical setting is only feasible with a highly accurate safety framework (i.e., robust constraints) and appropriate, albeit initially unknown, hyperparameters. Consequently, we outline the following avenues for subsequent research:
· Establishing chance-constraint satisfaction guarantees for scenarios where predefined constraint functions are unavailable (relying instead on restricted, verified-safe operational data) and methodically refining these initial constraint models as additional data is gathered. Under this framework, a statistical model (such as a Gaussian Process model) would be continuously updated to ensure that exploratory and exploitative actions remain within the safe operational envelope with a high degree of probability.
· Minimizing the required training budget (thereby boosting sample efficiency, potentially by integrating SafeFallback with OptLayer) and implementing a predetermined series of (robust5) control actions (for instance, through model-based RL agents) to facilitate day-ahead market scheduling.
· Enhancing the resilience of RL-driven energy management frameworks against erroneous or noisy data inputs and incorporating online hyper-parameter optimization techniques (allowing hyperparameters to adjust dynamically throughout the online training phase).
This research introduced two innovative model-free safe reinforcement learning (RL) strategies characterized by the following features: (i) they ensure hard-constraint satisfaction across multiple constraints, rather than relying on soft or chance constraints; (ii) they operate independently from the primary RL (Markov Decision Process) architecture; (iii) they maintain safety both throughout the training of a (near) optimal policy (accommodating exploratory and greedy exploitative actions) and during the execution of any given policy (including random agents or pre-trained offline RL agents); and (iv) they achieve this without necessitating the resolution of a mathematical program. The efficacy of these techniques was showcased within the context of a multi-energy management system, supported by comprehensive simulation data.
Both proposed approaches represent practical constraint-handling mechanisms that expand upon current state-of-the-art RL methodologies, successfully providing rigid safety guarantees even when applied to random agents. However, Algorithm 1 (SafeFallback) emerges as the preferred option. It demonstrates strong performance, bypasses the need for solving complex mathematical programs (unlike OptLayer, which requires a mixed-integer quadratic program), and capitalizes on the fact that rudimentary safe fallback policies are typically either already available or straightforward to engineer (often manifesting as a basic rule-based framework, such as a priority-driven control protocol).
This work has been supported in part by ABB n.v., Belgium and Flemish Agency for Innovation and Entrepreneurship (VLAIO) grant HBC.2019.2613, Belgium.
None
None
None
Open Access The author(s) retain copyright. This article is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. It may be shared and adapted for non-commercial purposes with appropriate attribution, an indication of changes, and distribution of adaptations under the same license. Third-party material may be subject to separate terms identified in its credit line. View the license at https://creativecommons.org/licenses/by-nc-sa/4.0/.