Daniela Yassuda Yamashita

Ionel Vechiu

Jean-Paul Gaubert

Two

Keywords:

come

Introduction

Renewable Energy Sources (RESs) play a fundamental role in paving the way toward transforming the global energy sector from fossil-based to zero-carbon energy. This evolution depends on policy-based incentives and restructuring in all branches of the energy sector. Particularly, buildings represent the second largest sector emitter of greenhouse gas, accounting for 28% of global CO 2 emissions, in which two-thirds comes from electricity generation [START_REF]Perspective for the clean energy transition 2019[END_REF]. Rapid energy transitioning scenario plans to reduce by 90% the carbon emissions produced from electricity by 2050, through a shift in the energy matrix toward low-carbon sources, such as solar and wind energy [START_REF]Perspectives for the Energy Transition: Investment Needs for a Low-Carbon Energy System[END_REF]. In this context, Building MicroGrids (BMGs) [START_REF] Lawrence | Ten questions concerning integrating smart buildings into the smart grid[END_REF] have emerged as an innovative grid topology to promote the penetration of renewables and foster decarbonisation.

By bringing the power generation to the final energy consumers, BMGs can be less dependent on the external grid, reducing energy transportation losses [START_REF] Lawrence | Ten questions concerning integrating smart buildings into the smart grid[END_REF]. However, contrary to traditional coal and gas power plants, RESs production varies according to weather conditions. Stochasticity in power generation leads the BMG to inject into the main grid when there is an energy surplus and import in the opposite case. From the point of view of the external grid, this complicates grid management, especially due to the subtle rise of unpredictable grid actors [START_REF] Lüth | Local electricity market designs for peer-to-peer trading: the role of battery flexibility[END_REF]. To maintain grid stability, Energy Storage Systems (ESSs) are key elements to achieve a high portion of internal load matching from renewable energy generated locally and consequently enhance building energy autonomy indexes, such as the self-consumption rate [START_REF] Luthander | Photovoltaic self-consumption in buildings: a review[END_REF].

There is a manifold of storage technologies, with different states of maturity that can be applied to BMGs depending on the desired response time and capacity. In recent years Li-ion batteries have demonstrated suitable behaviour for MicroGrid (MG) applications, thanks to their high energy density (80-200 Wh/kg), high energy efficiency (90-97%), and fast response time (<5 ms) [START_REF] Argyrou | Energy storage for electricity generation and related processes: technologies appraisal and grid scale applications[END_REF]. In contrast, Li-ion batteries cannot handle the seasonality of solar energy properly due to the selfdischarging phenomenon (<5%/month) and the sharp increase of installation costs according to their capacity [START_REF] Kim | Field study on operational performance and economics of lithium-polymer and lead-acid battery systems for consumer load management[END_REF]. On the contrary, hydrogen storage has become an important long-term seasonal ESS for enabling the energy transition, on account of its high energy capacity Energy assigned to fuel cells if in zone 1 (Wh)

E zone2 f c

Energy assigned to fuel cells if in zone 2 (Wh)

E zone3 f c

Energy assigned to fuel cells if in zone 3 (Wh)

E cons

Energy consumed by the building (Wh)

E injected grid

Energy injected into the external grid (Wh)

E import grid

Energy imported from the external grid (Wh)

π elec

Electricity price (€/Wh) F Faraday constant (As/mol) n H2 Number of moles of hydrogen stored in the tank (moles) n max (300 -1200 Wh/kg) and its almost zero self-discharge rate [START_REF] Argyrou | Energy storage for electricity generation and related processes: technologies appraisal and grid scale applications[END_REF][START_REF] Ren | Optimal operation of a grid-connected hybrid PV/ fuel cell/battery energy system for residential applications[END_REF]. In particular, despite power fluctuations, Proton Exchange Membrane (PEM) technology for electrolysis and fuel cells can be coupled with RESs [START_REF] Rakousky | Polymer electrolyte membrane water electrolysis: Restraining degradation in the presence of fluctuating power[END_REF].

In this perspective, the combination of short-and long-term ESS has been envisaged for real BMG implementation, as highlighted in [START_REF] Ren | Optimal operation of a grid-connected hybrid PV/ fuel cell/battery energy system for residential applications[END_REF][START_REF] Lokar | The potential for integration of hydrogen for complete energy self-sufficiency in residential buildings with photovoltaic and battery storage systems[END_REF]. A battery bank is usually designed to absorb the transients in the power balance, whereas hydrogen ESS is more suitable for smooth peak shaving. However, despite being totally clean, hydrogen storage in power-to-power configurationusing fuel-cell stacks and electrolysersis prevented from being broadly implemented due to its low electric round-trip efficiency (around 40%) [START_REF] Lamy | From hydrogen production by water electrolysis to its utilization in a PEM fuel cell or in a SO fuel cell: Some considerations on the energy efficiencies[END_REF] and its high capital costs (some price ranges are mentioned in [START_REF] Parra | A review on the role, cost and value of hydrogen energy systems for deep decarbonisation[END_REF]). In addition, the Energy Management System (EMS) of hybrid ESS is more complex than single ones, owing to the system's higher degree of freedom, which may result in adverse effects on the MG operation from an economic and efficiency standpoints.

In the literature, different strategies concerning EMS for hybrid ESS are present, such as those detailed in [START_REF] Argyrou | Energy storage for electricity generation and related processes: technologies appraisal and grid scale applications[END_REF], [START_REF] Yamashita | A review of hierarchical control for building microgrids[END_REF] and [START_REF] Fontenot | Modeling and control of building-integrated microgrids for optimal energy managementa review[END_REF]. Fuzzy logic and Rule-Based (RB) algorithms are the simplest control strategies that can be easily implemented in real-time applications. However, they do not guarantee the optimal operation of BMGs, and they need exhaustive prior testing with stringent knowledge of the MicroGrid (MG) plant model. The main drawback of these deterministic control strategies is that they usually rely only on the MG's current status, without considering future situations throughout analysis of prediction data. Controversially, more advanced strategies, such as Model Predictive Control (MPC), embed prediction data in their decision-making processes. The strength of MPC lies in considering current and future plant behaviour through the processing of both prediction data and MG mathematical model. By means of periodic optimisations over a sliding window, the MPC has proved its robustness against external disturbances [START_REF] Nassourou | Economic model predictive control for energy dispatch of a smart micro-grid system[END_REF][START_REF] Velarde | On the comparison of stochastic model predictive control strategies applied to a hydrogenbased microgrid[END_REF].

The weakness of MPC is its dependence on reliable modelling and defining cost function. When dealing with hybrid ESS, the MPC's objective function is usually designed as a multi-objective one, as in [START_REF] Velarde | On the comparison of stochastic model predictive control strategies applied to a hydrogenbased microgrid[END_REF][START_REF] Petrollese | Real-time integration of optimal generation scheduling with MPC for the energy management of a renewable hydrogen-based microgrid[END_REF][START_REF] Valverde | Integration of fuel cell technologies in renewableenergy-based microgrids optimizing operational costs and durability[END_REF]. The trade-off between batteries and the hydrogen chain is often handled by weighted factors in the MPC's cost function that are usually tuned through a trial and error approach. These weighted factors are often ordered to reduce, in all circumstances, the total imports and exports of grid energy and prioritizing the use of batteries over the hydrogen chain. This clearly diminishes the generality of the controller and might prevent the MPC from achieving its objectives if these weighted factors in the cost function are not well-tuned or subjected to unexpected changes in the plant model. To overcome this issue, the multi-objective MPC's cost function is usually normalised by converting each cost function term into the same physical unit, such as the local currency for economic optimisations [START_REF] Garcia-Torres | Optimal economical schedule of hydrogen-based microgrids with hybrid storage using model predictive control[END_REF][START_REF] Vivas | A suitable state-space model for renewable source-based microgrids with hydrogen as backup for the design of energy management systems[END_REF]. To determine a balanced use of the hybrid ESS, the degradation cost of batteries, electrolysers, and fuel cells as well as the electricity price are often integrated. Nonetheless, these optimisations are limited to the MPC's horizon and consider neither seasonality throughout the year nor the long-term objectives, such as the requirement of the building annual selfconsumption rate.

To tackle these weaknesses of MPC structures, this paper presents a two-level Hierarchical MPC (HMPC) empowered with two data-driven modules, namely a Real-Time Model Identification (RTMI) module, and an MG cost estimator. The main objective of these two data-oriented control units is to reduce the need for a precise pre-design phase in EMS blueprints based on MPC. The focus is to determine adequate parameters of the MPC's internal model and its cost function definition with minimal human intervention.

In this respect, the RTMI module aims to continuously improve the accuracy of the MPC's internal model by processing local measurements acquired at ESS branches. On the other hand, the MG cost estimator adjusts the cost function of the HMPC daily based on the analysis of both day-ahead and power imbalance prediction data of the previous year. This daily adjustment in the MPC cost function aims to satisfy the required marks of the annual self-consumption rate imposed by the grid code at minimum cost. Additionally, the balanced use of batteries and hydrogen chain is determined automatically by estimating their End of Life (EoL) calculated from the combination of local measurements and manufacture's specification as proposed in [START_REF] Vivas | A suitable state-space model for renewable source-based microgrids with hydrogen as backup for the design of energy management systems[END_REF]. Moreover, the contribution of each installed ESS to reducing the BMG injection is assessed daily to regulate the balance between profit and cost.

Through simulations in MATLAB Simulink, this proposed control strategy is compared with another HMPC designed with a conventional cost function that considers neither the ESS degradation nor the expected self-consumption rate. Additionally, the performance of the proposed HMPC is confronted against a traditional rule-based controller. The remainder of this paper is structured as follows. The overview of the BMG sizing together with its hierarchical EMS is described in Section 2. Thereafter, Section 3 describes the HMPC by stating its objective functions and its main constraints. In Section 4, the RTMI algorithm is explained, whereas in Section 5 the MG cost estimator module is detailed. The comparison of the three control strategies and the analysis drawn from the simulation results are presented in Section 6. Finally, Section 7 presents the main conclusions obtained from the developed work.

Overview of the building microgrid and its hierarchical energy management system

The BMG under study is a grid-connected MG primarily supplied by rooftop photovoltaic (PV) arrays, as illustrated in Fig. 1. To reduce grid energy imports and exports, the EMS relies on Li-ion batteries and a hydrogen chain of sizing specified in Table 1.

The energy exchange with the external grid is continuously supervised by a smart meter installed near the bidirectional interlinking DC-AC converter connecting the BMG to the main grid. The smart meter collects the building's raw net energy imbalance (E imb,k ) defined by [START_REF]Perspective for the clean energy transition 2019[END_REF] and the total energy imported (E import grid,k ) and exported (E injected grid,k ). Moreover, each ESS possesses sensors that transmit voltage and current measurements directly to the central EMS.

E imb,k = E pv,k -E cons,k (1)
Relying on these data measurements, the role of the EMS is to manage the BMG power flow to supply the building's energy demand using as much as possible the resources installed in the building and reducing its energy dependency on the external grid. To achieve this, in the case of surplus of energy (E imb,k > 0), the EMS has three options: produce and store hydrogen by means of electrolysis (E els ), charge the batteries (E ch bat ) or inject the surplus into the main grid (E injected grid ). Similarly, when there is an internal energy deficit (E imb,k < 0) the HMPC also has three alternatives: produce electricity through the fuel cells (E fc ), discharge the batteries (E dis bat ), or import energy from the grid (E import grid ). The proposed hierarchical EMS is divided into four control units working synchronously, namely two MPCs and two data-driven modules. The two MPCs in cascade aims at ensuring the BMG operates safely while minimising the whole system's operation costs. It aims to guarantee the internal energy balance and to respect the physical limitation of its electric components. To improve the flexibility of the MG system, the EMS adapts according to continuous data measurements thanks to the two data-driven modules. The first one is the Real-Time Model Identification (RTMI) unit for handling the imprecision of ESS modelling, whereas the second one is the MG cost estimator. In the next sections, each of these four control units will be further detailed.

Description of the hierarchical model predictive control structure

The proposed HMPC has two control levels, namely Economic MPC (EMPC) and Tracking MPC (TMPC). Formulated as EMPC, the upper control level minimises BMG operating costs by determining both the batteries' State-of-Charge references (SoC ref ) and the tank Level of Hydrogen reference (LoH ref ) to be forwarded to the lower MPC. The EMPC is also responsible for sending the day-ahead energy planning to the community aggregator. This piecewise information is essential to enable aggregators to maintain grid stability and to assure profitable grid contracts concerning local electricity prices [START_REF] Doostizadeh | A day-ahead electricity pricing model based on smart metering and demand-side management[END_REF]. Aiming to reduce computation costs, the EMPC is updated at least once a day, making it the slowest control layer in the proposed hierarchical control structure.

In parallel, a Tracking MPC (TMPC) determines batteries, electrolyser, and fuel cell power references (P Unlike EMPC, TMPC is a light control unit that has fewer constraints. Since the electricity price and the day-ahead raw net power imbalance does not change abruptly within 24 h, the high-cost computing EMPC does not need to be optimised hourly. Therefore, TMPC, which has a shorter horizon, cooperates with EMPC. This lower control layer is updated hourly and its main role is to guarantee that the boundary constraints involving the power balance and the safe operating of ESS are not violated.

It is important to highlight that both MPC control layers were modelled using linear equations to be solved through the Mixed-Integer Linear Programming (MILP) framework of CPLEX of IBM®. In the following two subsections, the main aspects of the design of EMPC and TMPC are detailed.

Design of economic model predictive control

The objective of EMPC is to guarantee the BMG operates at minimum cost. To reach this objective, EMPC minimises the estimated annual BMG expenditure over a horizon of two-days ahead (N EMPC

SoC ref , LoH ref = arg ⎛ ⎝ min SoCref ,LoHref ∑ N EMPC h =48 k=1 π grid,k + π deg els,k + π deg fc,k + π deg bat,k -π sc,k + π pen sc,k ⎞ ⎠ (2)
The EMPC has a timestamp of T EMPC s = 24h and a horizon of two-days ahead to better estimate the batteries SoC and tank LoH at the end of each day. By considering the estimated power imbalance of the current and next day, the EMPC can determine the remaining energy to be stored in ESSs to guarantee the optimal power flow not only for the current day but also for the following day.

Nonetheless, optimising the EMPC only once a day (i.e. T EMPC s = 24h) diminishes the optimality of its decisions. Therefore, to guarantee EMPC performance even subject to severe power imbalance prediction data inaccuracy throughout the day, the EMPC supervises the performance of TMPC by assessing the accuracy of SoC ref and LoH ref tracking. It compares the imported and exported energy measured at the interlinking AC-DC converter (E meas grid,k ) and those calculated by EMPC (E EMPC grid,k ). The gap between them can be due to either imprecisions in the SoC and LoH model estimation or on account of unexpected power imbalance variation. Therefore, to soften the effects of this stochasticity without increasing the computation costs too much, as soon as the absolute difference between E EMPC grid,k and E meas grid,k exceeds a predefined thresholdnamed ΔP thr grid -the EMPC determines new SoC ref and LoH ref . This reoptimisation process uses the updated prediction data, but with a reduced horizon, as illustrated in Fig. 2. The reduced horizon includes the data prediction for the period between the time where the absolute error surpasses ΔP thr grid -named t reOpt -and the end of the original horizon.

Design of tracking model predictive control

In parallel to EMPC, the TMPC determines corrective power references for batteries, fuel cells, and electrolysers to track SoC ref and LoH ref determined by EMPC. For this, TMPC optimises the cost function defined by (3) at a cadence of one hour. Considering the update data prediction coming from the community aggregator, the purpose of TMPC is to reduce the errors from both ESSs modelling and the raw power

( SoC ref ,k -ŜoC k ) 2 + 1 LoH max -LoH min ( LoH ref ,k -LoH k ) 2 ⎞ ⎠ (3)
Furthermore, TMPC constraints are softer than those of EMPC because it does not need to calculate the degradation cost of ESS and the penalisation of not attaining the self-consumption rate. However, constraints related to the safe operation of the BMG still exist. The constraints for assuring the power balance and the maximum power rate of batteries and hydrogen chain (Eqs. ( 4)- [START_REF] Argyrou | Energy storage for electricity generation and related processes: technologies appraisal and grid scale applications[END_REF], respectively) are present in both EMPC and TMPC.

E imb,k + E ch bat,k + E dis bat,k + E els,k + E fc,k + E import grid,k + E injected grid,k = 0 (4)
-P max els,k ≤ P els,k ≤ 0; 0 ≤ P fc,k ≤ P max fc,k

(5)

P min bat,k ≤ P ch bat,k ≤ 0; 0 ≤ P dis bat,k ≤ P max bat,k (6)
Likewise, the constraints for avoiding speculation with ESS are essential to be compliant with the grid code of grid-connected BMG. In France, BMGs can charge their ESSs only from renewable energy generated locally, and they can be discharged only to supply local demand. Consequently, the energy injected into the grid can only come from PV arrays and not from ESS discharging. To respect these restrictions, the constraints ( 7) and ( 8) must be embedded in both MPC layers.

-

⃒ ⃒ ⃒max ( ⃒ ⃒ P min bat ⃒ ⃒ + ⃒ ⃒ ⃒P max els,k ⃒ ⃒ ⃒, ⃒ ⃒ P surplus ⃒ ⃒ ) ⃒ ⃒ ⃒ ≤ P ch bat,k + P els,k ≤ 0 (7) 0 ≤ P dis bat,k + P fc,k ≤ ⃒ ⃒ ⃒min ( ⃒ ⃒ P max bat ⃒ ⃒ + ⃒ ⃒ ⃒P max fc,k ⃒ ⃒ ⃒, ⃒ ⃒ P deficit ⃒ ⃒ ) ⃒ ⃒ ⃒ (8)

Description of the real-time model identification module

In the literature [START_REF] Garcia-Torres | Optimal economical schedule of hydrogen-based microgrids with hybrid storage using model predictive control[END_REF], ESSs are usually modelled through a model composed of time-invariant parameters derived from the manufacturer's technical specifications. However, based on more realistic models of Liion batteries [START_REF] Tremblay | Experimental validation of a battery dynamic model for EV applications[END_REF], electrolysers [START_REF] Abdin | Modelling and simulation of a proton exchange membrane (PEM) electrolyser cell[END_REF], and fuel cells [START_REF] Njoya | A generic fuel cell model for the simulation of fuel cell vehicles[END_REF], efficiency during their charge or discharge, their nominal voltage, and other important inherent parameters change according to the intensity of the current, equipment age and temperature. Concerning batteries, voltage variation can be around 10% of nominal voltage when they are fully charged and discharged [START_REF] Li | State of health estimation for Li-Ion battery using incremental capacity analysis and Gaussian process regression[END_REF][START_REF] Li | Data-driven health estimation and lifetime prediction of lithium-ion batteries: a review[END_REF]. Moreover, at the end of their life, batteries can lose between 10% and 20% of their initial capacity [START_REF] Li | Data-driven health estimation and lifetime prediction of lithium-ion batteries: a review[END_REF].

On the other hand, regarding PEM electrolysers and fuel cells, cells overpotential is very sensitive to temperature and the level of cell degradation [START_REF] Abdin | Modelling and simulation of a proton exchange membrane (PEM) electrolyser cell[END_REF][START_REF] Njoya | A generic fuel cell model for the simulation of fuel cell vehicles[END_REF][START_REF] Buttler | Current status of water electrolysis for energy storage, grid balancing and sector coupling via power-to-gas and power-to-liquids: a review[END_REF]. The cell voltage is directly correlated to the temperature in the case of electrolysers and inversely correlated in fuelcell configuration [START_REF] Lamy | From hydrogen production by water electrolysis to its utilization in a PEM fuel cell or in a SO fuel cell: Some considerations on the energy efficiencies[END_REF]. The voltage offset in PEM technology affects round-trip efficiency, since the chemical hydrogen reaction is mainly dependent on the current flowing through the PEM cells, according to Faraday's law of electrolysis [START_REF] Buttler | Current status of water electrolysis for energy storage, grid balancing and sector coupling via power-to-gas and power-to-liquids: a review[END_REF]. Therefore, this implies a different hydrogen flows for the same amount of delivered power, depending on operating temperature and level of cell degradation. Consequently, additional uncertainties on SoC k+1 and LoH k+1 estimation arise with static-parameter models, which may result in under or overuse of ESSs.

To tackle this issue, the RTMI module was designed to maintain the accuracy of the ESS models throughout the BMG operation. For this, new reservoir-based models are proposed to estimate their remaining energy. Therefore, batteries and the hydrogen chain are modelled through linear equations linking the expected future energy stored (i.e. SoC k+1 and LoH k+1 ) to their energy supplied to the BMG (E ch bat,k , E dis bat,k , E els,k or E fc,k ), as specified in equations ( 9) and [START_REF] Lokar | The potential for integration of hydrogen for complete energy self-sufficiency in residential buildings with photovoltaic and battery storage systems[END_REF], respectively. Remarkably, f bat and f H2 are linear functions in which their parameters are updated in realtime by the RTMI module continuously, without needing an exhaustive pre-modelling step.

SoC k+1 = SoC k + f bat ( E ch bat,k , E dis bat,k ) (9
)

LoH k+1 = LoH k + f H2 ( E els,k ) -f H2 ( E fc,k ) (10)
The following two subsections detail these two linear functions and explain how the RTMI algorithm identifies their parameters in real-time. The greatest advantage of the RTMI algorithm is its non-dependency on the storage of past measurements. The knowledge of the previous measurements is stored in dynamic confidence weights. As a result, only a few sets of parameters are stored in the memory.

Real-time identification of the batteries model

The linear function f bat considers the distinct efficiency and voltage when commuting between charge and discharge of batteries [START_REF] Tremblay | Experimental validation of a battery dynamic model for EV applications[END_REF]. For this reason, the energy assigned to the battery packs was divided into four variables, named E cd,k and E dd,k when the batteries are discharged, and E dc,k and E cc,k when they are charged at time k, as specified in [START_REF] Lamy | From hydrogen production by water electrolysis to its utilization in a PEM fuel cell or in a SO fuel cell: Some considerations on the energy efficiencies[END_REF] and [START_REF] Parra | A review on the role, cost and value of hydrogen energy systems for deep decarbonisation[END_REF]. The indexes ε = {cd, dd, cc, dc} indicate the sequence of charge (c) and discharge (d), at time k -1 and k, making each of these variables dependent on the current and previous batteries states. The selection of batteries status is controlled by Mixed Logic Dynamic (MLD) constraints and binary variables, similarly to [START_REF] Garcia-Torres | Optimal economical schedule of hydrogen-based microgrids with hybrid storage using model predictive control[END_REF]. In this manner, the linear parameters θ cd,k , θ dd,k , θ cc,k and θ dc,k -named θ-parameters -are selected accordingly, following the equation ( 13).

E dis bat,k = E cd,k + E dd,k (11)
E ch bat,k = E cc,k + E dc,k (12)
f bat ( E ch bat,k , E dis bat,k ) = θ cd,k E cd,k + θ dd,k E dd,k + θ cc,k E cc,k (13)
The θ-parameters are calculated based on an interactive and realtime algorithm, as shown in Fig. 3. Synchronised with the HMPC, the RTMI module acquires a new measurement point, composed of the battery current (i) and voltage (v). To improve robustness against cell temperature (T cell ) variations, the RTMI updates the θ-parameters for a temperature range defined a priori. Without using any temperature sensor, the RTMI algorithm estimates the temperature interval using the voltage v and the integral of the current (i t ) measurements.

When a new measured point is acquired, θ meas are estimated and the Fig. 2. Re-optimisation of EMPC using the reduced horizon.

θ-parameters of a specific temperature interval are updated using the principle of a weighted average, as defined in [START_REF] Fontenot | Modeling and control of building-integrated microgrids for optimal energy managementa review[END_REF]. The term ω k corresponds to a confidence weight that indicates the reliability of the estimation of θ-parameter, whereas σ is a parameter that gives the importance of the new measurement (θ meas ) regarding the previous estimation (θ k ). The confident weight ω k grows with acquisition of new measurements and reduces over time. For further information, the entire RTMI algorithm for batteries model identification is explained in the authors' previous work [START_REF] Yamashita | Real-time parameters identification of lithium-ion batteries model to improve the hierarchical model predictive control of building microgrids[END_REF].

θ k+1 = ω k ⋅θ k + σ⋅θ meas ω k + σ (14)
After updating the θ-parameters of the current range of battery cell temperature, every day the RTMI sends to the HMPC only the θ-parameters corresponding to the most likely temperature for the next day, which is the average cell temperature of the previous day. By using MATLAB/Simulink and the SimPower-Systems library, the SoC estimation using the RTMI algorithm and this using the static model found in the literature are compared. The graphs in Fig. 4 shows that the error using the RTMI module is on average four times lower than the classic model. Remarkably, the discontinuity at every 24 h is due to the update of EMPC state variables by real measurements. The conventional model is defined by [START_REF] Nassourou | Economic model predictive control for energy dispatch of a smart micro-grid system[END_REF], where the static parameters Q nom , v nom bat , η ch and η dis are equal to 167 Ah, 700 V, 97% and 99%, respectively.

SoC k+1 = SoC k + η ch v nom bat ⋅Q nom E ch bat,k + 1 v nom bat ⋅Q nom ⋅η dis E dis bat,k (15)

Real-time identification of the hydrogen chain model

Concerning the hydrogen chain, f H2 was divided into three ranges of power, named zone1, zone2, and zone3, referring to small, medium, and large power rates. This division is necessary because, if operating outside the nominal power, the currentwhich is the image of the hydrogen flow across the cellsis non-linear with the power, as shown in Fig. 5. Faraday's law of electrolysis, defined in ( 16), links the current (i els and i fc ) and the hydrogen flowing ( ṅels H2 and ṅfc H2 ), which is constant when operating close to nominal conditions (~1A/cm 2 ). Remarkably, the index i refers to either electrolysers (els) or fuel cells (fc). In this context, a unique line to represent the tank inlet and outlet hydrogen flow, as proposed in most of the studies in the literature [START_REF] Valverde | Integration of fuel cell technologies in renewableenergy-based microgrids optimizing operational costs and durability[END_REF][START_REF] Garcia-Torres | Optimal economical schedule of hydrogen-based microgrids with hybrid storage using model predictive control[END_REF], may result in a non-accurate model.

ṅi H2 i i = N i cells ⋅A i cells 2⋅F = β i Faraday ≅ constant (16)
Faced to this issue, at each TMPC sampling time, the RTMI module acquires the tank pressure (P tank ), the current (i els and i fc ) and voltage (v els and v fc ) at fuel cells and electrolyser branches, as shown in Fig. 6. First, the tank pressure is used to estimate the current LoH k and its variation regarding the last measurement at k -1, as detailed in equations ( 17) and ( 18), respectively. The maximum pressure of the hydrogen tank (P max tank ) is specified by the manufacturer and is dependent on the tank temperature. In this paper, it was assumed that the temperature regulation of the entire hydrogen chain is perfectly controlled by ancillary services so that the electrolyser, tank, and fuel cell temperatures are constant. Consequently, according to the ideal gas law, the maximum number of moles of hydrogen stored in the tank (n max H2 ) is also assumed to be constant throughout all the simulations.

LoH k = P tank,k P max tank = n H2,k n max H2 ( 17
)
ΔLoH k = LoH k -LoH k = ΔP tank,k P max H2 ≅ T TMPC s ⋅n els,fc H2,k n max H2 ( 18
)
The current total number of moles of hydrogen stored in the tanks can be calculated based on the previous quantity and the number of 10) with ( 17), the future LoH can be estimated using [START_REF] Garcia-Torres | Optimal economical schedule of hydrogen-based microgrids with hybrid storage using model predictive control[END_REF].

LoH k+1 = P tank,k P max tank + f H2 ( E els,k ) -f H2 ( E fc,k ) [%] (19)
To identify the parameters of f H2 , at each TMPC sampling time, the RTMI implements two real-time model adjustments. The first one is to determine β els,fc Faraday , by a dynamic average of the ratio between ΔP tank,k and i els,fc . The second one consists of identifying a line for each of the three power zones (i.e. zone1, zone2 or zone3). Through a dynamic updating process between the power measurements (i els ⋅v els and i fc ⋅v fc ) and the respective current (i els and i fc ), it is possible to determine α i 1 , α i 2 , α i 3 , β i 1 and β i 2 in Fig. 5. Subsequently, the linear coefficients β i 2 and β i 3 are adjusted slightly to keep the model's continuity across the zones.

Therefore, using the constant β i Faraday in Eq. ( 16) the function f H2 is defined by [START_REF] Vivas | A suitable state-space model for renewable source-based microgrids with hydrogen as backup for the design of energy management systems[END_REF], where δ els,k and δ fc,k are Boolean variables indicating whether the electrolyser or the fuel cell is active. Remarkably, the energy assigned to electrolyser and fuel cell are also divided into three ranges, namely

E zone1 i,k , E zone2 i,k and E zone3 i,k
. The performance of the proposed linear model with the RTMI algorithm was validated using the Simulink SimPower-System fuel cell model, an electrolyser model developed by the authors based on experimental polarisation curves of [START_REF] García-Valverde | Simple PEM water electrolyser model and experimental validation[END_REF], and a hydrogen tank model based on the Beattie-Bridgeman formula [START_REF] Wang | Modelling and control of hybrid wind/photovoltaic/fuel cell distributed generation systems[END_REF]. The precision of the RTMI model and the common linear model found in the literature (Eq. ( 21) and values in Table 1) are shown in Fig. 7, where it is possible to verify that the proposed model is about ten times more accurate than the classic one.

f H2 ( E i,k ) = β i Faraday P max tank ( 1 α i 1 E zone1 i,k + 1 α i 2 E zone2 i,k + 1 α i 3 E zone3 i,k - β i 2 α i 2 δ zone2 i,k - β i 3 α i 3 δ zone3 i,k ) (20)
LOH k+1 = LOH k + E els,k ς els ⋅V tank ⋅1000 - ς fc ⋅E fc,k V tank ⋅1000 (21)

Description of the microgrid cost estimator module

The MG cost estimator is an adjunct module in the hierarchical control structure that interacts with the EMPC directly. Its main objective is to determine the most suitable parameters of the EMPC cost function that increase the likelihood of the BMG to attain the required marks of the annual self-consumption rate at minimum cost.

By analysing both the day-ahead and the previous year's power imbalance prediction data, it estimates the average behaviour of the hierarchical EMS when it is subjected to similar conditions of daily power imbalance and calculates the expected annual BMG cost and the expected annual self-consumption rate. The expected annual BMG cost defines the EMPC cost function that is minimised daily, whereas the expected annual self-consumption rate is embedded into EMPC formulation through an inequality constraint, forcing it to be higher than the required marks imposed by the grid regulator. To explain the main functioning of the MG cost estimator, the expected annual BMG cost is detailed in Section 5.1, whereas the algorithm to calculate the expected annual self-consumption rate is explained in Section 5.3.

Estimation of the expected annual building microgrid cost

The annual BMG cost is estimated daily and embedded into the six π-cost terms which make up the EMPC cost function defined by Eq. ( 2), namely π grid , π deg els , π deg fc , π deg bat , π sc and π pen sc . The next four subsections explain in detail how these π-costs are determined.

Cost of electricity

The term π grid refers to the annual electricity cost and it is estimated from both the electricity price and the total energy deficit of the previous year. Since the energy deficit (E deficit,k ), defined by [START_REF] Tremblay | Experimental validation of a battery dynamic model for EV applications[END_REF], can be covered either by purchasing electricity from the grid or discharging the ESS, the total energy imported can be calculated from [START_REF] Abdin | Modelling and simulation of a proton exchange membrane (PEM) electrolyser cell[END_REF], and the estimated annual electricity cost from [START_REF] Njoya | A generic fuel cell model for the simulation of fuel cell vehicles[END_REF]. Since E deficit,k is an uncontrollable variable from the point of view of EMPC, the minimisation of ( 24) can be ensured by periodic minimisations of ( 25) over the overlap periods of EMPC horizon.

E deficit,k = { E imb,k ⟺E imb,k < 0 0⟺E imb,k ≥ 0 (22) E import grid,k = E deficit,k - ⃒ ⃒ E fc,k ⃒ ⃒ - ⃒ ⃒ ⃒E dis bat,k ⃒ ⃒ ⃒ ( 23
)
π annual grid = ∑ 365 k=1 π elec,k ( E deficit,k - ⃒ ⃒ E fc,k ⃒ ⃒ - ⃒ ⃒ ⃒E dis bat,k ⃒ ⃒ ⃒ ) (24)
π grid,k = π elec,k

( - ⃒ ⃒ E fc,k ⃒ ⃒ - ⃒ ⃒ ⃒E dis bat,k ⃒ ⃒ ⃒ ) (25)

Cost due to the degradation of the energy storage device

The cost due to the degradation of ESS includes π deg bat , π deg els and π deg fc , referring to the deterioration cost of batteries, fuel cells, and electrolysers, respectively. From experimental curves provided by manufacturers, the ESS degradation level can be estimated. In the case of batteries, the loss of nominal capacity, which follows an exponential trend depending on the number of cycles and the depth of discharge [START_REF] Omar | Lithium iron phosphate based batteryassessment of the aging parameters and development of cycle life model[END_REF], can be used to measure their degradation level. Concerning PEM electrolysers and PEM fuel cells, the voltage offset is used for assessing their EoL [START_REF] Rakousky | Polymer electrolyte membrane water electrolysis: Restraining degradation in the presence of fluctuating power[END_REF]. However, the approximation given by technical specifications is usually a non-linear function that can differ from the real degradation rate. Therefore, this complicates the design of linear models and introduces undesirable errors into the estimation of the EoL of ESSs.

To deal with this problem, the authors of [START_REF] Cardoso | Battery aging in multi-energy microgrid design using mixed integer linear programming[END_REF] and [START_REF] Vivas | A suitable state-space model for renewable source-based microgrids with hydrogen as backup for the design of energy management systems[END_REF] proposed linear models based on expected values. Particularly, in [START_REF] Vivas | A suitable state-space model for renewable source-based microgrids with hydrogen as backup for the design of energy management systems[END_REF], the degradation is estimated through the expected capacity loss in the case of batteries, and the expected degradation in fuel cells and electrolysers based on a factor proportional to their operating power. Nonetheless, these linear models are still dependent on static parameters that need to be manually assigned.

To overcome this dependency on reliable technical specifications, in this paper, similar linear models proposed in [START_REF] Vivas | A suitable state-space model for renewable source-based microgrids with hydrogen as backup for the design of energy management systems[END_REF] were implemented and updated daily based on real-time measurements. The battery maximum capacity is estimated daily from the non-linear model existent in the Simulink® SimPower-Systems library. However, in real applications, this estimation can be implemented through data-driven algorithms such as those reviewed in [START_REF] Li | State of health estimation for Li-Ion battery using incremental capacity analysis and Gaussian process regression[END_REF][START_REF] Li | Data-driven health estimation and lifetime prediction of lithium-ion batteries: a review[END_REF], in which the real capacity can be evaluated from voltage and current measurements.

It is therefore possible to linearly correlate batteries power to their loss of capacity, named ΔQ bat . For this, the ratio d bat,k linking the energy used for charging and discharging the batteries to its respective ΔQ bat,k can be calculated daily, through equations ( 26) and [START_REF] Buttler | Current status of water electrolysis for energy storage, grid balancing and sector coupling via power-to-gas and power-to-liquids: a review[END_REF]. Calculated as explained in Appendix I, the dynamic average d bat,k of all past measured d bat,k determines the model of batteries degradation. The graph in Fig. 8 shows the dynamic average and the complete linear regression of these measurements d bat,k , after a one-year simulation in MATLAB Simulink®. Contrary to complete linear regression, the dynamic average algorithm updates d bat,k as soon as a new ΔQ bat is acquired, thus avoiding the storage of past measurements. Comparing the final linear approximations, the dynamic average algorithm d bat,k represents a fair approximation of the complete linear regression.

ΔQ bat,k = ⃒ ⃒ Q bat,k -Q bat,k+24 ⃒ ⃒ ( 26
)
d bat,k = ΔQ bat,k ∑ k+24 k |E ch bat,k |+ ⃒ ⃒ ⃒E dis bat,k ⃒ ⃒ ⃒ (27)
Therefore, given that it is recommended to replace battery packs when they lose 20% of their initial capacity (Q bat ), the cost of using the batteries in the current day can be expressed as in [START_REF] Yamashita | Real-time parameters identification of lithium-ion batteries model to improve the hierarchical model predictive control of building microgrids[END_REF], where C bat is the capital cost of batteries in €.

π deg bat,k = d bat,k ⋅ ( E ch bat,k + E dis bat,k ) 0.2⋅Q bat ⋅C bat (28)
Analogously, the degradation cost of PEM electrolysers and PEM fuel cells is estimated from the voltage offset after operating them. According to [START_REF] Parra | A review on the role, cost and value of hydrogen energy systems for deep decarbonisation[END_REF], the degradation rate in electrolysers and fuel cells is around 3 μV h for each cell at nominal operation, which corresponds to approximately 20 years of lifespan. Generally, fuel cells and electrolysers must be replaced when they lost 10% of their efficiency, which represents 10% of voltage offset for the same operating conditions [START_REF] Buttler | Current status of water electrolysis for energy storage, grid balancing and sector coupling via power-to-gas and power-to-liquids: a review[END_REF]. Therefore, at the end of each day, voltage degradation is correlated to the total energy required for that day, by calculating the ratio d i , given by ( 29) and [START_REF] Wang | Modelling and control of hybrid wind/photovoltaic/fuel cell distributed generation systems[END_REF]. The index i refers to either the fuel cells or the electrolysers. Since the Simulink® fuel cell model does not consider voltage degradation, this phenomenon was modelled based on [START_REF] Rakousky | Polymer electrolyte membrane water electrolysis: Restraining degradation in the presence of fluctuating power[END_REF], in which it was concluded through experimental tests that the voltage drop is more intense when operating them for long periods and with a current density over 1 A/ cm 2 . Fig. 9 shows the voltage offset for electrolysers and fuel cells modelled in Simulink that is in accordance with the results obtained in [START_REF] Rakousky | Polymer electrolyte membrane water electrolysis: Restraining degradation in the presence of fluctuating power[END_REF].

Δv i,k = ⃒ ⃒ v i,k -v i,k+24 ⃒ ⃒ ( 29
)
d i = Δv i,k ∑ k+24 k |E i | (30)
The dynamic average d i over all previous measured d i enables to estimate the EoL of electrolysers and fuel cells, as shown in Fig. 10. When the offset voltage attains 10% of the initial voltage v init i (i.e. without any degradation), PEM fuel cells and electrolysers are totally degraded and must be replaced. Therefore, using Eq. ( 31), the degradation cost of fuel cells or electrolysers during EMPC horizons can be defined as a proportion of their capital cost in € (C fc or C els ).

π deg i,k = d i,k ⋅E i 0.1⋅v init i ⋅C i (31)

Grid reward for self-consuming electricity

Although the grid code for individual prosumers is still being developed, some financial incentives have already been established. Particularly, the French Energy Regulation Commission (ERC) limits the total energy injection in BMGs with capacity over or equals to 100 kWc by imposing required marks of the self-consumption rate at the end of the year [START_REF]la réalisation et l'exploitation d'Installations de production d'électricité à partir d'énergies renouvelables en autoconsommation et situées en métropole continentale[END_REF]. The annual self-consumption rate (τ annual sc ) measures the percentage of renewable energy that is produced and consumed locally. As expressed in [START_REF] Cardoso | Battery aging in multi-energy microgrid design using mixed integer linear programming[END_REF], the self-consumed energy (E sc ) is equal to the difference between the energy generated by the PV panels (E pv,k ) and the energy injected (E injected grid,k ). Deducted from the power balance in Eq. ( 4), E injected grid,k corresponds to the part of the surplus (E surplus,k ) that was not stored in the ESS. It can be estimated by using [START_REF]la réalisation et l'exploitation d'Installations de production d'électricité à partir d'énergies renouvelables en autoconsommation et situées en métropole continentale[END_REF], where E surplus,k is calculated by [START_REF] Celebi | Partitional Clustering Algorithms[END_REF]. Consequently, τ annual sc is the ratio calculated in [START_REF]JRC Photovoltaic Geographical Information System (PVGIS) -European Commission[END_REF].

E sc,k = E pv,k -E injected grid,k (32) E injected grid,k = E surplus,k - ⃒ ⃒ E els,k ⃒ ⃒ - ⃒ ⃒ ⃒E ch bat,k ⃒ ⃒ ⃒ ( 33
)
E surplus,k = { E imb,k ⟺E imb,k > 0 0⟺E imb,k ≤ 0 (34) τ annual sc = ∑ 365 k=1 E sc,k ∑ 365 k=1 E pv,k = ∑ 365 k=1 E pv,k -E surplus,k + ⃒ ⃒ E els,k ⃒ ⃒ + ⃒ ⃒ ⃒E ch bat,k ⃒ ⃒ ⃒ ∑ 365 k=1 E pv,k (35)
To financially encourage self-consumption beyond the minimum threshold imposed by ERC, a reward mechanism has been established, in which internal load matching is favoured, and injection is penalised. The additional income [START_REF]la réalisation et l'exploitation d'Installations de production d'électricité à partir d'énergies renouvelables en autoconsommation et situées en métropole continentale[END_REF] for the annual energy self-consumed is Fig. 8. Linear regression vs dynamic average approximations of the daily capacity loss of batteries. calculated according to [START_REF] Bendib | A survey of the most used MPPT methods: conventional and advanced algorithms applied for photovoltaic systems[END_REF], which is dependent on both the value of the premium P in €/MWh and the PV installed capacity P inst pv . In the BMG being studied, P is worth 20 €/MWh and P inst pv is equal to 100 kWc. Moreover, the BMG revenue is penalised according to the maximum power injected in a year (P maxInjected ). This encourages BMGs to inject constant and low power rate to relieve the unpredictability of energy management among neighbouring BMGs.

π annual sc = 10 -6 ⋅ ( ∑ 365 k=1 (P + 5)⋅E sc,k + P⋅E injected grid,k -12⋅E pv,k ⋅ P maxInjected P inst pv ) (36)
By combining ( 32)- [START_REF] Bendib | A survey of the most used MPPT methods: conventional and advanced algorithms applied for photovoltaic systems[END_REF], maximisation of the bonus for selfconsuming electricity (π annual sc ) can be guaranteed by periodic optimisations of Eq. ( 37) within the EMPC horizon. The complete reasoning for deducting [START_REF] Lee | Electricity demand profile of Australian low energy houses[END_REF] is explained in Appendix II.

π sc,k = 5⋅10 -6 ⋅ ( ⃒ ⃒ E els,k ⃒ ⃒ + ⃒ ⃒ ⃒E ch bat,k ⃒ ⃒ ⃒ ) -12⋅10 -6 ⋅ ∑ 365 i=1 E pv,i P maxInjected,k=N EMPC h P inst pv (37)

Grid penalisation for not attaining the marks of self-consumption

The French ERC requires a predefined mark of self-consumption (τ required sc ) at the end of the year, which limits BMGs to injecting energy into the grid according to their annual energy consumption and annual PV energy generation. To force BMGs to respect this restriction, the premium P in Eq. ( 36) is reduced by 2% per percentage point of the gap between the expected marks of self-consumption and the real one attained by the BMG [START_REF]la réalisation et l'exploitation d'Installations de production d'électricité à partir d'énergies renouvelables en autoconsommation et situées en métropole continentale[END_REF]. For instance, if the required mark is τ required sc = 80% and the BMG attained only 70%, the premium P in the next year will be reduced by 2 × (80% -70%) = 20%.

To avoid this grid penalisation and ensure BMG profitability for the upcoming years, the objective function and constraints of EMPC were designed to force the expected annual self-consumption rate to be greater than τ required sc . Therefore, if expected self-consumption is bellow τ required sc , the BMG has to virtually pay for the ESSs capital cost and the annual electricity bill of the expected annual deficit using the maximum electricity price for previous years. Consequently, formulated as in [START_REF] Yu | An integrated and reconfigurable hybrid AC/DC microgrid architecture with autonomous power flow control for nearly/net zero energy buildings[END_REF], π pen sc,k was designed to force the BMG to attain τ required sc in all circumstances.

The variable δ sc,k is a Boolean variable that is worth 0 when the BMG is likely to attain the τ required sc and worth 1 in the opposite case. This logic is expressed in (39), where τannual sc is the expected annual self-consumption rate that will be explained in the next section.

π pen sc,k = ( C bat + C fc + C els + max ( π elec,k=[1,365] ) ⋅ ∑ 365 i=1 P deficit,i ) ⋅δ sc,k (38)
δ sc,k = { 1, if τannual sc ≥ τ required sc 0, otherwise (39)

Estimation of the expected annual self-consumption rate

Aiming to operate the BMG at minimum cost, but at the same time guarantee the required annual marks of self-consumption imposed by French grid operators, the MG cost estimator calculates the expected annual self-consumption rate (τ annual sc ) using both the prediction data for the previous year and the average behaviour of HMPC. Therefore, the estimation process contains three main steps. Firstly, the previous year prediction data are classified into four classes using the k-means algorithm. Secondly, the average of HMPC control variables is assigned to each k-means class, and the expected annual self-consumption rate is calculated using this average and the results from k-means classification.

Finally, τannual sc is integrated into the two-days ahead horizon of EMPC. The following subsections detail these three steps.

Classification of prediction data using k-means algorithm

The k-means algorithm aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean called centroid [START_REF] Celebi | Partitional Clustering Algorithms[END_REF]. In this paper, k-means algorithm is used to classifies the annual data prediction of PV power generation and the building's power consumption into four classes, representing the four seasons. These classes distinguish the annual dataset concerning the five normalised features retrieved from the daily prediction data, named x 1 ,x 2 , x 3 , x 4 and x 5 , as illustrated in Fig. 11. Therefore, based on the raw net power imbalance, each day is assigned to one class among k = {1, 2, 3, 4}. Therefore, by definition, each class contains n k = {n 1 , n 2 , n 3 , n 4 } observations, where n 1 + n 2 + n 3 + n 4 = 365days.

Fig. 12 shows the layout of these five features of the dataset for a public building after k-means classification, in which the black points are the four centroids. Fig. 13 shows that daily profiles that share a similar portion of data are grouped into distinct k-means classes.

To enhance precision over time, k-means classification is implemented once a day at midnight using updated data. For this, the data prediction of the current day replaces the data prediction of the corresponding day in the last year, as shown in Fig. 14. Therefore, the accuracy of the classification is enhanced when approaching the end of the year.

Estimation average HMPC behaviour

According to Eq. ( 35), the self-consumption rate depends on the annual E pv,k , E surplus,k , E els,k and E ch bat,k . Consequently, it is possible to estimate τannual sc by using Eq. ( 40), where, Êpv , Êsurplus , Êels , Êch bat are the estimated values of annual E pv , E surplus , E els and E ch bat , respectively.

τannual sc = 1 - Êsurplus - ⃒ ⃒ ⃒ Êch bat ⃒ ⃒ ⃒ - ⃒ ⃒ ⃒ Êels ⃒ ⃒ ⃒ Êpv (40)
Considering that the current day is the day D, then Êpv and Êsurplus can be calculated by combining prediction data for the previous year and those of the current year, using Eqs. ( 41) and [START_REF] Dualsun | Warrant terms of photovoltaic panels of Dualsun[END_REF]. Therefore, the estimation of Êpv and Êsurplus is continuously enhanced by the replacement process described in Fig. 14.

Êpv = ∑ 365 k=1 E pv,k = ∑ D-1 k=1 E this year pv,k + ∑ 365 k=D E last year pv,k (41)
Êsurplus = ∑ 365 k=1 E surplus,k = ∑ D-1 k=1 E this year surplus,k + ∑ 365 k=D E last year surplus,k (42)
Likewise, Êels and Êch bat can be estimated through Eqs. ( 43) and (44), respectively. Remarkably, E els,k and E ch bat,k for previous period [1; D -1] are measured variables since they are collected by sensors in the electrolysers and batteries DC-DC power converters. On the other hand, the outcome of k-means classification is used for calculating the expected values concerning the future partition of Êels and Êch bat (i.e. those corresponding to future periods [D; 365]). Based on the hypothesis that the HMPC will determine similar control variables when subjected to similar conditions of raw net energy, the classified expected value of the daily energy assigned to batteries and electrolysis reflects a fair approximation for calculating Êch bat and Êels .

Êels = ∑ 365 k=1 E els,k = ∑ D-1 k=1 E els,k + ∑ 365 k=D E els,k (43)
Êch bat = ∑ 365 k=1 E ch bat,k = ∑ D-1 k=1 E ch bat,k + ∑ 365 k=D E ch bat,k (44)
In other words, given that the current day D belongs to the k-means class k (i.e. c k = k), then it is likely that the batteries will be charged

ch bat|k = E ( ∑ 24 i=1 E ch bat,i ⃒ ⃒ ⃒ ⃒ ⃒ c k = k ) (45) Êch bat = ∑ 365 i=1 E ch bat,i = ∑ D-1 i=1 E ch bat,i + ∑ 4 k=1 ( n future k ⋅E ( ∑ 24 i=1 E ch bat,i ⃒ ⃒ ⃒ ⃒ ⃒ c k = k ) ) (46)
Êels = ∑ D-1 i=1 E els,i + ∑ 4 k=1 ( n future k ⋅E ( ∑ 365 i=D E els,i ⃒ ⃒ ⃒ ⃒ ⃒ c k = k ) ) (47)
The estimation of n future k is calculated from the total number of observations n k of a given class k ∈ {1, 2, 3, 4} and the total number of observations in the past n past k , as expressed in (48). Fig. 15 summarises the process for estimating the expected annual self-consumption.

n k = n past k + n future k , ∀k ∈ {1, 2, 3, 4} (48)

Integration of the annual expected self-consumption rate into the EMPC formulation

To integrate τannual sc into the EMPC optimisation process, Eq. ( 40) is adapted to be compliant with the two-day-ahead horizon of EMPC. By combining (46) with (48) and considering that the current day (day D) belongs to the class k today and the following day (day D + 1) belongs to the class k tomorrow , the expected energy used for charging batteries over a year can be calculated using (49).

(49) Since the EMPC includes only days D and D + 1 (i.e. today and tomorrow), the actions of EMPC will impact only the third and the fourth terms of the Eq. ( 49), whereas the first and the second terms are constant from the perspective of EMPC. For simplicity, these constant terms are named as α const sc-bat for batteries and α const sc-els for electrolysers. Therefore, the expected τannual sc within the EMPC horizon ranging from 1 to 48 h is formulated as the inequality constraint (50).

τannual sc = β const sc + β today⋅ sc ( ∑ 24 i=1 ( E ch bat,i + E els,i ) ) + β tomorrow sc ⋅ ( ∑ 48 i=25 ( E ch bat,i + E els,i
) )

≥ τ required

β const sc = 1 - ∑ 365 k=1 E surplus,k -α const sc-bat -α const sc-els ∑ 365 k=1 E pv,k (51)
β today sc = n today ∑ 365 k=1 E pv,k (52) β tomorrow sc = n tomorrow ∑ 365 k=1 E pv,k (53)

Results and discussions

The primary objective of the designed EMS is to guarantee at minimal expenditure the self-consumption rate above 80% (τ required sc = 80% of Eq. ( 50)) of a BMG of sizing of Table 1. To evaluate the performance of the HMPC empowered with the MG cost estimator and RTMI module, it was compared to a conventional HMPC and a traditional rule-based strategy. For the sake of clarity, these three controllers are abbreviated as HMPC-kmeans, HMPC and RB, respectively. In Section 6.1, the input parameters and the conditions of simulation tests are explained. Thereafter, in Section 6.2, HMPC and RB control strategies are detailed. Afterward, the metrics for comparing and the simulating cases are presented in paragraph 6.3. Finally, the comparison of the three control strategies is discussed in Section 6.4.

The input parameters and conditions of simulation tests

The building's hierarchical EMS receives hourly from the community aggregator the prediction data for the next 48 h concerning PV power generation, the building's power consumption, and the ongoing electricity price. These data are streaming vectors with a resolution of one hour. With a view to comparing the three power flow control strategies, one-hour resolution was set up as a compromise between computation burden and accuracy. However, in real applications, the prediction data resolution may be smaller than 1 h, which will require the preprocessing of raw prediction data to conceive reliable one-hour resolution data for the HMPC. The robustness of the control strategies against inaccuracies in the data prediction is further discussed in Section 6.4.4. Additionally, with the increased prediction data resolution, TMPC and RTMI update times must be faster than one hour to compensate for fast power imbalance variability. This will also require the inclusion of filters and pre-processing of data measurements, such as moving average or finite impulse response filters.

PV power generation was modelled using real profiles of solar irradiation and temperature in the town of Bidart, where the future BMG will be placed. These meteorological data were procured from the Joint Research Centre platform for photovoltaic geographical study [START_REF]JRC Photovoltaic Geographical Information System (PVGIS) -European Commission[END_REF] and passed through a PV mathematical model that was driven by an incremental conductance maximum-power-tracking algorithm [START_REF] Bendib | A survey of the most used MPPT methods: conventional and advanced algorithms applied for photovoltaic systems[END_REF] to retrieve the estimated power generated over an entire year. Fig. 16 shows the data that was used both in the Simulink model emulating the real power plant and in MPC prediction data.

Similarly, the building's power consumption prediction data emulates the power consumption of a medium-sized building. Since the objective of this paper is to design a generic EMS for any type of building, the power consumption subject to study mimics the behaviour of a non-residential (i.e. public) and a residential building. The power consumption profile of a public building was estimated based on an existent building of ESTIA Institute of Technology, whereas the data of a common residential building was scaled from [START_REF] Lee | Electricity demand profile of Australian low energy houses[END_REF]. Remarkably, in both cases, building demand is about 25% more elevated during the winter than in summer days due to heating devices. Moreover, weekends and holidays were considered when designing the non-residential dataset, whereas only weekends were taken into account for the residential one, as shown in Fig. 17.

To interconnect the MG with the main electric grid, the power de-mand is indirectly controlled through a demand response signal mechanism from the community grid aggregator [START_REF] Lüth | Local electricity market designs for peer-to-peer trading: the role of battery flexibility[END_REF]. Consequently, the ongoing electricity price is sent to the building's central controller to reduce power consumption during peak hours. Consequently, the electricity price from 7 AM to 8 PM is about 30% more expensive than offpeak periods. In this manner, purchasing electricity is more expensive when most of the neighbouring BMGs have surplus energy to foster selfconsumption.

The conventional hierarchical model predictive controller and the rule-based controller

Since the objective is to demonstrate the capabilities and effectiveness of a feasible strategy to consider both energy and economic aspects in the optimisation of the BMG power flow without needing to tune any parameter in the HMPC cost function, the HMPC and RB were designed to only maximise the self-consumption rate, which is the utmost objective of the building EMS. The RB consists of a set of if-else logic that can be easily applied in real systems. This controller serves as a basis to identify whether the proposed controller performs better than a rudimentary controller. On the other hand, the HMPC, which is the previous version of the authors' work [START_REF] Yamashita | Real-time parameters identification of lithium-ion batteries model to improve the hierarchical model predictive control of building microgrids[END_REF], is a smarter control structure that takes its decisions based on prediction data but it optimises only the BMG's energy aspects and ignores economic ones. The comparison with HMPC aims to verify whether it is important to consider both economic and energetic aspects when optimising the power flow. Furthermore, it would allow evaluating whether the MG cost estimator does reduce the BMG operation cost or not.

In this regard, the HMPC architecture is the same as the HMPCkmeans except for the fact that it only contains the RTMI module and the two MPC layers. Therefore, the HMPC does not include the MG cost estimator module as HMPC-kmeans does, which leads its EMPC to be designed differently: it penalises any grid energy exchange, as expressed in Eq. ( 54). In this formulation, instead of considering the ESS capital costs, ESS efficiency, electricity price, and self-consumption additional income, the HMPC decides between batteries and hydrogen storage based only on their electric efficiency that is embedded in the internal ESS models.

SoC ref , LoH ref = arg ⎛ ⎝ min SoCref ,LoHref ∑ N EMPC h =48 k=1 ⃒ ⃒ ⃒E import grid,k ⃒ ⃒ ⃒ + ⃒ ⃒ ⃒E injected grid,k ⃒ ⃒ ⃒ ⎞ ⎠ (54)
On the other hand, the RB strategy was adapted from [START_REF] Yu | An integrated and reconfigurable hybrid AC/DC microgrid architecture with autonomous power flow control for nearly/net zero energy buildings[END_REF], in which the use of batteries is prioritised over fuel cells and electrolysers. The use of batteries is favoured over the use of hydrogen storage because the current capital cost of fuel cells and electrolysers is much higher, and their efficiency is much lower than batteries. In the RB strategy, the hydrogen ESS is controlled using the principle of hysteresis, as detailed in Fig. 18.

The metrics for comparison and overview of the simulation cases

Through one-year simulations in MATLAB Simulink®, the economic and energy outcomes of public and residential BMGs are evaluated to assess four important aspects:

• the impact of ESS installation • the impact of hydrogen ESS capital costs • the impact of constraining the use of hydrogen ESS at a nominal power rate • the impact of power imbalance prediction data error To evaluate these four aspects, seven metrics were created, namely, the annual self-consumption rate (M 1 ), the total MG cost (M 2 ), the degradation cost of batteries (M 3 ), electrolyser (M 4 ) and fuel cells (M 5 ), the cost of purchasing electricity (M 6 ), and the additional income for self-consumption (M 7 ). The equations used for calculating these metrics are summarised in Table 2, with the related equations that were discussed previously.

The performance of the HMPC and HMPC-kmeans will be compared with the RB strategy by using the relative difference defined by (55). Therefore, each of the seven metrics (M 1 to M 7 ) of HMPC and HMPCkmeans will be presented as a relative percentage of RB metrics presented in Table 4 for a public building and Table 5 for a residential building. The degradation cost of batteries (M 3 ), electrolysers (M 4 ) and fuel cells (M 5 ) was calculated using the current capital costs (C bat , C els and C fc ) presented in Table 3.

relative difference(%)

= 100

M HMPC i -M RB i M RB i , ∀i ∈ [1; 7] (55)

Comparison between RB, HMPC, and HMPC-kmeans

The following four subsections detail the impact of the four aspects on the BMG's overall performance when using RB, HMPC, or HMPCkmeans. By using the seven metrics presented in Section 6.3, the three control strategies will be compared to determine an affordable and durable BMG operation.

Impact of installing energy storage system

Due to the disposal of the power consumption profile, selfconsumption in residential buildings is strictly inferior to public buildings in all scenarios shown in Table 4 and Table 5. Observing Fig. 16 and Fig. 17, residential buildings have a peak of consumption when the PV arrays do not generate any power and almost does not consume energy when PV panels are generating. Controversially, by analysing Fig. 16 and Fig. 17, the power consumption in public buildings almost superposes the solar irradiation profiles. Consequently, without ESS, in residential buildings, only 47% of the energy generated by PVs are consumed locally, compared to almost 70% in public buildings. This also highlights the role of ESS installation, in which self-consumption is drastically increased in residential buildings, while in public buildings the role of ESS is less relevant.

According to RB results in Table 4 and Table 5, the BMG's first year of operation with only batteries is more expensive than the scenario without ESS. This is due to the additional cost created by the degradation of batteries, which represents about 12% of total MG expenditure. Nonetheless, without ESS, the BMG cannot guarantee the minimum mark of self-consumption of τ required sc = 80%. Consequently, despite being less expensive in the first year, the BMG without ESS will suffer more severe grid penalisation in the long term.

To evaluate the impact of the installation of ESS in the BMG revenue in the long term, it was estimated the total savings brought by batteries and hydrogen ESS for the next 25 years. The savings in the year y are calculated using Eq. ( 56) for batteries and Eq. (57) for hybrid ESS. In these formulations, the total savings of ESS installation correspond to the differences in the electricity bill (metric M 6 ), in the additional income for self-consumption (metric M 7 ) and the Operation and Maintenance (O&M) cost of batteries (O&M bat ), fuel cells (O&M fc ) and electrolysers (O&M fc ). In this study, it is considered that O&M bat is equal to 1200 €/year (i.e. 0.10 €/year/kWh installed), while O&M fc is equal to 0.26 €/kWh (i.e. 0.013 €/kW/kW installed) [39] and O&M els is equal to 0€/kWh. Remarkably, O&M els is equal to zero because it is already counted in the electricity consumption to generate hydrogen and to turn on the gas compressor [START_REF] Glenk | Economics of converting renewable power to hydrogen[END_REF] and its maintenance is already embedded in O&M fc .

In this analysis, it is considered that the premium factor P equals 20

€/MWh in the first year and it is reduced by 2 × ( τ required sc -M 1 ) % p.a.

[33], if M 1 < τ required sc . Furthermore, it assumes that the electricity price doubles every 10 years [START_REF] Panos | The future developments of the electricity prices in view of the implementation of the Paris Agreements: Will the current trends prevail, or a reversal is ahead?[END_REF] and that the PV panels lose 10% of their efficiency over 10 years [START_REF] Dualsun | Warrant terms of photovoltaic panels of Dualsun[END_REF]. On the other hand, it is considered that the building energy consumption for the next 25 years is the same as the first year. This is reasonable because, according to [START_REF]Perspective for the clean energy transition 2019[END_REF], the building energy consumption per square meter will be reduced in the future due to buildings envelope's refurbishment and improvement in electric appliance efficiency. Consequently, considering that the building's infrastructure will be the same for the next years, the annual building energy consumption can be assumed to be the same throughout the upcoming years. Despite these assumptions, this analysis satisfies the objective of assessing the relative capabilities of the EMS algorithms in managing the BMG power flow under different conditions. Based on these assumptions, the cumulative savings brought by the ESS installation minus its investment cost are shown in Fig. 19. All curves in Fig. 19 starts at negative values corresponding to the purchase cost of ESS. Therefore, it starts with -C bat in the case where only batteries are installed, and with -C hybrid = -C bat -C fc -C els in the case where hybrid ESS are installed. Since all curves in the case where only batteries are installed cross the abscissa axis, the batteries installation is more profitable than not installing them within the horizon of 25 years. On the other hand, the investment in the installation of hybrid ESS is not compensate within 25 years, since the red curves do not cross the abscissa axis, even though the hydrogen ESS savings are higher than the case without ESS. It is possible that within a longer horizon, the hybrid ESS investment may be paid back, but this is not the focus of this study. The savings from batteries and hydrogen ESS installation come mainly from the reduction in the electricity bill and the increase in the additional income for self-consumption, as detailed in Fig. 20.

The results in Table 4 and Table 5 demonstrate that hybrid ESS has the potential to be more profitable in the first year of BMG operation

Table 2

Metrics for comparing the performance of controllers.

Annual metrics

Equation Related equation

M1-Self-consumption rate [%] 1 - ∑ 365 k=1 E injected,k ∑ 365 k=1 E pv,k (35)

M2-Total MG cost [€]

π annual bat + π annual els + π annual fc + π annual grid -π annual sc (2) M3-Batteries cost (π annual bat ) [€] C bat ⃒ ⃒ Q bat,365 -Q bat,0 ⃒ ⃒ 0.2⋅Q bat,0 (28)
M4-Electrolyser cost (π annual els

) [€] C els ⃒ ⃒ v els,365 -v els,0 ⃒ ⃒ 0.1⋅v els,0 (31)
M5-Fuel cells cost (π annual f c

) [€] C fc ⃒ ⃒ v fc,365 -v fc,0 ⃒ ⃒ 0.1⋅v fc,0 (31)
M6-Electricity cost (π annual grid ) [€] ∑ 365 k=1 π elec,k ⋅E import grid,k (24)
M7-Additional income (π annual sc with simple controllers as RB, if its capital cost is reduced (decrease M 4 and M 5 ). Hydrogen ESS can decrease the expenses with electricity (metric M 6 ) and increase the additional income due to self-consumption (metric M 7 ). However, its current capital cost and O&M is too high to make its installation worthwhile without financial incentives such as the self-consumption additional income (e.g. without penalization of P factor). Considering that the high hydrogen ESS capital cost is the main challenge for their application, in Section 6.4.2, a suitable hydrogen ESS capital cost that would make its installation advantageous from the first year of BMG operating will be investigated.

) [€] 5⋅10 -6 ⋅ ( ∑ 365 k=1 (P + 5)⋅E sc,k + P⋅E injected grid,k -12⋅E pv,k ⋅ P maxInjected P inst pv ) (36)
The results with the RB controller indicate that BMG profitability is sensitive to the profile of energy consumption and may change with different ESS sizing. This highlights the need for a flexible EMS capable of adapting to many different situations, without demanding exhaustive tests. In this regard, the HMPC and HMPC-kmeans were designed and compared to the RB results.

To compare the performance of HMPC-kmeans and HMPC to RB, the seven metrics were evaluated by calculating their relative differences (Eq. ( 55)). These results are shown in Fig. 21 Regarding the results of Fig. 23 where only batteries are installed, both HMPC and HMPC-kmeans have a higher self-consumption rate than RB. Particularly, both HMPC and HMPC-kmeans achieved similar annual self-consumption rates in the public building (around 1.04 × 79.7 ≅ 83%) and the residential building (around 1.10 × 62.2 ≅ 68%)), but HMPC-kmeans guarantees cheaper BMG operating cost. Compared to HMPC, HMPC-kmeans can save (5-3.8) 100 × 11819 ≅ 142 € in public buildings and (5.5-4.5) 100 × 20888 ≅ 209 € in residential buildings in the first year of operating. In the long term, the graphs in Fig. 19 show that the cumulative savings of HMPC-kmeans are very similar to HMPC in public buildings, which are higher than RB: about 10 k€ on the horizon of 15 years. These savings come especially from the reduction in electricity purchase in the case of public buildings (Fig. 20b2) and both electricity expenses and the additional income in the case of residential buildings (Fig. 20a1 and Fig. 20a2). Since neither RB, nor HMPC, nor HMPC-kmeans attained τ required sc with only batteries in the residential building, the additional income gradually reduces up to the value of the case without ESS, making the graphs in Fig. 20a2 tend to zero. Therefore, after 15 years, the main savings come from only the reduction of the electricity bill, as shown in Fig. 20a1.

According to Fig. 22, with hybrid ESS the HMPC-kmeans in the public building reduces by about 9% the total MG cost (metric M 2 ) compared to the simple RB in the first year. Despite degrading the annual self-consumption by 10%, it could maintain the self-consumption rate above τ required sc , since -10% = M HMPCkmeans 1 ≥ τ 80% sc = -14%. As consequence, the factor P is not penalised in the long term. However, the additional income when using HMPC-kmeans is smaller than using RB or HMPC (Fig. 20b2). The same behaviour happens in the residential building, where the self-consumption was kept around 82% > τ required sc and the additional income is lower than RB and HMPC. Hence, the savings when using HMPC-kmeans comes especially from the O&M fc and the degradation of ESS. The hydrogen ESS is almost not exploited in public buildings in the first 10 years (Fig. 20b3) and they are used about 12% less than RB and about 52% less than HMPC in residential buildings (Fig. 20a3 and metrics M 4 and M 5 in Fig. 22). Notably, during the first 10 years in residential buildings (Fig. 20a3), HMPC-kmeans reduces the use of fuel cells because PV panels lose their efficiency, making the total raw energy surplus in the upcoming years lower than the first year. Consequently, the fuel cells do not need to be run as much as the first year to satisfy τ required sc . However, this scenario change in the future, especially after 10 years from today. With the increase in the electricity price, HMPC-kmeans prefers to use the hydrogen ESS to cover the building internal deficit rather than purchase electricity from the grid. This demonstrates that the MG cost estimator, along with the estimation of the expected annual self-consumption can handle the trade-off between the grid requirements and BMG expenditures. As an example, the first-year results shown in Fig. 23a reveal that HMPC-kmeans identifies that the BMG can satisfy τ required sc with only batteries, which is cheaper than the hydrogen chain.

Controversially, the HMPC uses the hydrogen ESS whenever it can, which leads it to attain a self-consumption rate 17% higher in public buildings and 14% higher in residential buildings (Fig. 22, metric M 1 ) than HMPC-kmeans, but the operating cost was about 7% higher in public buildings and 3% higher in residential buildings (Fig. 22, metric M 2 ). According to Fig. 19, HMPC with hybrid ESS results in fewer savings than HMPC-kmeans, even though it attained a higher selfconsumption rate (Fig. 20a4 and Fig. 20b4). This leads us to conclude that the additional income due to the self-consumption premium does not encourage the use of fuel cells and electrolysers enough because it is advantageous not to use the hydrogen ESS than foster selfconsumption. Although the HMPC attained higher marks of selfconsumption than both RB and HMPC-kmeans, its operating cost is still higher than HMPC-kmeans and nearly the same as RB.

Likewise, in the scenario of residential buildings, the HMPC-kmeans with hybrid ESS provides the cheapest BMG operating cost while satisfying τ required sc . As shown in Fig. 22, the total BMG operation cost with HMPC-kmeans in the residential building is reduced by 5.5% compared to RB. This is because HMPC-kmeans uses the hydrogen ESS only when necessary, instead of whenever there is an energy surplus or energy deficit. As concluded previously, residential BMG cannot attain τ required sc with only batteries (Fig. 21, all M 1 < τ 80% sc = 28.5%). Consequently, as shown in Fig. 23b, through the expected self-consumption estimation handled by the inequality constraint of Eq. ( 50), the HMPC-kmeans identifies that it is necessary to use the hydrogen chain to accomplish the primordial objective of annual self-consumption rate; otherwise it will be penalised by π pen sc of Eq. ( 38). However, hydrogen ESS is much more expensive than batteries. Therefore, the hydrogen ESSs are used only to attain the minimum τ required sc . As a result, HMPC-kmeans degrades 35% less electrolysers and 12% less fuel cells compared to RB and much less than HMPC (metrics M 4 and M 5 of Fig. 22).

Impact of hydrogen ESS capital costs

Since one of the greatest challenges of hydrogen ESS market accessibility is its high investment cost, a suitable capital cost that would become hydrogen ESS cost-effective was investigated. This economic analysis was conducted using the scenario of the first year of BMG operating, which corresponds to the current capital costs and electricity prices. According to [START_REF] Parra | A review on the role, cost and value of hydrogen energy systems for deep decarbonisation[END_REF], the capital cost of fuel cells is nowadays significantly higher than the cost of the entire PV-battery systems, which leads the use of fuel cells highly dependent on public policies to financially support their investment or major technological breakthroughs to reduce their capital cost.

However, the capital cost of fuel cells depends on the size of the equipment (usually in kW) and the annual manufacturing rate [START_REF] Blvd | Manufacturing Cost Analysis of Stationary Fuel Cell Systems[END_REF], which make future and current fuel cell capital costs (C fc ) very uncertain. Although many studies [START_REF] Parra | A review on the role, cost and value of hydrogen energy systems for deep decarbonisation[END_REF][START_REF] Yamashita | A review of hierarchical control for building microgrids[END_REF] indicate that it will tend to decrease in the future, projections for C fc depend on the manufacturing process which introduces high divergences in fuel cell prices, especially for small ones (some price ranges are provided in [START_REF] Parra | A review on the role, cost and value of hydrogen energy systems for deep decarbonisation[END_REF][START_REF] Yamashita | A review of hierarchical control for building microgrids[END_REF]).

Therefore, aiming to evaluate the impact of hydrogen ESS capital costs on annual BMG operating cost, the sensitivity of HMPC-kmeans to variations in C fc was assessed. Fig. 24a1 reveals that, from the perspective of HMPC-kmeans, the use of hydrogen ESS starts being profitable in public buildings when C fc is below 3500 €/kW, which represents a decrease of 53% of the adopted current C fc ≅ 7500 €/kW (Table 3). Regarding the curves in Fig. 24b1, HMPC-kmeans in residential buildings starts using hydrogen ESS to increase the selfconsumption rate when C fc is inferior to 2500 €/kW, which is lower than in public buildings.

By correlating the use of ESS with the total MG cost with HMPCkmeans (Fig. 24a1 and Fig. 24a2 for public buildings; Fig. 24b1 and Fig. 24b2 for residential buildings), it is possible to note that the use of fuel cells rises when the total MG cost with only batteries is smaller than the scenario with hybrid ESS. This highlights that HMPC-kmeans can adapt according to C fc guaranteeing higher annual self-consumption rates when C fc is cheaper (Fig. 24a3 and Fig. 24b3). This mechanism provides cheaper BMG operating cost than RB in all circumstances (Fig. 19a2 and Fig. 19b2) and HMPC for high C fc (above 2500 €/kW in residential and above 3500 €/kW in public buildings). Nonetheless, at cheap C fc , HMPC is very close to the performance of HMPC-kmeans and in some situations HMPC outperforms HMPC- kmeans (Fig. 24a2 and Fig. 24b2). According to Fig. 24a1 and Fig. 24b1, at small fuel cell prices, HMPC-kmeans increases the use of hydrogen ESS and reduces the uses of batteries, regulating the trade-off of exploiting hybrid ESS. Remarkably, in the residential building, the trade-off between batteries and hydrogen ESS is more obvious, as shown in Fig. 24b1 at a price of 1000 €/kW and 2000 €/kW. When fuel cells and electrolysers become as competitive as batteries, there will be an oscillation in the tendency to ESS and the self-consumption rate.

Among the three control strategies studied, HMPC with hybrid ESS guaranteed the highest self-consumption rate but the highest BMG operating cost with the current capital cost (Fig. 21 and Fig. 22). For this reason, the condition for HMPC to be profitable was investigated. As HMPC is insensitive to C fc , the hydrogen ESS would be advantageous if the economic savings of its installation were greater than its cost. In other words, to guarantee the hydrogen ESS profitability, Eq. ( 58) must be respected.

Considering the same capital cost for batteries (C bat ), electrolysers (C els ), the same electricity price (π elec,k ), similar financial incentives for self-consumption (π annual sc ) and similar O&M fc , the economic savings from hydrogen ESS installation are constant regarding variations to C fc . Therefore, the right side of Eq. ( 58), corresponding to the total saving from hydrogen ESS installation (named 'Total H 2 benefits' in Fig. 25), is constant under variations of C fc . Controversially, π annual fc,hybrid is linearly dependent on C fc as specified in metric M 4 in Table 2, which results in the curves in Fig. 25. Due to the low round-trip efficiency of hydrogen ESS, the use of batteries is privileged, making equal battery cost with hybrid and non-hybrid ESS (π annual bat,hybrid and π annual bat,onlyBat , respectively). Therefore, using the values of points Today, A, B and C given in Fig. 25, the use of hydrogen ESS by means HMPC in public and residential BMGs would be advantageous under three scenarios:

• Scenario 1: The capital cost of fuel cells must be reduced by at least 1 -Ax Todayx . This means a reduction of 72% in public buildings (C fc < 2117 €/kW) and 89% in residential buildings (C fc < 847 €/kW).

• Scenario 2: Self-consumption additional income must be increased by (Todayy-Ay) By -1 when the hydrogen ESS is installed. For this, Eq.

(37) for the additional income must be modified accordingly. This means an increase of 94% in public buildings and 338% in residential buildings.

• Scenario 3: The price of electricity must be (Todayy-Ay) (Cy-By) more expensive. This means an increase of 76% in public buildings and 149% in residential buildings.

Impact of operating the hydrogen ESS at a nominal power rate

Operating PEM electrolysers and PEM fuel cells close to their nominal power rate can enhance power-to-gas or gas-to-power conversion efficiency and extend the lifetime of ESS devices [START_REF] Rakousky | Polymer electrolyte membrane water electrolysis: Restraining degradation in the presence of fluctuating power[END_REF]. However, the benefits of operating hydrogen ESS at nominal power may not be enough to cover the drawbacks of constraining the use of hydrogen ESS, which may result in the non-profitable operating of the BMG. Depending on the ESS capital cost, public financial incentives, electricity price, and internal power consumption profiles, fuel cells and electrolyser operating at nominal power may prevent the BMG to attain major objectives, such as minimising the whole operation cost or maximizing the selfconsumption rate. Therefore, to evaluate the impact of limiting the use of hydrogen ESS at nominal power, two additional scenarios were assessed: scenario with hard constraints and scenario with soft constraints. To highlight the impact of constraining the use of hydrogen ESS, these two scenarios consider that the hydrogen ESS capital cost is zero, leading the HMPC-kmeans to use fuel cells and electrolysers.

The scenario with hard constraints consists of embedding into EMPC constraints (59) and (60). In this manner, electrolysers and fuel cells can operate only if there is enough energy to run them near to their nominal power (P nom fc and P nom els in Table 1) for at least 2 h. On the other hand, these constraints do not exist in the scenario with soft constraints, so that the hydrogen chain is free to operate according to BMG needs.

According to the graphs in Fig. 26, limiting the use of the hydrogen chain reduces the capacity of the BMG to attain higher marks of selfconsumption, which increases the total MG cost. Hard constraints result in a reduction of 7% of self-consumption in public buildings, whereas in residential buildings it is decreased by 2% when using HMPC. This is because the hydrogen chain is less exploited in the scenario with hard constraints than with soft constraints, which minimises the capacity of shifting the load toward periods of surplus and obliges the BMG to inject into the grid. For this reason, the total annual degradation of hydrogen ESS (third and fourth lines of graphs of Fig. 26) is considerably lower with hard constraints than with soft constraints.

By observing the power flow of these two scenarios with HMPC (Fig. 27), the reduction of the hydrogen ESS total degradation is mainly because the hydrogen ESS is not used at all in certain circumstances, rather than because it is operated at nominal power rate. According to Fig. 26, the fuel cell and electrolyser degradation rate (fifth and sixth lines of graphs of Fig. 26) with hard or soft constraints are nearly the same, which is in line with the conclusion of [START_REF] Rakousky | Polymer electrolyte membrane water electrolysis: Restraining degradation in the presence of fluctuating power[END_REF]. As shown in Fig. 27, the fuel cells and electrolysers are not used because the power imbalance is lower than their respective nominal power, while under soft constraints, the hydrogen ESS can cover most of the raw power imbalance. This is because hard constraints prevent the use of fuel cells if the energy deficit is lower than its nominal power (P nom fc = 20kW) and restrain the use of electrolysers if the energy surplus is lower than its nominal power (P nom els = 25kW).

To overcome this problem, there are two solutions: either the hydrogen chain should be sized according to the most likely minimum power consumption and minimum power generation, or the controller should be designed with soft constraints. Given that the power imbalance in BMG is very unpredictable, it is to use soft constraints rather than hard constraints. Since the power imbalance of buildings is very seasonal, it is difficult to assign minimum operating power (P nom fc and P nom els ) without losing performance or profitability during the entire year.

Impact of power imbalance prediction data error

Aiming to demonstrate the robustness of the proposed HMPCkmeans against the stochasticity in power imbalance, scenarios with prediction data error were analysed. For this, the real power imbalance was multiplied by a random factor, and it was shifted in time randomly up to 3h. To mimic the rising of prediction error along the MPC horizon, the error in the amplitude of the signal increases over time, detaining 0% of errors at the current time and attaining up to 60% of errors 48 h ahead. The comparison between the real and the predicted power imbalance is shown in Fig. 28.

By analysing the results of Fig. 29, although errors in the prediction data harm the performance of both HMPC and HMPC-kmeans, they satisfy the required self-consumption (M1 ≥ τ 80% sc ) and they still outperforming the RB in the economic aspects. The self-consumption rate using HMPC and HMPC-kmeans approaches the values attained by RB. In residential buildings, self-consumption is degraded in 6%, compared to 4% in public buildings. Despite this considerable reduction, HMPCkmeans can still ensure nearly the same operating cost (results of Fig. 22), which is 9% lower in public buildings and 5% lower in residential buildings than RB.

Conclusion

One of the greatest challenges in designing an energy management system for building microgrids equipped with hybrid energy storage systems is the trade-off between using hydrogen storage and batteries. Other problems restraining building microgrid breakthroughs are the cost-effectiveness of installing storage devices in buildings and determining their balanced use to guarantee high marks of self-consumption at minimum cost. Aiming to tackle these issues, this paper proposes a two-level Hierarchical Model Predictive Controller (HMPC) empowered with two data-driven algorithms. This innovative control strategy aims to increase the flexibility of the power flow controller by enabling it to

Fig. 1 .

 1 Fig. 1. Hierarchical energy management system for optimising the power flow of a building microgrid.

h=

  48h), considering the total electricity cost (π grid,k ), the total ESS degradation cost (π deg bat,k + π deg els,k + π deg fc,k ), the annual financial reward for self-consuming electricity (π sc,k ) and the penalisation for not attaining the required marks of annual self-consumption rate (π pen sc,k ) for each hour k. Therefore, the EMPC optimises at least once a day (T EMPC s = 24h) the cost function defined by (2) and determines the SoC ref and LoH ref to be sent to the lower MPC. Each of these costs is updated daily by the MG cost estimator by analysing local measurements and the past behaviour of the HMPC. Further details about the MG cost estimator are provided in the Section 5.

  moles consumed (T TMPC s ⋅ ṅfc H2 ,k ) or generated (T TMPC s ⋅ ṅels H2,k ) within the TMPC sampling time (T TMPC s = 1h). Therefore, by combining (

Fig. 3 .

 3 Fig. 3. Real-Time model identification of the parameters for Li-ion battery model.

Fig. 4 .

 4 Fig. 4. Comparison between the real and estimated SoC using the classic model and the proposed dynamic model within the EMPC sampling time of 24 h (marked by the vertical lines EMPC update).

Fig. 5 .

 5 Fig. 5. Fuel cell and electrolyser power according to their current.

Fig. 6 .

 6 Fig.6. Real-Time model identification of the parameters for a hydrogen storage system model.

Fig. 7 .

 7 Fig. 7. Comparison between the real and estimated LoH using the classic model and the proposed dynamic model within the EMPC time sample of 24 h (marked by the vertical lines EMPC update).

Fig. 9 .

 9 Fig. 9. Degradation in fuel cells and electrolyser cells overpotentials modelled in Simulink.

Fig. 10 .

 10 Fig. 10. Linear regression vs dynamic average approximations of voltage degradation in fuel cells and electrolysers.

Fig. 11 .

 11 Fig. 11. The five features for k-means classification.

  equivalently to E ch bat|k , which is the average energy for charging the batteries given that day D belongs to class k. Therefore, E ch bat|k is determined using (45), in which the conditional expected value is calculated through the dynamic average of the total daily energy assigned for batteries ( ∑ 24 i=1 E ch bat,i ) after the k-means classification. Consequently, E ch bat|k combined with the expected number of days belonging to class k in the future (n future k ) enables to estimate the annual Êch bat . As expressed in (46), Êch bat is the union of all conditional expected values through all four kmeans classes. Following the same reasoning, Eq. (47) is obtained for estimating Êels .

E

  change according to the current power imbalance profile, n today and n tomorrow . Therefore, these parameters are calculated daily using (51) -(53).

Fig. 12 .

 12 Fig. 12. K-means classification of the one-year power imbalance data prediction.

Fig. 13 .

 13 Fig. 13. Annual power imbalance data prediction classified into four classes.

Fig. 14 .

 14 Fig. 14. Replacement of previous year data prediction by the recent one.

Fig. 15 .

 15 Fig. 15. Estimation of the expected annual self-consumption rate based on power imbalance prediction data.

Fig. 16 .

 16 Fig. 16. Maximum, minimum, and average photovoltaic power generation profiles.

Fig. 17 .

 17 Fig. 17. Summer, winter and holidays power consumption daily profiles. (a) Public building. (b) Residential building.

Fig. 18 .

 18 Fig. 18. The logic of the rule-based controller with the transition, conditions and states to operate building microgrids with hybrid or non-hybrid energy storage systems.

+

  O&M bat,y + O&M els,y + O&M fc,y )

  and Fig. 22. Remarkably, the variable τ 80% sc indicates the minimum relative difference of self-consumption (metric M 1 ) to satisfy τ required sc of 80%. In other words, the relative difference of M 1 should be above τ 80% sc to avoid reduction of the P factor.

Fig. 19 .

 19 Fig. 19. Estimation for the next 25 years of the annual building microgrids operation cost, considering the grid penalisation for not satisfying the required self-consumption rate of 80%. (a) Public building. (b) Residential building.

Fig. 20 .

 20 Fig. 20. Detail of the estimation of the building expenses for the next 25 years depending on the energy management system and the type of building.

Fig. 22 .

 22 Fig. 22. Comparison of the first-year performance of the three control strategies when batteries and hydrogen ESS are installed.

Fig. 23 .

 23 Fig. 23. Accuracy of the annual self-consumption prediction implemented by HMPC-kmeans.

  grid,hybrid -π annual bat,hybrid -π annual els,hybrid + π annual sc,hybrid -O&M fc ) -( -π annual grid,onlyBAT -π annual bat,onlyBAT + π annual sc,onlyBAT )

Fig. 24 .

 24 Fig. 24. Impact of fuel cells capital cost on the building microgrids performance. (a) Public buildings. (b) Residential buildings.

Fig. 25 .

 25 Fig. 25. Economic analysis of hydrogen ESS installation in public and residential BMGs to estimate three possible affordable scenarios for fuel-cell in building microgrids.

∑

Fig. 26 .

 26 Fig. 26. Performance of the conventional Hierarchical Model Predictive Controller (HMPC) and proposed hierarchical model prediction controller (HMPC-kmeans) with soft and hard constraints for operating hydrogen storage.

Fig. 27 .

 27 Fig. 27. Impact hard and soft constraints in the operation of electrolysers and fuel cells in the public building, when using the conventional Hierarchical Model Predictive Controller (HMPC).

Fig. 28 . 1 x 3 )

 2813 Fig. 28. Prediction data with and without error along the Economic Model Predictive Control horizon of 48 h.

Table 1

 1 Sizing of the building microgrid.

	Equipment	Description
	Photovoltaic panels	Peak power at 1000 W/m 2 : 100 kWc
	Lithium-ion batteries	Nominal capacity: 167 Ah
		Nominal Voltage: 700 V
		Nominal discharge current: 70A
		Maximum power rate: 60 kW
	Electrolyser	Nominal power: 25 kW Hydrogen production (ς els ): 4.18 kWh/Nm 3
		Maximum power rate: 30 kW
	Fuel cell	Nominal power: 20 kW Hydrogen consumption (ς fc ): 0.63 Nm 3 /kWh
		Maximum power rate: 48 kW
	Hydrogen tank	Maximum pressure: 8 bars @ 80 • C
		Maximum hydrogen mass: 9 kg Volume (Vtank): 173 Nm 3
	Grid	Maximum grid energy exchange: 100 kW
		DC bus voltage: 380 V

Table 3

 3 Current cost of ESS equipment.

	ESS equipment	CAPEX*	Sizing	Cost (€) *
	Battery [7]	500 (€/kWh)	120 kWh	C bat = 60120
	Electrolyser [11,27]	750 (€/kW)	25 kW	C els = 18750
	Fuel cell [27]	7500 (€/kW)	20 kW	C fc = 150000
	*The cost includes installation expenses and ESS purchase
	CAPEX: capital expenditure

Table 4

 4 One-year simulation results of the rule-based controller in the public building.

	ESS	Self-consumption	Total MG cost	Battery cost	Electrolyser cost	Fuel cell cost	Electricity cost	Additional income
		(M RB 1 )	(M RB 2 )	(M RB 3 )	(M RB 4 )	(M RB 5 )	(M RB 6 )	(M RB 7 )
	Battery	79.7%	11,819 €	1456 €	0 €	0 €	12,220 €	1857 €
	Battery and	92.9%	12,307 €	1456 €	292	1247 €	11,723 €	2410 €
	hydrogen
	Without ESS	69.6%	11,660 €	0 €	0 €	0 €	13,451 €	1791 €

Table 5

 5 One-year simulation results of the rule-based controller in a residential building.

	ESS	Self-consumption	Total MG cost	Battery cost	Electrolyser cost	Fuel cell cost	Electricity cost	Additional income
		(M RB 1 )	(M RB 2 )	(M RB 3 )	(M RB 4 )	(M RB 5 )	(M RB 6 )	(M RB 7 )
	Battery	62.2%	20,888 €	2586 €	0 €	0 €	19,766 €	1463 €
	Battery and	86.7%	22,362	2586 €	541 €	2267 €	19,058 €	2090 €
	hydrogen
	Without ESS	47.3%	20,047 €	0 €	0 €	0 €	21,413 €	1366 €

  The energy self-consumed (E sc,k ) is calculated from (B.2).Since E surplus,k is uncontrolled by the EMPC because it is dependent on weather conditions and building internal consumption, the maximization of

	π annual sc	= 10 -6 ⋅ (	∑ 365 k=1	(P + 5)⋅E sc,k + P⋅E injected grid,k -12⋅E pv,k ⋅ P maxInjected pv P inst	)		(B.1)
	E sc,k = E pv,k -E injected grid,k									(B.2)
	By replacing (B.2) in (B.1), and knowing that E injected grid,k is calculated from (33), π annual sc	can be calculated following (B.3).
	π annual sc	= 10 -6 ⋅ (	∑ 365 k=1	5⋅ ( ⃒ ⃒ E els,k	⃒ ⃒ +	⃒ ⃒ ⃒E ch bat,k	⃒ ⃒ ⃒	)	-5⋅E surplus,k + (P + 5)⋅E pv,k -12⋅E pv,k ⋅	P maxInjected pv P inst	)	(B.3)
	π annual sc π annual sc	is guaranteed by optimizing (B.4). = 10 -6 ⋅ ( ∑ 365 k=1 5⋅ ( ⃒ ⃒ E els,k ⃒ ⃒ + ⃒ ⃒ ⃒E ch bat,k ⃒ ⃒ ⃒ ) -12⋅E pv,k ⋅ P maxInjected pv P inst	)			(B.4)

Acknowledgements

The authors would like to thank the New Aquitaine Region (research agreement: AAPFO424953) and ESTIA, the Institute of Advanced Industrial Technologies, for their financial support for the OptiMicroGrid project.

adapt to different energy storage installations (i.e. hybrid or non-hybrid) and different type of buildings (i.e. residential and public) automatically.

The first data-driven algorithm is to handle inaccuracies in HMPC internal models. The simulations conducted in MATLAB Simulink demonstrated that it can enhance the accuracy of battery model up to four times and can improve up to ten times the precision of hydrogen storage model. This makes the building energy management system more flexible and less dependent on accurate pre-modelling steps.

The second data-driven algorithm is to determine optimal parameters for the HMPC cost function to handle the trade-off between maximising the annual self-consumption rate and minimising the building microgrid's total cost, without needing to tune any parameter. Through simulations using the dataset of both a public and a residential building, the proposed controller was confronted with a traditional rule-based and a conventional HMPC. The simulations were carried out to assess four important aspects of these three controllers: the impact of ESS installation, the impact of hydrogen storage capital costs, the impact of constraining the use of hydrogen storage at nominal power and the impact of errors in the prediction data.

Considering all simulation scenarios, the proposed HMPC identifies the most suitable storage device to be run each day to guarantee the required marks of self-consumption rates at minimum cost. Compared to the rule-based controller, the proposed controller reduced the building microgrid's total operation cost by up to 5% in residential buildings and up to 9% in non-residential buildings in the first year of operation. To highlight the importance of considering not only energy aspects but also the economic ones in power flow optimisation and to demonstrate a feasible strategy to tackle this issue, the proposed controller that figures out a balance between cost, profit and energy autonomy automatically was compared to another HMPC that contains a cost function that maximises only the self-consumption rate. Although the proposed strategy guaranteed a self-consumption rate from 5% to 17% lower than the conventional HMPC, the proposed strategy satisfied the required self-consumption rate with annual operation cost between 1% and 7% lower.

The results also revealed that the current French grid reward for self-consumption is not enough to encourage the use of fuel cells and electrolysers with their current capital cost. Hydrogen storage is still very expensive to be profitable to integrate it into building microgrids. Since the proposed HMPC calculates its control actions that maximises the expected annual self-consumption rate and minimises the expected annual operation cost, it operates fuel cells and electrolysers only when it is strictly necessary. As a result, the hydrogen chain is almost unused in the scenario where the microgrid can satisfy the minimum requirements of self-consumption rate with only batteries. Controversially, the rule-based controller and the conventional HMPC operate the hydrogen chain as much as possible to maximise the self-consumption rate but this ignores economic aspects, resulting in higher operating cost. Although this result was drawn in the scenario of the French grid policy, it can be exploitable in other countries. Based on the results obtained, three possible scenarios to make the use of fuel cells profitable were suggested, which can be useful to other applications that targets encouraging self-consumption in buildings. Furthermore, it was verified that constraining the use of hydrogen chains around their nominal power restrain the capacity of the building microgrid to attain higher marks of annual self-consumption rate. Due to the stochasticity in the power imbalance, it is difficult to determine an optimal minimum power threshold to operate fuel cells and electrolysers, without degrading the system's profitability. Consequently, making the use of hydrogen chain free not only allows the BMG to increase the self-consumption rate by up to 6.5% and reduce total costs by up to 7% but also reduces the complexity of the controller's design.

As future work, the performance of the proposed HMPC with more severe prediction data errors, such as changing in vacation days, will be evaluated. This will verify the robustness of the controller to handle events that approach real applications. Furthermore, the benefits and drawbacks of exploiting the batteries of electric vehicles on behalf of BMG will be evaluated.

CRediT authorship contribution statement

Declaration of Competing Interest

The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.

Appendix A. Dynamic average

Let be x i a measurement point acquired at instant i and x N the dynamic average of all Npast measurement points from t = 0 to t = i. Therefore, x N+1 can be calculated only using the current measure x i and the total number of updates N, as specified in the following equations in order of compilation: