{'fraction_non_alphanumeric': 0.040267768707947675, 'fraction_numerical': 0.010348714095426757, 'mean_word_length': 4.307232191408374, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 1, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Stochastic optimal control of a domestic microgrid equipped with solar panel and battery

Microgrids are integrated systems that gather and operate energy production units to satisfy consumers demands. This paper details different mathematical methods to design the Energy Management System (EMS) of domestic microgrids. We consider different stocks coupled together - a battery, a domestic hot water tank - and decentralized energy production with solar panel. The main challenge of the EMS is to ensure, at least cost, that supply matches demand for all time, while considering the inherent uncertainties of such systems. We benchmark two optimization algorithms to manage the EMS, and compare them with a heuristic. The Model Predictive Control (MPC) is a well known algorithm which models the future uncertainties with a deterministic forecast. By contrast, Stochastic Dual Dynamic Programming (SDDP) models the future uncertainties as probability distributions to compute optimal policies. We present a fair comparison of these two algorithms to control microgrid. A comprehensive numerical study shows that i) optimization algorithms achieve significant gains compared to the heuristic, ii) SDDP outperforms MPC by a few percents, with a reasonable computational overhead.


A. Context
A microgrid is a local energy network that produces part of its energy and controls its own demand. Such systems are complex to control, because of the different stocks and interconnections. Furthermore, at local scale, electrical demands and weather conditions (heat demand and renewable energy production) are highly variable and hard to predict; their stochastic nature adds uncertainty to the system.
We consider here a domestic microgrid (see Figure 1), equipped with a battery, an electrical hot water tank and a solar panel. We use the battery to store energy when prices are low or when the production of the solar panel is above the electrical demand. The microgrid is connected to an external grid to import electricity when needed. Furthermore, we model the building's envelope to take advantage of the thermal inertia of the building. Hence, the system has four stocks to store energy: a battery, a hot water tank, and two passive stocks being the building's walls and inner rooms. Two kind of uncertainties affect the system. First, the electrical and domestic hot water demands are not known in advance. Second, the production of the solar panel is heavily perturbed because of the varying nebulosity affecting their production.
We aim to compare two classes of algorithms to tackle the uncertainty in microgrid Energy Management Systems (EMS). The renowned Model Predictive Control (MPC) algorithm views the future uncertainties with a deterministic forecast. Then, MPC relies on deterministic optimization algorithms to compute optimal decisions. The contender -Stochastic Dual Dynamic Programming (SDDP) -is an algorithm based on the Dynamic Programming principle. Such algorithm computes offline a set of value functions by backward induction; optimal decisions are computed online as time goes on, using the value functions. We present a balanced comparison of these two algorithms, and highlight the advantages and drawbacks of both methods.
B. Litterature 1) Optimization and energy management systems: Energy Management Systems (EMS) are integrated automated tools used to monitor and control energy systems. The design of EMS for buildings has raised interest in recent years. In [1], the authors give an overview concerning the application of optimization methods in designing EMS.
The well-known Model Predictive Control (MPC) [2] has been widely used to control EMS. We refer notably to [3], [4], [5] for applications of MPC in buildings. Different solutions are investigated to tackle uncertainties, such as Stochastic MPC [3] or robust optimization [6].
2) Stochastic Optimization: as we said, at local scale, electrical demand and production are highly variable, especially as microgrids are expected to absorb renewable energies. This leads to pay attention to stochastic optimization approaches. Apart from microgrid management, stochastic optimization has found some applications in energy systems (see [7] for an overview). Historically, stochastic optimization has been widely applied to hydrovalleys management [8]. Other applications have arisen recently, such as integration of wind energy and storage [9] or insulated microgrids management [10].
Stochastic Dynamic Programming (SDP) [11] is a general method to solve stochastic optimal control problems. In energy applications, a variant of SDP, Stochastic Dual Dynamic Programming (SDDP), has proved its adequacy for large scale applications. SDDP was first described in the seminal paper [8]. We refer to [12] for a generic description of the algorithm and its application to the management of hydrovalleys. A proof of convergence in the linear case is given in [13], and in the convex case in [14].
With the growing adoption of stochastic optimization methods, new researches aim to compare algorithms such as SDP and SDDP with MPC. We refer to the recent paper [15].

C. Structure of the paper
We detail a modelling of the microgrid in Sect. II, then formulate an optimization problem in Sect. III. We outline the different optimization algorithms in Sect. IV. Finally, we provide in Sect. V numerical results concerning the management of the microgrid.

II. ENERGY SYSTEM MODEL
In this section, we depict the physical equations of the energy system model described in Figure 1. These equations write naturally in continuous time t. We model the battery and the hot water tank with stock dynamics, and describe the dynamics of the building's temperatures with an electrical analogy. Such physical model fulfills two purposes: it will be used to assess different control policies; it will be the basis of a discrete time model used to design optimal control policies.

A. Load balance
Based on Figure 1, the load balance equation of the microgrid writes, at each time t: We now comment the different terms. In the left hand side of Equation (1), the load produced consists of • the production of the solar panel φ pv (t), • the importation from the network f ne (t), supposed nonnegative (we do not export electricity to the network).
In the right hand side of Equation (1), the electrical demand is the sum of • the power exchanged with the battery f b (t), • the power injected in the electrical heater f t (t), • the power injected in the electrical hot water tank f h (t), • the inflexible demands (lightning, cooking...), aggregated in a single demand d el (t).

B. Energy storage
We consider a lithium-ion battery, whose state of charge at time t is denoted by b(t). The state of charge is bounded: (2) Usually, we set b = 30% × b so as to avoid empty state of charge, which proves to be stressful for the battery. The battery dynamics is given by the differential equation with ρ c and ρ d being the charge and discharge efficiency and f b (t) denoting the power exchange with the battery. We use the convention f + = max(0, f ) and f − = max(0, −f ).
As we cannot withdraw an infinite power from the battery at time t, we bound the power exchanged with the battery:

C. Electrical hot water tank
We use a simple linear model for the electrical hot water tank dynamics. At time t, we denote by T h (t) the temperature inside the hot water tank. We suppose that this temperature is homogeneous, that is, that no stratification occurs inside the tank.
At time t, we define the energy h(t) stored inside the tank as the difference between the tank's temperature T h (t) and a reference temperature T ref where V h is the tank's volume, c p the calorific capacity of water and ρ the density of water. The energy h(t) is bounded: The enthalpy balance equation writes where • f h (t) is the electrical power used to heat the tank, satisfying • d hw (t) is the domestic hot water demand, • β h is a conversion yield. A more accurate representation would model the stratification inside the hot water tank. However, this would greatly increase the number of states in the system, rendering the numerical resolution more cumbersome. We refer to [16] and [17] for discussions about the impact of the tank's modeling on the performance of the control algorithms.

D. Thermal envelope
We model the evolution of the temperatures inside the building with an electrical analogy: we view temperatures as voltages, walls as capacitors, and thermal flows as currents. A model with 6 resistances and 2 capacitors (R6C2) proves to be accurate to describe small buildings [18]. The model takes into account two temperatures: • the wall's temperature θ w (t), • the inner temperature θ i (t). Their evolution is governed by the two following differential equations where we denote • the power injected in the heater by f t (t), • the external temperature by θ e (t), • the radiation on the wall by Φ ext (t), • the radiation through the windows by Φ int (t). The time-varying quantities θ e (t), Φ int (t) and Φ ext (t) are exogeneous. We denote by R i , R s , R m , R e , R v , R f the different resistances of the R6C2 model, and by c i , c m the capacities of the inner rooms and the walls. We denote by γ the proportion of heating dissipated in the wall through conduction, and by (1 − γ) the proportion of heating dissipated in the inner room through convection.

III. OPTIMIZATION PROBLEM STATEMENT
Now that we have described the physical model, we turn to the formulation of a decision problem. We aim to compute optimal decisions that minimize a daily operational cost, by solving a stochastic optimization problem.

A. Decisions are taken at discrete times
The EMS takes decisions every 15 minutes to control the system. Thus, we have to provide decisions in discrete time.
We set ∆ = 15mn, and we consider an horizon T 0 = 24h. We adopt the following convention for discrete processes: for t ∈ {0, 1, · · · , T = T0 ∆ }, we set x t = x(t∆). That is, x t denotes the value of the variable x at the beginning of the interval [t∆, (t + 1)∆[. Otherwise stated, we will denote by

B. Modeling uncertainties as random variables
Because of their unpredictable nature, we cannot anticipate the realizations of the electrical and the thermal demands. A similar reasoning applies to the production of the solar panel. We choose to model these quantities as random variables (over a sample space Ω). We adopt the following convention: a random variable will be denoted by an uppercase bold letter Z and its realization will be denoted in lowercase z = Z (ω). For each t = 1, . . . , T , we define the uncertainty vector modeled as a random variable. The uncertainty W t takes value in the set W t = R 3 .

C. Modeling controls as random variables
As decisions depend on the previous uncertainties, the control is a random variable. We recall that, at each discrete time t, the EMS takes three decisions: taking values in U t = R 3 . Then, between two discrete time indexes t and t + 1, the EMS imports an energy F ne t+1 from the external network. The EMS must fulfill the load balance equation (1) whatever the demand D el t+1 and the production of the solar panel Φ pv t+1 , unknown at time t. Hence F ne t+1 is a recourse decision taken at time t + 1. The load balance equation (1) now writes as where P − a.s. indicates that the constraint is fulfilled in the almost sure sense. Later, we will aggregate the solar panel production Φ pv t+1 with the demands D el t+1 in Equation (13), as these two quantities appear only by their sum.
The need of a recourse variable is a consequence of stochasticity in the supply-demand equation. The choice of the recourse variable depends on the modeling. Here, we choose the recourse F ne t+1 to be provided by the external network, that is, the external network mitigates the uncertainties in the system.

D. States and dynamics
The state becomes also a random variable It gathers the stocks in the battery B t and in the electrical hot water tank H t , plus the two temperatures of the thermal envelope (θ i t , θ w t ). Thus, the state vector X t takes values in X t = R 4 .
The discrete dynamics writes where f t corresponds to the discretization of the continuous dynamics (10) using a forward Euler scheme, that is, By doing so, we suppose that the control u t and the uncertainty w t+1 are constant over the interval [t, t + ∆[. The dynamics (15) rewrites as an almost-sure constraint: We suppose that we start from a given position x 0 , thus adding a new initial constraint: X 0 = x 0 .

E. Non-anticipativity constraints
The future realizations of uncertainties are unpredictable. Thus, decisions are functions of previous history only, that is, the information collected between time 0 and time t. Such a constraint is encoded as an algebraic constraint, using the tools of Probability theory [19]. The so-called non-anticipativity constraint writes where σ(U t ) is the σ-algebra generated by U t and F t = σ(W 1 , · · · , W t ) the σ-algebra associated to the previous history (W 1 , . . . , W t ). If Constraint (17) holds true, the Doob lemma [19] ensures that there exists a function π t such that This is how we turn an (abstract) algebraic constraint into a more practical functional constraint. The function π t is an example of policy.

F. Bounds constraints
By Equations (2) and (6), the stocks in the battery B t and in the tank H t are bounded. At time t, the control F b t must ensure that the next state B t+1 is admissible, that is, b ≤ B t+1 ≤ b by Equation (2), which rewrites, Thus, the constraints on F b t depends on the stock B t . The same reasoning applies for the tank power F h t . Furthermore, we set bound constraints on controls, that is, (20) Finally the load-balance equation (13) also acts as a constraint on the controls. We gather all these constraints in an admissible set on control U t depending on the current state X t :

G. Objective
At time t, the operational cost L t : X t × U t × W t+1 → R aggregates two different costs: First, we pay a price p e t to import electricity from the network between time t and t + 1. Hence, electricity cost is equal to p e t × F ne t+1 . Second, if the indoor temperature is below a given threshold, we penalize the induced discomfort with a cost p d t × max(0, θ i t − θ i t ), where p d t is a virtual price of discomfort. The cost L t is a convex piecewise linear function, which will prove important for the SDDP algorithm.
We add a final cost K : X T → R to ensure that stocks are non empty at final time T where κ is a positive penalization coefficient calibrated by trials and errors. As decisions U t and states X t are random, the costs L t (X t , U t , W t+1 ) become also random variables. We choose to minimize the expected value of the daily operational cost, yielding the criterion yielding an expected value of a convex piecewise linear cost.

H. Stochastic optimal control formulation
Finally, the EMS problem translates to a generic Stochastic Optimal Control (SOC) problem Problem (25) states that we want to minimize the expected value of the costs while satisfying the dynamics, the control bounds and the non-anticipativity constraints.

IV. RESOLUTION METHODS
The exact resolution of Problem (25) is out of reach in general. We propose two different algorithms that provide policies π t : X 0 × W 1 × · · · × W t → U t that map available information x 0 , w 1 , . . . , w t at time t to a decision u t .

A. Model Predictive Control (MPC)
MPC is a classical algorithm commonly used to handle uncertainties in energy systems. At time t, it considers a deterministic forecast (w t+1 , . . . , w T ) of the future uncertainties (W t+1 , . . . , W T ) and solves the deterministic problem min (ut,··· ,u T −1 ) x j+1 = f j x j , u j , w j+1 , (26b) At time t, we solve Problem (26), retrieve the optimal decisions (u t , . . . , u T −1 ) and only keep the first decision u t to control the system between time t and t + 1. Then, we restart the procedure at time t + 1.
As Problem (26) is linear and the number of time steps remains not too large, we are able to solve it exactly for every t.
where µ of t+1 is a (offline) probability distribution on W t+1 . Once these functions are computed, we compute a decision at time t as a state-feedback: where µ on t+1 is an online probability distribution on W t+1 . This method proves to be optimal when the uncertainties W 1 , . . . , W T are stagewise independent and when µ on t = µ of t is the probability distribution of W t in (27).
2) Description of Stochastic Dual Dynamic Programming: Dynamic Programming suffers from the well-known curse of dimensionality [11]: its numerical resolution fails for state dimension typically greater than 4 when value functions are computed on a discretized grid. As the state X t in §III-D has 4 dimensions, SDP would be too slow to solve numerically Problem (25). The Stochastic Dual Dynamic Programming (SDDP) can bypass the curse of dimensionality by approximating value functions by polyhedral functions. It is optimal for solving Problem (25) when uncertainties are stagewise independent, costs L t and K are convex and dynamics f t are linear [14].
SDDP provides an outer approximation V k t of the value function V t in (27) with a set of supporting hyperplanes Each iteration k of SDDP encompasses two passes.
• During the forward pass, we draw a scenario x 0 , . . . , w k T of uncertainties, and compute a state trajectory x k t t=0···T along this scenario. Starting from position x 0 , we compute x k t+1 in an iterative fashion: i) we compute the optimal control at time t using the available V k t+1 function where f t is given by (15). • During the backward pass, we update the approximated value functions V k t t=0,··· ,T backward in time along the trajectory x k t t=0,··· ,T . At time t, we solve the problem Otherwise stated, SDDP only explores the state space around "interesting" trajectories (those computed during the forward passes) and refines the value functions only in the corresponding space regions (backward passes).
3) Obtaining online controls with SDDP: in order to compute implementable decisions, we use the following procedure.
• Approximated value functions V t are computed with the SDDP algorithm (see §IV-B2). These computations are done offline. • The approximated value functions V t are then used to compute online a decision at any time t for any state x t . More precisely, we compute the SDDP policy π sddp t by π sddp t (x t ) ∈ arg min which corresponds to replacing the value function V t+1 in Equation (28) with its approximation V t+1 . The decision π sddp t (x t ) is used to control the system between time t and t + 1. Then, we resolve Problem (32) at time t + 1.
To solve numerically problems (30)-(31)-(32) at time t, we will consider distributions with finite support w 1 t , . . . , w S t . The offline distribution µ of t+1 now writes: where δ w s t+1 is the Dirac measure at w s t+1 and (p 1 , . . . , p S ) are probability weights. The same reasoning applies to the online distribution µ on t+1 . For instance, Problem (32) reformulates as V. NUMERICAL RESULTS A. Case study 1) Settings: we aim to solve the stochastic optimization problem (25) over one day, with 96 time steps. The battery's size is 3 kWh, and the hot water tank has a capacity of 120 l. We suppose that the house has a surface A p = 20 m 2 of solar panel at disposal, oriented south, and with a yield of 15%. We penalize the recourse variable F ne t+1 in (22) with on-peak and off-peak tariff, corresponding toÉlectricité de France's (EDF) individual tariffs. The building's thermal envelope corresponds to the French RT2012 specifications [21]. Meteorological data comes from Meteo France measurements corresponding to the year 2015.
2) Demands scenarios: we have scenarios of electrical and domestic hot water demands at 15 minutes time steps, obtained with StRoBe [22]. Figure 2 displays 100 scenarios of electrical and hot water demands. We observe that the shape of these scenarios is consistent: demands are almost null during night, and there are peaks around midday and 8 pm. Peaks in hot water demands corresponds to showers. We aggregate the production of the solar panel Φ pv and the electrical demands D el in a single variable D el to consider only two uncertainties (D el t , D hw t ).  3) Out of sample assessment of strategies: to obtain a fair comparison between SDDP and MPC, we use an out-ofsample validation. We generate 2,000 scenarios of electrical and hot water demands, and we split these scenarios in two distinct parts: the first N opt scenarios are called optimization scenarios, and the remaining N sim scenarios are called assessment scenarios. We made the choise N opt = N sim = 1, 000.
First, during the offline phase, we use the optimization scenarios to build models for the uncertainties, under the mathematical form required by each algorithm (see Sect. IV). Second, during the online phase, we use the assessment scenarios to compare the strategies produced by these algorithms. At time t during the assessment, the algorithms cannot use the future values of the assessment scenarios, but can take advantage of the observed values up to t to update their statistical models of future uncertainties.
B. Numerical implementation 1) Implementing the algorithms: we implement MPC and SDDP in Julia 0.6, using JuMP [23] as a modeler, StochDynamicProgramming.jl as a SDDP solver, and Gurobi 7.02 [24] as a LP solver. All computations run on a Core i7 2.5 GHz processor, with 16Go RAM.
2) MPC procedure: Electrical and thermal demands are naturally correlated in time [25]. To take into account such a dependence across the different time-steps, we chose to model the process W 1 , . . . , W T with an auto-regressive (AR) process.
a) Building offline an AR model for MPC: we fit an AR(1) model upon the optimization scenarios (we do not consider higher order lag for the sake of simplicity). For i ∈ {el, hw}, the AR model writes Once the forecast (w t+1 , . . . , w T ) is available, it is fed into the MPC algorithm that solves Problem (26).
3) SDDP procedure: even if electrical and thermal demands are naturally correlated in time [25], the SDDP algorithm only relies upon marginal distributions. a) Building offline probability distributions for SDDP: rather than fitting an AR model like done with MPC, we use the optimization scenarios to build marginal probability distributions µ of t that will feed the SDDP procedure in (30)-(31).
We cannot directly consider the discrete empirical marginal probability derived from all N opt scenarios, because the support size would be too large for SDDP. This is why we use optimal quantization to map the N opt optimization scenarios to S representative points. We use a Loyd-Max quantization scheme [26] to obtain a discrete probability distribution: at each time t, we use the N opt optimization scenarios to build a partition Ξ = (Ξ 1 , · · · , Ξ S ), where Ξ is the solution of the optimal quantization problem where w s t = 1 card(Ξs) w i t ∈Ξs w i t is the so-called centroid of Ξ s . Then, we set for all time t = 0, · · · , T the discrete offline distributions µ of t = S s=1 p s δ w s t , where δ w s t is the Dirac measure at point w s t and p s = card(Ξ s )/N opt is the associated probability weight. We have chosen S = 20 to have enough precision. b) Computing value functions offline: then, we use these probability distributions as an input to compute a set of value functions with the procedure described in §IV-B2.
c) Using the value functions online: once the value functions have been computed by SDDP, we are able to compute online decisions with Equation (33) 1 . SDDP, on the contrary of MPC, does not update the online probability distribution µ on t during assessment to consider the information brought by the previous observations. 4) Heuristic procedure: we choose to compare the MPC and SDDP algorithms with a basic decision rule. This heuristic is as follows: the battery is charged whenever the solar production Φ pv is available, and discharged to fulfill the demand if there remains enough energy in the battery; the tank is charged (F h t > 0) if the tank energy H t is lower than H 0 , the heater F t t is switched on when the temperature is below the setpoint θ i t and switched off whenever the temperature is above the setpoint plus a given margin.

C. Results
1) Assessing on different meteorological conditions: we assess the algorithms on three different days, with different meteorological conditions (see Table I). Therefore, we use three distinct sets of N sim assessment scenarios of demands, one for each typical day. These three different days corresponds to different heating needs. During Winter day, the heating is maximal, whereas it is medium during Spring day and null during Summer day. The production of the solar panel varies accordingly.
2) Comparing the algorithms performances: during assessment, we use MPC (see (26)) and SDDP (see (32)) strategies to compute online decisions along N sim assessment scenarios. Then, we compare the average electricity bill obtained with these two strategies and with the heuristic. The assessment results are given in Table II: means and standard deviation σ are computed by Monte Carlo with the N sim assessment scenarios; the notation ± corresponds to the interval ±1.96 which is a 95% confidence interval. We observe that MPC and SDDP exhibit close performance, and make better than the heuristic. If we consider mean electricity bills, SDDP achieves better savings than MPC In addition, SDDP achieves better savings than MPC for the vast majority of scenarios. Indeed, if we compare the difference between the electricity bills scenario by scenario, we observe that SDDP is better than MPC for about 93% of the scenarios. This can be seen on Figure 3 that displays the histogram of the absolute gap savings between SDDP and MPC during Summer day. The distribution of the gap exhibits a heavy tail that favors SDDP on extreme scenarios. Similar analyses hold for Winter and Spring day. Thus, we claim that SDDP outperforms MPC for the electricity savings. Concerning the performance on thermal comfort, temperature trajectories are above the temperature setpoints specified in §III-G for both MPC and SDDP.
In term of numerical performance, it takes less than a minute to compute a set of cuts as in §IV-B2 with SDDP on a particular day. Then, the online computation of a single decision takes 1.5 ms on average, compared to 0.5 ms for MPC. Indeed, MPC is favored by the linearity of the optimization Problem (26), whereas, for SDDP, the higher the quantization size S, the slowest is the resolution of Problem (32), but the more information the online probability distribution µ on t carries.  3) Analyzing the trajectories: we analyze now the trajectories of stocks in assessment, during Summer day. The heating is off, and the production of the solar panel is nominal at midday. Figure 4 displays the state of charge of the battery along a subset of assessment scenarios, for SDDP and MPC. We observe that SDDP charges earlier the battery at its maximum. On the contrary MPC charges the battery later, and does not use the full potential of the battery. The two algorithms discharge the battery to fulfill the evening demands. We notice that each trajectory exhibits a single cycle of charge/discharge, thus decreasing battery's aging. Figure 5 displays the charge of the domestic hot water tank along the same subset of assessment scenarios. We observe a similar behavior as for the battery trajectories: SDDP uses more the electrical hot water tank to store the excess of PV energy, and the level of the tank is greater at the end of the day than in MPC. This analysis suggests that SDDP makes a better use of storage capacities than MPC.

VI. CONCLUSION
We have presented a domestic microgrid energy system, and compared different optimization algorithms to control the stocks with an Energy Management System.
The results show that optimization based strategies outperform the proposed heuristic procedure in term of money savings. Furthermore, SDDP outperforms MPC during Winter and Summer day -achieving up to 35% costs savings -and displays similar performance as MPC during Spring day. Even if SDDP and MPC exhibit close performance, a comparison scenario by scenario shows that SDDP beats MPC most of the time (more than 90% of scenarios during Summer day). Thus, we claim that SDDP is better than MPC to manage uncertainties in such a microgrid, although MPC gives also good performance. SDDP also makes a better use of storage capacities.
Our study can be extended in different directions. First, we could mix SDDP and MPC to recover the benefits of these two algorithms. Indeed, SDDP is designed to handles the uncertainties' variability but fails to capture the time correlation, whereas MPC ignores the uncertainties' variability, but considers time correlation by means of a multistage optimization problem. Second, we are currently investigating the optimization of larger scale microgrids -with different interconnected buildings -by decomposition methods.