Demand and Storage Management in a Prosumer Nanogrid Based on Energy Forecasting

Energy efficiency and consumers’ role in the energy system are among the strategic research topics in power systems these days. Smart grids (SG) and, specifically, microgrids, are key tools for these purposes. This paper presents a three-stage strategy for energy management in a prosumer nanogrid. Firstly, energy monitoring is performed and time-space compression is applied as a tool for forecasting energy resources and power quality (PQ) indices; secondly, demand is managed, taking advantage of smart appliances (SA) to reduce the electricity bill; finally, energy storage systems (ESS) are also managed to better match the forecasted generation of each prosumer. Results show how these strategies can be coordinated to contribute to energy management in the prosumer nanogrid. A simulation test is included, which proves how effectively the prosumers’ power converters track the power setpoints obtained from the proposed strategy.


Introduction
The reinforcement of consumers' role in energy systems and the improvement of energy efficiency, in general, are among the key actions established in the European Strategic Energy Technology (SET) Plan [1]. This paper deals with some of the main topics in this SET Plan-energy monitoring and forecasting, consumers' role in demand response (DR), and energy production and storage management-to achieve a higher renewable energy penetration and to improve energy efficiency. It is focused on a prosumer nanogrid [2], where prosumers have generation and energy storage systems (ESS) and they have control over their demand. Many studies about each of those topics can be found in the recent scientific literature. However, the combination of them in a whole management strategy has been hardly addressed in other works.
Wide attention has been paid to energy management systems (EMS) in microgrids, which may be applied to small-scale nanogrids, although they are not usually focused on prosumer-based microgrids. Literature on microgrids EMS is usually focused on defining the objective function to optimize the economic benefit within the microgrid [3,4]. Energy trading among different agents, like microgrids [5,6] or prosumers [7], has also been studied, with the aim of defining an incentive scheme for energy trading. However, none of these works provide a joint perspective of energy monitoring and forecasting, DR, and storage management, which is the main contribution of this proposal. All these aspects are essential to move towards Renewable Energy Communities, encouraged by the European Union in Directive (EU) 2018/2001 [8].
Mass digitization and the Internet of Things (IoT) are transforming many industries (Industry 4.0) and residential zones. This implies that the latest advances related to communication technologies, monitoring devices, and multiple data processing algorithms constitute qualitative progress that makes it possible to introduce more monitoring points as part of the Advanced Metering Infrastructure (AMI) [9] in the SG at all voltage levels [10,11].
The methods for permanent monitoring of power quality (PQ) and reliability analysis have to be adapted to large-scale deployments and campaigns, where time and space compression plays a special role. For this reason, the market for industrial and manufacturing PQ equipment is growing significantly, and consequently, several areas of knowledge are converging and pushing it up (e.g., Statistical Signal Processing and Instrumentation). In fact, while traditional PQ instruments have been devoted to developing specific measurement campaigns with the goal of capturing certain types of events, the current electrical network demands a flexible strategy capable of measuring new types of PQ disturbances as a result of non-optimized managements. Consequently, the number of fixed PQ analyzers has increased, and massive data are managed according to different measurement strategies, depending on the European country [12]. The SG demands an enhanced role for individual customers and prosumers taking part in the decisions in a new market model [13], where new energy profiles are appearing [14] and learning-based systems help empower customers to select companies according to the price and electricity fulfillment [15]. In this sense, it is crucial to fill in the gap between the energy delivered by utilities, and how end users assess its quality. According to the current nanogrid framework, it would be desirable to monitor the energy delivery and the PQ in the point of common coupling (PCC) and within the prosumers' sides. In addition, weather and energy should be forecasted to guarantee that the smart appliances (SA) operate properly.
Popularly, SA are recognized for having some modern computer-based communication technology to make their tasks faster, cheaper, or more energy efficient. For example, smart washing machines can independently regulate the washing powder and the detergent to be used depending on the weight of the load and the type of fabric. They can also automatically send alerts when the detergent runs out. However, in the energy field, within the framework of SG, the term "smart" refers to those appliances capable of modulating their electricity demand in response to signal request from the electrical system [16][17][18]. Thus, household appliances could incorporate different DR strategies.
Generally, DR policies can be divided into direct (explicit DR) through aggregation, or indirect (implicit DR). Explicit DR (also called incentive-based DR program) is divided into traditional (e.g., direct load control-DLC, interruptible pricing) and market-based (e.g., emergency DR programs, capacity programs, demand bidding programs, and ancillary services market programs). On the other hand, implicit DR (sometimes called price-based DR programs) refers to the voluntary program in which consumers are exposed to electricity prices that vary over time, for example, time-of-use prices, prices at critical peaks, and real-time prices. For appliances, this would take the form of load-shifting strategies, which change their period of operation from peak to non-peak hours, or load-modulating strategies, which directly reduce or avoid energy use during peak hours [19].
EMS requires flexibility to match demanded energy with generated energy. As well as DR techniques, ESS definitely contribute to such flexibility. In microgrids, ESS usually have functions related to peak shaving and mitigation of intermittent generation fluctuation, typical of some renewable energy sources, like photovoltaic (PV) [20]. ESS management also aims to obtain economic advantages in literature [3,4]. In this paper, the role of ESS focuses on collaborating with DR techniques to outperform the management capability of the nanogrid energy. Figure 1 depicts a scheme of the different stages of the proposed strategy. The first stage constitutes a forecasting tool, which can be used to estimate the PV generation power profile, as well as the weather variables, which influence energy consumption; the second stage performs a DR technique to optimize the consumption power profile; finally, the first stage schedules the ESS power profile with the aim of reducing the nanogrid dependence on the main grid. A simulation of the prosumer-based nanogrid is then carried out to test the results.
Electronics 2020, 9, x FOR PEER REVIEW  3 of 15 profile with the aim of reducing the nanogrid dependence on the main grid. A simulation of the prosumer-based nanogrid is then carried out to test the results. This paper is organized as follows: Section 2 is focused on energy monitoring and forecasting; a DR method based on SA is proposed in Section 3; Section 4 is devoted to optimizing the ESS scheduling within the nanogrid; Section 5 presents a simulation test of power converters control to track obtained power setpoints; Finally, Section 6 summarizes conclusions.

Nanogrid Energy Monitoring and PQ Forecasting
Some recent works on the role played by forecasting in demand and storage management are related to managing uncertainties from renewable generation, electric load demand, temperature, and PV energy storage. Different energy demand strategies are proposed from the demand side and the generation side based on operating and environmental costs. Operational optimization of hybrid renewable energy systems (HRES), such as solar, wind, and diesel generation as backup resources and battery storage, helps manage system sizing in a local framework [21]. Additionally, coordinating virtual ESS using electric vehicles as more flexible resources, introducing intra-hour adjustment stage. The objectives are to adjust the different forecasting errors and to monitor the response characteristics based on scenarios [21,22].
Indeed, optimal economical dispatch plays an important role in order to minimize the microgrid operating costs and reduce the energy costs compared with different strategies [21,23]. Hierarchical control structure and alternative forecasting techniques are implemented using autoregressive integrated moving average (ARIMA), exponential smoothing, and neural networks [24]. Some other optimal EMS incorporate the stochastic approach for microgrids using optimization algorithms of mixed-integrated linear programming (MILP), and GAMS (general algebraic modeling system) implementation using power optimization at minimum operational costs.
Along with this, weather forecasting strategies are needed in order to update the energy models to the local conditions and improve energy dispatch, taking advantage of all the energy resources. The introduction of weather forecasting models in predictive control [21,24] allows forecasting studies in a smaller scale (e.g., single residential buildings and tertiary buildings).
Nevertheless, none of these previous strategies introduces the power quality issues on the nanogrid energy forecasting management. This section points to space and time compression as the main forecasting solutions to manage data within the frame of an instrumental technique, which is, at the same time, extensive to all PQ disturbance types and applicable downstream and upstream of a nanogrid energy forecasting system. In addition, an easy-to-implement PQ index is proposed which is intended for prosumers and house-hold appliances ( Figure 2). This paper is organized as follows: Section 2 is focused on energy monitoring and forecasting; a DR method based on SA is proposed in Section 3; Section 4 is devoted to optimizing the ESS scheduling within the nanogrid; Section 5 presents a simulation test of power converters control to track obtained power setpoints; Finally, Section 6 summarizes conclusions.

Nanogrid Energy Monitoring and PQ Forecasting
Some recent works on the role played by forecasting in demand and storage management are related to managing uncertainties from renewable generation, electric load demand, temperature, and PV energy storage. Different energy demand strategies are proposed from the demand side and the generation side based on operating and environmental costs. Operational optimization of hybrid renewable energy systems (HRES), such as solar, wind, and diesel generation as backup resources and battery storage, helps manage system sizing in a local framework [21]. Additionally, coordinating virtual ESS using electric vehicles as more flexible resources, introducing intra-hour adjustment stage. The objectives are to adjust the different forecasting errors and to monitor the response characteristics based on scenarios [21,22].
Indeed, optimal economical dispatch plays an important role in order to minimize the microgrid operating costs and reduce the energy costs compared with different strategies [21,23]. Hierarchical control structure and alternative forecasting techniques are implemented using autoregressive integrated moving average (ARIMA), exponential smoothing, and neural networks [24]. Some other optimal EMS incorporate the stochastic approach for microgrids using optimization algorithms of mixed-integrated linear programming (MILP), and GAMS (general algebraic modeling system) implementation using power optimization at minimum operational costs.
Along with this, weather forecasting strategies are needed in order to update the energy models to the local conditions and improve energy dispatch, taking advantage of all the energy resources. The introduction of weather forecasting models in predictive control [21,24] allows forecasting studies in a smaller scale (e.g., single residential buildings and tertiary buildings).
Nevertheless, none of these previous strategies introduces the power quality issues on the nanogrid energy forecasting management. This section points to space and time compression as the main forecasting solutions to manage data within the frame of an instrumental technique, which is, at the same time, extensive to all PQ disturbance types and applicable downstream and upstream of a nanogrid energy forecasting system. In addition, an easy-to-implement PQ index is proposed which is intended for prosumers and house-hold appliances ( Figure 2). The reporting levels along with the allocations within the entire network are usually interpreted through the PQ triangle [9], in which time and space compression are concepts of high importance when monitoring PQ. Time compression implies reducing one time-series to a number and usually converts one unit (e.g., Volts) into another different unit (e.g., root mean square -RMS). Space compression consists of the reduction of the same measurement taken from several locations at the same level (e.g., site index) with the goal of characterizing an area (e.g., feeder index) within a microgrid, or a prosumer in a nanogrid. The proposed method for massive data acquisition and representation may consist of scheduled data acquisition and processing data and can be applied on a nanogrid. Given a time window of length Δt, the M time-series of measurements are compressed in the time domain, as each N-point register is reduced to a single data point in the 2D space. The statistic versus statistic representation allows a better understanding of the system's dynamic, as the evolution of the vector indicates the energy fluctuation. Depending on the total elapsed time (multiple of Δt), the trajectory accounts for PQ or reliability operation.
The proposed unified PQ index is calculated via (1), in which the averaged differences among the measurements sij and the ideal values ˆj s (associated with a healthy power-line signal) of the statistics are computed. (1) The role of this index consists of monitoring the energy state within transactions between the actors in the system under normal operating conditions, i.e., the role of the monitoring system is to check if contractual conditions are fulfilled (e.g., frequency, voltage levels) to guarantee an adequate power supply that outperforms the management capability of the nanogrid. This strategy is an approximation to match PQ and energy forecasting data so as to enable adequate supply, i.e., to perform a forecast when the energy can be supplied or when the supply is most convenient ( Figure  2). Hereinafter, we show the performance of real-life instrumental examples within a week measurement campaign. The reporting levels along with the allocations within the entire network are usually interpreted through the PQ triangle [9], in which time and space compression are concepts of high importance when monitoring PQ. Time compression implies reducing one time-series to a number and usually converts one unit (e.g., Volts) into another different unit (e.g., root mean square -RMS). Space compression consists of the reduction of the same measurement taken from several locations at the same level (e.g., site index) with the goal of characterizing an area (e.g., feeder index) within a microgrid, or a prosumer in a nanogrid. The proposed method for massive data acquisition and representation may consist of scheduled data acquisition and processing data and can be applied on a nanogrid. Given a time window of length ∆t, the M time-series of measurements are compressed in the time domain, as each N-point register is reduced to a single data point in the 2D space. The statistic versus statistic representation allows a better understanding of the system's dynamic, as the evolution of the vector indicates the energy fluctuation. Depending on the total elapsed time (multiple of ∆t), the trajectory accounts for PQ or reliability operation.

Demand Response by Means of Smart Appliances
The proposed unified PQ index is calculated via (1), in which the averaged differences among the measurements s ij and the ideal valuesŝ j (associated with a healthy power-line signal) of the statistics are computed.
The role of this index consists of monitoring the energy state within transactions between the actors in the system under normal operating conditions, i.e., the role of the monitoring system is to check if contractual conditions are fulfilled (e.g., frequency, voltage levels) to guarantee an adequate power supply that outperforms the management capability of the nanogrid. This strategy is an approximation to match PQ and energy forecasting data so as to enable adequate supply, i.e., to perform a forecast when the energy can be supplied or when the supply is most convenient ( Figure 2). Hereinafter, we show the performance of real-life instrumental examples within a week measurement campaign.

Demand Response by Means of Smart Appliances
In order to test the effectiveness of the most common DR techniques, a control platform composed of four blocks has been proposed, that collects and exchanges information, aiming to minimize the demand peaks and, therefore, to reduce the electricity bill by means of the DLC. Figure 3 refers to the architecture of the proposed platform, in which the core application developed with LabVIEW is in charge of processing the data provided by the rest of subsystems.
Electronics 2020, 9, x FOR PEER REVIEW 5 of 15 In order to test the effectiveness of the most common DR techniques, a control platform composed of four blocks has been proposed, that collects and exchanges information, aiming to minimize the demand peaks and, therefore, to reduce the electricity bill by means of the DLC. Figure  3 refers to the architecture of the proposed platform, in which the core application developed with LabVIEW is in charge of processing the data provided by the rest of subsystems. To achieve the abovementioned goal, DR policies will be implemented through an optimization model, specifically an MILP model that includes in its constraints details such as the SA nature, the people's behavior, and the amount of available energy that could be imported from the main sources taken into account. As can also be depicted from Figure 3, the optimization engine of GAMS was used due to its flexibility, as it makes it possible to state the mathematical formulation without regarding the number of decision variables, and also a straightforward way of interaction from many environments. A middleware written in C++ which internally uses the object-oriented Application Programming Interface (API) that the company provides for interacting purposes makes possible the link with the application core. In this sense, the MILP model that will be raised in the following lines can be solved simply by calling this middleware with the appropriate parameters. The block on the right of Figure 3 is related to the APIs that furnish the data to the optimization model (real-time prices-RTP, temperature and radiation forecast), therefore, three LabVIEW subVIs have been dedicated for managing the communication between them via HTTP.
Concerning the model, this paper proposes a novel MILP to optimize the cost of the daily household energy consumption and thus ensure the peak demand minimization using a strategy based on the DLC. Equation (2) refers the objective function f (in €) and the daily cost of the energy, where Pgrid(t) (in kW), RTP(t) (in €/kWh) and Δt (in hours) are the power imported from the utility, the hourly price of the energy at time slot t  [1, …T], and the time resolution given by being T equal to 24 h. This means a resolution of 1 h, which is more than enough for the platform, as it is devised to work in the highest control layer of the nanogrid (tertiary control).
The rest of the equations are related to the power balance and user preferences and have been expressed as constraints within the model. Equation (3) refers to the power balance at each time slot , being the foregoing power Pgrid(t) and the PV production Ppv(t) (in kW) on the generation side. On the demand side is the non-shiftable power Pns(t) (in kW), coming from uncontrollable loads such as lighting and small devices or simply the standby consumption. Pwm(t), Pdw(t), and Ptd(t) (in kW) are also on this side and represent the power consumption of the well-known SAs that can be found To achieve the abovementioned goal, DR policies will be implemented through an optimization model, specifically an MILP model that includes in its constraints details such as the SA nature, the people's behavior, and the amount of available energy that could be imported from the main sources taken into account. As can also be depicted from Figure 3, the optimization engine of GAMS was used due to its flexibility, as it makes it possible to state the mathematical formulation without regarding the number of decision variables, and also a straightforward way of interaction from many environments. A middleware written in C++ which internally uses the object-oriented Application Programming Interface (API) that the company provides for interacting purposes makes possible the link with the application core. In this sense, the MILP model that will be raised in the following lines can be solved simply by calling this middleware with the appropriate parameters. The block on the right of Figure 3 is related to the APIs that furnish the data to the optimization model (real-time prices-RTP, temperature and radiation forecast), therefore, three LabVIEW subVIs have been dedicated for managing the communication between them via HTTP.
Concerning the model, this paper proposes a novel MILP to optimize the cost of the daily household energy consumption and thus ensure the peak demand minimization using a strategy based on the DLC. Equation (2) refers the objective function f (in €) and the daily cost of the energy, where P grid (t) (in kW), RTP(t) (in €/kWh) and ∆t (in hours) are the power imported from the utility, the hourly price of the energy at time slot t ∈ [1, . . . T], and the time resolution given by ∆t = 24/T, being T equal to 24 h. This means a resolution of 1 h, which is more than enough for the platform, as it is devised to work in the highest control layer of the nanogrid (tertiary control).
The rest of the equations are related to the power balance and user preferences and have been expressed as constraints within the model. Equation (3) refers to the power balance at each time slot t, being the foregoing power P grid (t) and the PV production P pv (t) (in kW) on the generation side. On the demand side is the non-shiftable power P ns (t) (in kW), coming from uncontrollable loads such as lighting and small devices or simply the standby consumption. P wm (t), P dw (t), and P td (t) (in kW) are also on this side and represent the power consumption of the well-known SAs that can be found within a residential environment, in particular, the washing machine (WM), the dishwasher (DW), and the tumble drier (TD) respectively, the averaged consumption of the water heater (WH) has been expressed by P wh (t) (in kW). Equation (4) establishes the upper limit of the power taken from the grid by means of P max grid , which represents this value.
The previous power demands of each SA are expressed in Equations (5)-(7) through their averaged consumption profiles D wm , D dw , and D td (in kW), which are vectors with T components: the first two represent the averaged consumption and the rest of them are zero, since the time cycle of these SAs has been chosen to be 2 h. The employed strategy entailed building as many rotated demand profiles as the vectors DV wm , DV dw , and DV td indicate for each SA, where each one of their components DV wm (i), DV dw (j), and DV td (k), denote the number of slots that the original demand profiles D wm , D dw , and D td must be rotated to the right to generate a new possibility (in this case, one slot matches one hour, since T = 24). The number of rotated profiles is denoted by d wm , d dw , and d td , respectively, for each SA. Furthermore, these rotated demands have also been associated with each component S wm (i), S dw (j), and S td (k) of the binary decision vectors S wm , S dw , and S td , which represent their states: when the model is solved, these variables may be 1 or 0 and thus this rotated demand will be the final scheduled demand or not. Equation (8) forces the number of binary variables of each decision vector that are equal to 1 and thus the number of cycles.
Equation (9) describes the WH dynamic and regards its thermal inertia as well as parameters such as the instantaneous energy flow with the environment, . Q amb (t), and the energy supplied by the inlet water, . Q in (t) and the heating element, . Q r (t), for each time slot t. Parameters such as ρ (in kg/m 3 ) and C p (in J/kg·K) model essential supply water characteristics like its density and specific heat, while T inlet refers to its average temperature, which is typically computed over a one-month time horizon. The WH design and dynamic also influence the tank capacity and the loss factor C wh (in m 3 ) and g wh (in W/K), respectively. T wh (t) and T wh (t − 1) (in K) are the current and the last value of the water temperature inside the tank. Finally, the user assumes an active role again by selecting the hourly water demand D wt (t) (in m 3 ) and the temperature limits in Equation (10), where the vector T min wh (t) represents the minimum temperature of the water for each hour and T max wh the maximum admissible temperature, both in K. Starting from the user selection, the vector T min wh (t) is generated according to D w (t): if the water demand in t is zero, the minimum temperature matches the T inlet , otherwise, the minimum temperature is set to the temperature selected by the user. where: .
Under this framework, a case of study of a typical dwelling found in residential environments with a PV system of 2 kW and maximum power,P max grid , of 3.6 kW located in Cordoba (Spain) was chosen according to the platform scheme followed. The WH parameters were selected according to specifications that commercial electric water heaters provide for the selected capacity (C wh = 150 L): T min wh and T max wh set at 65 • C and 90 • C, respectively, and g wh equal to the standard value 15 W/K. The inlet water temperature, T inlet , depends on the month of the year and the worst case (6 • C) suggested by the report [26] was selected. Besides these parameters previously fixed, Figure 4a-c shows the demand profiles selected that model the consumption of the common-use SA [27] to obtain 1 h resolution power profiles to be used by LabVIEW. Furthermore, the daily hot water demand (see the purple line in Figure 4d) used in this case study was based on [28], which considers the household usage (i.e., showering, cooking, or dishwashing). The non-shiftable power (red demand of Figure 4d) was obtained by monitoring the active power for a 24-h workday in one of the laboratory circuits. Subsequently, this profile was adapted to be used with the LabVIEW platform, which works with 1-h intervals, by computing the average. A scenario was assumed in which the user scheduled multiple SAs during the day under study, using a tariff with no hourly discrimination.
Electronics 2020, 9, x FOR PEER REVIEW 7 of 15 Under this framework, a case of study of a typical dwelling found in residential environments with a PV system of 2 kW and maximum power, max inlet water temperature, Tinlet, depends on the month of the year and the worst case (6 °C) suggested by the report [26] was selected. Besides these parameters previously fixed, Figure 4a-c shows the demand profiles selected that model the consumption of the common-use SA [27] to obtain 1 h resolution power profiles to be used by LabVIEW. Furthermore, the daily hot water demand (see the purple line in Figure 4d) used in this case study was based on [28], which considers the household usage (i.e., showering, cooking, or dishwashing). The non-shiftable power (red demand of Figure 4d) was obtained by monitoring the active power for a 24-h workday in one of the laboratory circuits. Subsequently, this profile was adapted to be used with the LabVIEW platform, which works with 1h intervals, by computing the average. A scenario was assumed in which the user scheduled multiple SAs during the day under study, using a tariff with no hourly discrimination.  Three SAs were scheduled with only one cycle of operation in this case example showing a 24-h pattern. Specifically, the WM was scheduled within the period 8:00-18:00, TD within 10:00-22:00, and DW to be launched at 13:00 h, which was added to the non-shiftable power described above. With respect to the results, note the relationship between the PV production and the water heater consumption from Figure 4d: at 12:00, the highest power consumption (around 0.6 kW) and the highest generation (around 1.1 kW) took place, showing the strategy followed by the WH, which consisted of increasing the temperature to store energy in high generation periods to be used at peak demand hours, and thus avoid more expensive energy hours due to its thermal inertia. Its Three SAs were scheduled with only one cycle of operation in this case example showing a 24-h pattern. Specifically, the WM was scheduled within the period 8:00-18:00, TD within 10:00-22:00, and DW to be launched at 13:00 h, which was added to the non-shiftable power described above. With respect to the results, note the relationship between the PV production and the water heater consumption from Figure 4d: at 12:00, the highest power consumption (around 0.6 kW) and the highest generation (around 1.1 kW) took place, showing the strategy followed by the WH, which consisted of increasing the temperature to store energy in high generation periods to be used at peak demand hours, and thus avoid more expensive energy hours due to its thermal inertia. Its temperature, shown in Figure 4d, also reached almost the maximum allowed at this time slot, which supports this operation principle. Clearly, Figure 4e shows the SA isolated demand and thus the hours allocated for them, which were the period 10:00-12:00 h for both the WM and the TD, since this time interval entails the highest power consumption of the day, approximately 2.8 kW, and satisfies the user preferences and the DW, which was scheduled in fixed mode, started its operation at 13:00. Through this case, it can be inferred that the platform considers it more suitable to use the available PV production as a more optimum power source than that provided by the grid, even in the cheapest energy hours. Finally, Figure 4f shows the daily profiles of the real-time prices (tariff with no hourly discrimination), and the power taken from the grid (still without ESS) from which the objective function was computed.

Cooperative Storage Management within the Prosumer Nanogrid
The households whose demands are managed are integrated within a nanogrid, which is composed of two neighbor households, among whose loads there are SAs which are managed as in Section 3. The same PV installation and production are assumed for both prosumers and each of them also has battery ESS with a capacity of 6 kWh and a maximum charging/discharging power of ±2 kW ( Figure 5). Generation and initial demand hourly active power of each prosumer are shown in Figure 6a,b. It can be observed that the initial demand of prosumer 1 is the result of demand management performed in the case study of Section 3. A different demand profile is assumed for prosumer 2 to illustrate the storage management. In this final stage of nanogrid energy management, the energy interchange with the main grid is aimed to be minimized. Therefore, the schedule of charging/discharging power of both batteries is performed with this target. supports this operation principle. Clearly, Figure 4e shows the SA isolated demand and thus the hours allocated for them, which were the period 10:00-12:00 h for both the WM and the TD, since this time interval entails the highest power consumption of the day, approximately 2.8 kW, and satisfies the user preferences and the DW, which was scheduled in fixed mode, started its operation at 13:00. Through this case, it can be inferred that the platform considers it more suitable to use the available PV production as a more optimum power source than that provided by the grid, even in the cheapest energy hours. Finally, Figure 4f shows the daily profiles of the real-time prices (tariff with no hourly discrimination), and the power taken from the grid (still without ESS) from which the objective function was computed.

Cooperative Storage Management within the Prosumer Nanogrid
The households whose demands are managed are integrated within a nanogrid, which is composed of two neighbor households, among whose loads there are SAs which are managed as in Section 3. The same PV installation and production are assumed for both prosumers and each of them also has battery ESS with a capacity of 6 kWh and a maximum charging/discharging power of ±2 kW ( Figure 5). Generation and initial demand hourly active power of each prosumer are shown in Figure  6a,b. It can be observed that the initial demand of prosumer 1 is the result of demand management performed in the case study of Section 3. A different demand profile is assumed for prosumer 2 to illustrate the storage management. In this final stage of nanogrid energy management, the energy interchange with the main grid is aimed to be minimized. Therefore, the schedule of charging/discharging power of both batteries is performed with this target. Generation and initial demand hourly power values are collected in 24-element vectors Ppv(t) and PD(t), respectively, with t = 1, 2, …, 24 h. PD vector equals the left part of Equation (3). A new 24element vector PB i (t) is defined to collect the scheduled battery hourly power. When individual scheduling is performed, Ppv(t), PD(t) and PB i (t) correspond to each prosumer. However, if a coordinated operation is performed, Ppv(t) and PD(t) are the sum of prosumers' generation and demand, and PB(t) is composed of 48 elements, i.e., two strings of the 24-hourly power values of each of the batteries, PB i (t). Elements of PB i (t) are the variables to be obtained as a result of the optimization process proposed. Once it has been obtained, a modified demand vector PDmod(t) is calculated with (11). Adopted sign criterion for PB i (t) is positive values when charging and negative values when discharging. Under this criterion, battery power behaves as demanded power, and it can be added to the consumers' initial demand to obtain the modified demand, which better matches the generation profile.
The optimization process tries to find proper values for every PB i (t) vector with the aim of optimizing the balance between generation and modified demand, i.e., minimizing the power in the connection point with the distribution grid at every hour [29]. This target is directly related to the Economic profits are usually the preferred objective function in grid-connected microgrid energy management [3,4]. However, when network tariffs are considered and self-consumption aids are not granted, the proposed objective function presents economic advantages as well as technical ones, as discussed in [30].
The optimization problem is also subjected to several constraints (further explanation in [29]): (i) The state of charge (SoC) of batteries must be kept within a safe operational range. In this work (20%, 100%) was assumed for this range; (ii) The discharging/charging power must not exceed the rated power of the battery's power converter. In this work, maximum discharging and charging power rates were −2 and 2 kW; (iii) With the aim of smoothing batteries' SoC variations, a maximum power gradient of 0.3 kW between consecutive hours was established.
Genetic algorithms (GA) were chosen to search for a proper solution for the optimization process. Although GA are not formally classified as optimization techniques, they have been widely used for energy management purposes, due to their ability to find a global solution even in nonconvex, non-linear, and non-smooth optimization problems, and with either positive or negative values for the variables [29]. Both individual and cooperative operations were performed, to illustrate the advantages of energy sharing in the context of microgrids. The optimization results are depicted in Figure 6, where modified demand, once battery power was added to initial demand, is shown together with the initial demand and generation. It can be observed that both in individual and in a coordinated operation, modified demand better matches the generation profile, thus reducing the remaining power, which must be interchanged with the main grid at each hour.   (13) indices and absolute values of daily imported (Eimp) and exported (Eexp) energy. It can be observed that SC and SS indices increase due to the action of batteries in both individual and cooperative operation. In the case of total energy interchange with the main grid, cooperative scheduling of batteries clearly outperforms the situation without batteries as well as their individual operation. Generation and initial demand hourly power values are collected in 24-element vectors P pv (t) and P D (t), respectively, with t = 1, 2, . . . , 24 h. P D vector equals the left part of Equation (3). A new 24-element vector P B i (t) is defined to collect the scheduled battery hourly power. When individual scheduling is performed, P pv (t), P D (t) and P B i (t) correspond to each prosumer. However, if a coordinated operation is performed, P pv (t) and P D (t) are the sum of prosumers' generation and demand, and P B (t) is composed of 48 elements, i.e., two strings of the 24-hourly power values of each of the batteries, P B i (t).
Elements of P B i (t) are the variables to be obtained as a result of the optimization process proposed.
Once it has been obtained, a modified demand vector P Dmod (t) is calculated with (11). Adopted sign criterion for P B i (t) is positive values when charging and negative values when discharging. Under this criterion, battery power behaves as demanded power, and it can be added to the consumers' initial demand to obtain the modified demand, which better matches the generation profile.
The optimization process tries to find proper values for every P B i (t) vector with the aim of optimizing the balance between generation and modified demand, i.e., minimizing the power in the connection point with the distribution grid at every hour [29]. This target is directly related to the concept of energy autarky, because it aims to maximize both self-consumption (SC) and self-sufficiency (SS) of the nanogrid, thus optimizing the exploitation of the distributed energy resources. The objective function is shown in Equation (12).
Economic profits are usually the preferred objective function in grid-connected microgrid energy management [3,4]. However, when network tariffs are considered and self-consumption aids are not granted, the proposed objective function presents economic advantages as well as technical ones, as discussed in [30].
The optimization problem is also subjected to several constraints (further explanation in [29]): (i) The state of charge (SoC) of batteries must be kept within a safe operational range. In this work (20%, 100%) was assumed for this range; (ii) The discharging/charging power must not exceed the rated power of the battery's power converter. In this work, maximum discharging and charging power rates were −2 and 2 kW; (iii) With the aim of smoothing batteries' SoC variations, a maximum power gradient of 0.3 kW between consecutive hours was established.
Genetic algorithms (GA) were chosen to search for a proper solution for the optimization process. Although GA are not formally classified as optimization techniques, they have been widely used for energy management purposes, due to their ability to find a global solution even in non-convex, non-linear, and non-smooth optimization problems, and with either positive or negative values for the variables [29]. Both individual and cooperative operations were performed, to illustrate the advantages of energy sharing in the context of microgrids. The optimization results are depicted in Figure 6, where modified demand, once battery power was added to initial demand, is shown together with the initial demand and generation. It can be observed that both in individual and in a coordinated operation, modified demand better matches the generation profile, thus reducing the remaining power, which must be interchanged with the main grid at each hour. Table 1 quantifies the results in terms of SC and SS (13) indices and absolute values of daily imported (E imp ) and exported (E exp ) energy. It can be observed that SC and SS indices increase due to the action of batteries in both individual and cooperative operation. In the case of total energy interchange with the main grid, cooperative scheduling of batteries clearly outperforms the situation without batteries as well as their individual operation. SC = 24 t=1 min P Dmod (t), P pv (t) 24 t=1 P pv (t) ; SS = 24 t=1 min P Dmod (t), P pv (t) 24 t=1 P D (t) (13)

Simulation of the Nanogrid
A nanogrid with two prosumers was simulated with Matlab/Simulink ® to validate the performance of the proposed strategy in each prosumer's power converters. The topology of the system was the same in both prosumers and it is depicted in Figure 7. The electric circuit in Figure 7 was modeled using Simulink/Power System Blockset. Switching devices of power converters were insulated gate bipolar transistors (IGBT)/diode pairs controlled by firing pulses produced by a Pulse Width Modulation (PWM) generator. Filters were built with passive elements and consumer load was a constant RL shunt impedance. A lead-acid battery model from the Power System Blockset modeled the storage device.

Simulation of the Nanogrid
A nanogrid with two prosumers was simulated with Matlab/Simulink ® to validate the performance of the proposed strategy in each prosumer's power converters. The topology of the system was the same in both prosumers and it is depicted in Figure 7. The electric circuit in Figure 7 was modeled using Simulink/Power System Blockset. Switching devices of power converters were insulated gate bipolar transistors (IGBT)/diode pairs controlled by firing pulses produced by a Pulse Width Modulation (PWM) generator. Filters were built with passive elements and consumer load was a constant RL shunt impedance. A lead-acid battery model from the Power System Blockset modeled the storage device. The PV installation was assumed to be a current source, tracking its maximum power point (MPP). Two control loops were defined and programmed in the simulation model (by means of Simulink basic blocks and math operations): one for the battery current (which controls the DC/DC converter) and another one for the inverter output current (which generates the switching signals for the DC/AC converter). Both prosumers were connected to each other at the point of common coupling (PCC) bus.
The battery current reference was obtained from the algorithm of Figure 8. A proportionalintegral (PI) controller, with constants KP = 0.4 and KI = 0.008, obtained the first term of the reference current, starting from the error between measured and reference values of the DC-link voltage (tuning guidelines for PI controllers can be found in [31]). Afterwards, once the system was connected to the grid, a second term, obtained from the planned power and the measured voltage of the battery, was added. The PV installation was assumed to be a current source, tracking its maximum power point (MPP). Two control loops were defined and programmed in the simulation model (by means of Simulink basic blocks and math operations): one for the battery current (which controls the DC/DC converter) and another one for the inverter output current (which generates the switching signals for the DC/AC converter). Both prosumers were connected to each other at the point of common coupling (PCC) bus.
The battery current reference was obtained from the algorithm of Figure 8. A proportional-integral (PI) controller, with constants K P = 0.4 and K I = 0.008, obtained the first term of the reference current, starting from the error between measured and reference values of the DC-link voltage (tuning guidelines for PI controllers can be found in [31]). Afterwards, once the system was connected to the grid, a second term, obtained from the planned power and the measured voltage of the battery, was added. Electronics 2020, 9, x FOR PEER REVIEW 11 of 15 Figure 8. Algorithm to obtain the battery current reference.
In this figure, uDC and uDC* are measured and reference values for the DC-link voltage, respectively; PB is the planned power for the battery, obtained from the optimization process described in Section 4; uB is the measured voltage of the battery; iB* is the resulting reference current; and KP and KI are the PI controller constants.
A dead-beat controller was used to obtain the duty cycle for the DC/DC converter that connected the battery to the other elements, as shown in (14) [32]. Switching signals for the converter gates were obtained from this duty cycle by means of a pulse width modulation (PWM) technique.
where dB is the duty cycle for the converter; iB is the measured value of battery current; RB and LB are the resistance and inductance of the filter (RB = 0.3 Ω, LB = 8 mH); and Ts is the sampling period (Ts = 1 × 10 −4 s).
As was previously mentioned, the second control loop tried to track a reference in the output AC current of the inverter.
The reference current iout * was obtained in this paper from the single-phase PQ theory in the αβ reference frame [33]: where P* is the active power output setpoint for the inverter (P* = Ppv -PB), Q* is the reactive power output (Q* = 0) and uPCCα and uPCCβ are the αβ components of the measured voltage in the PCC, uPCC, obtained by means of a Second Order Generalized Integrator-Phase-Locked Loop (SOGI-PLL) [33]. Once the reference current was calculated, a proportional-resonant (PR) controller was used to obtain the modulation signal for the inverter, as shown in Figure 9. This kind of controller is usually used in current controllers when a conversion from αβ to dq stationary frame is not required and, therefore, can be avoided [33]. The modulation signal enabled the switching signals for the gates in the DC/AC converter by means of a sinusoidal pulse width modulation (SPWM) technique.  In this figure, u DC and u DC * are measured and reference values for the DC-link voltage, respectively; P B is the planned power for the battery, obtained from the optimization process described in Section 4; u B is the measured voltage of the battery; i B * is the resulting reference current; and K P and K I are the PI controller constants.
A dead-beat controller was used to obtain the duty cycle for the DC/DC converter that connected the battery to the other elements, as shown in (14) [32]. Switching signals for the converter gates were obtained from this duty cycle by means of a pulse width modulation (PWM) technique.
where d B is the duty cycle for the converter; i B is the measured value of battery current; R B and L B are the resistance and inductance of the filter (R B = 0.3 Ω, L B = 8 mH); and T s is the sampling period (T s = 1 × 10 −4 s).
As was previously mentioned, the second control loop tried to track a reference in the output AC current of the inverter.
The reference current i out * was obtained in this paper from the single-phase PQ theory in the αβ reference frame [33]: where P* is the active power output setpoint for the inverter (P* = P pv − P B ), Q* is the reactive power output (Q* = 0) and u PCCα and u PCCβ are the αβ components of the measured voltage in the PCC, u PCC , obtained by means of a Second Order Generalized Integrator-Phase-Locked Loop (SOGI-PLL) [33]. Once the reference current was calculated, a proportional-resonant (PR) controller was used to obtain the modulation signal for the inverter, as shown in Figure 9. This kind of controller is usually used in current controllers when a conversion from αβ to dq stationary frame is not required and, therefore, can be avoided [33]. The modulation signal enabled the switching signals for the gates in the DC/AC converter by means of a sinusoidal pulse width modulation (SPWM) technique. In this figure, uDC and uDC* are measured and reference values for the DC-link voltage, respectively; PB is the planned power for the battery, obtained from the optimization process described in Section 4; uB is the measured voltage of the battery; iB* is the resulting reference current; and KP and KI are the PI controller constants.
A dead-beat controller was used to obtain the duty cycle for the DC/DC converter that connected the battery to the other elements, as shown in (14) [32]. Switching signals for the converter gates were obtained from this duty cycle by means of a pulse width modulation (PWM) technique.

 
where dB is the duty cycle for the converter; iB is the measured value of battery current; RB and LB are the resistance and inductance of the filter (RB = 0.3 Ω, LB = 8 mH); and Ts is the sampling period (Ts = 1 × 10 −4 s).
As was previously mentioned, the second control loop tried to track a reference in the output AC current of the inverter.
The reference current iout * was obtained in this paper from the single-phase PQ theory in the αβ reference frame [33]: where P* is the active power output setpoint for the inverter (P* = Ppv -PB), Q* is the reactive power output (Q* = 0) and uPCCα and uPCCβ are the αβ components of the measured voltage in the PCC, uPCC, obtained by means of a Second Order Generalized Integrator-Phase-Locked Loop (SOGI-PLL) [33]. Once the reference current was calculated, a proportional-resonant (PR) controller was used to obtain the modulation signal for the inverter, as shown in Figure 9. This kind of controller is usually used in current controllers when a conversion from αβ to dq stationary frame is not required and, therefore, can be avoided [33]. The modulation signal enabled the switching signals for the gates in the DC/AC converter by means of a sinusoidal pulse width modulation (SPWM) technique.  In this figure, i out is the measured output current, and k P and k R (20 and 2000 are the respective values, tuning guidelines for PR controllers can be found in [34]) are the controller constants.
The system was started and connected to the grid, according to the following event sequence: firstly, the battery adjusted the DC-link voltage up to a reference value of 400 V; secondly, the nanogrid was connected to the main grid; finally, the current controller for the DC/AC converter was activated, the PV installation connected, and the reference current for the battery was updated, starting from the planned battery power. Power values assumed for the test were those corresponding to the coordinated scheduling during period 13-14 h (Figure 6c), and they are detailed in Table 2.  Figure 10, the output current of both prosumers' converters is depicted, along with the voltage signal in PCC (this one has been scaled for better visibility). Sinusoidal currents in phase with voltage were obtained in both cases. On the other hand, Figure 11 shows how, after a short transient period since control was activated, the active power output of each converter properly tracked the desired setpoints with a stable behavior.
In this figure, iout is the measured output current, and kP and kR (20 and 2000 are the respective values, tuning guidelines for PR controllers can be found in [34]) are the controller constants.
The system was started and connected to the grid, according to the following event sequence: firstly, the battery adjusted the DC-link voltage up to a reference value of 400 V; secondly, the nanogrid was connected to the main grid; finally, the current controller for the DC/AC converter was activated, the PV installation connected, and the reference current for the battery was updated, starting from the planned battery power. Power values assumed for the test were those corresponding to the coordinated scheduling during period 13-14 h (Figure 6c), and they are detailed in Table 2.  Figure 10, the output current of both prosumers' converters is depicted, along with the voltage signal in PCC (this one has been scaled for better visibility). Sinusoidal currents in phase with voltage were obtained in both cases. On the other hand, Figure 11 shows how, after a short transient period since control was activated, the active power output of each converter properly tracked the desired setpoints with a stable behavior.

Conclusions
In this paper, an EMS for a prosumer nanogrid was defined in three stages. Firstly, a monitoring and data processing technique was proposed as a previous step towards energy forecasting. This forecasting was necessary to perform the following stages, which were based on forecasted energy Electronics 2020, 9, x FOR PEER REVIEW 12 of 15 In this figure, iout is the measured output current, and kP and kR (20 and 2000 are the respective values, tuning guidelines for PR controllers can be found in [34]) are the controller constants.
The system was started and connected to the grid, according to the following event sequence: firstly, the battery adjusted the DC-link voltage up to a reference value of 400 V; secondly, the nanogrid was connected to the main grid; finally, the current controller for the DC/AC converter was activated, the PV installation connected, and the reference current for the battery was updated, starting from the planned battery power. Power values assumed for the test were those corresponding to the coordinated scheduling during period 13-14 h (Figure 6c), and they are detailed in Table 2.  11 show the simulation results. In Figure 10, the output current of both prosumers' converters is depicted, along with the voltage signal in PCC (this one has been scaled for better visibility). Sinusoidal currents in phase with voltage were obtained in both cases. On the other hand, Figure 11 shows how, after a short transient period since control was activated, the active power output of each converter properly tracked the desired setpoints with a stable behavior.

Conclusions
In this paper, an EMS for a prosumer nanogrid was defined in three stages. Firstly, a monitoring and data processing technique was proposed as a previous step towards energy forecasting. This forecasting was necessary to perform the following stages, which were based on forecasted energy

Conclusions
In this paper, an EMS for a prosumer nanogrid was defined in three stages. Firstly, a monitoring and data processing technique was proposed as a previous step towards energy forecasting. This forecasting was necessary to perform the following stages, which were based on forecasted energy production and demand to optimally manage demand and storage. Secondly, a DR technique for scheduling SA in nanogrid households was proposed. By means of an MILP technique, SA demand was shifted and WH was optimally scheduled to minimize the cost of the purchased energy. The last stage dealt with the coordinated management of each ESS with the aim of minimizing the power interchange of the nanogrid with the distribution grid, by means of GA. Results show that the energy balance within the nanogrid and in the interconnection with the main grid was significantly improved, outperforming the generation-demand match and resulting in noticeably higher SC and SS indices. Finally, a simulation test was designed, along with control loops for prosumers' power converters, which validated the ability of converters to track the power setpoints previously obtained.
Previous forecasting strategies based on artificial intelligence tools that introduce energy and power quality issues could have potential for more realistic scenarios considering nanogrids under normal operating conditions.
It is worth noting that although this work was focused on residential prosumer-based nanogrids, the proposed methodology is suitable for EMS of any communities or industrial facilities with DR capability, generation, and ESS. The strength of the method lies in its generalization capability, by using objective functions for the optimization processes, which are applicable to any other energy environment without dependence on economic country policies. The DR process based on splitting the different kinds of consumption devices can be adapted to any other demand scheme, although knowledge of individual demand of devices is required. On the other hand, the battery scheduling method is valid for any other ESS and generation technology, with the aim of improving SC and SS. Economic profit objectives could be also pursued by changing the objective function, although specific economic policy about self-consumption and energy communities must be considered in that case.