A heuristic method to calculate the capacity of residential PV-BESS in providing upward flexibility services in energy communities

This paper proposes a heuristic method for calculating the capacity of a set of residential photovoltaic-battery systems in providing upward flexibility services to the grid in an energy communities framework. The proposed method has been designed to calculate the upward service capacity in a few minutes, assuming a scenario where the grid operator urgently needs an upward service in a specific area. The proposed method calculates the service capacity by exploiting the PV overgeneration and the state of charge of batteries, adopting a distributed approach. If the service capacity varies relevantly over time, a centralized approach is considered allowing the service capacity to remain constant over time. An algorithm is provided that implements the proposed heuristic method that can be easily translated into a software code and solved even in the absence of specific skills and expensive high-level computational tools, i.e. using cost-effective single-board computers. The main benefits and advantages of the proposed method are due to its applicability in real-time problems and to its simplicity which makes it easy to be translated into software code and solved even in the absence of specific skills and high-level computational tools. Therefore, it is a simple and advantageous solution, especially for small energy communities. The numerical results demonstrate the effectiveness of the proposed method and algorithm, studying a set of four residential photovoltaic-battery systems and real input data. For this test case, the algorithm returns a flat service capacity of approximately 8 kW which remains perfectly constant for 1-hour. Lastly, the performance of the proposed heuristic method is compared with the solution of two optimization problems aiming at the same scope.

and CEC, are similar however there are significant differences; for example, members of a REC must be located in the proximity of the renewable energy projects that are owned/developed by the REC itself but this constraint does not apply to CECs. Furthermore, a REC allows the production, consumption and selling of renewable energy to all energy sectors; on the contrary, a CEC limits these activities to the electricity sector only. ECs, regardless of whether CECs or RECs, are a modern reorganization of local energy systems to integrate distributed energy resources [1]; a reorganization that plays a strategic role [2] to help the EU in the transition process towards sustainable and renewable energy [3]; the relevance of the role of ECs is confirmed by the fact that directive 2019/944/EU allows energy communities to manage the electricity distribution networks in the relevant area if this is necessary to allow the birth and development of these modern reorganizations. Citizen involvement in energy issues and ECs themselves is crucial [4]; in this sense, many efforts are today devoted to showing ordinary people how desirable it is to abandon the position of individuals who manage their own distributed generation to become part of an ENCO [5]. Along this path, studies on social acceptability [6] and institutional preconditions [7] are also underway through extensive surveys and the comprehensive analysis quantifying citizens' potential to co-finance and participate in community renewable energy initiatives across Europe [8]. ECs tend to be local communities; this is because the better adaptation to the legal and regulatory frameworks [9] and the ecosystems diversity [10], the better management of the energy needs and energy consumption as in the case of an urban neighbourhood [11] or a municipality [12], [13].
The benefits of citizens participating in ECs are manifold; a distinction can be made by drawing a line that distinguishes between economic benefits and non-economic benefits. For example, participating in ECs allows access to consumption management services that empower members of the community, show them current consumption patterns, and suggest greater awareness to potentially reduce overall consumption. The electricity bill decreases but, in this situation, it is a welcome by-product; the primary benefit is not of an economic type, it is the empowerment of the consumer and the exploitation of energy resources in respect of the environment which are among the main motivations of citizens for participation in these communities [14]. On the contrary, economic benefits derive from direct sharing and peer-to-peer (P2P) electricity trading in the internal market of the community between producers, consumers, and selfconsumers [15], [16]. Underlying these modern reorganizations is a key concept and that is energy communities handle and commercialize flexibility in both internal and external electricity markets. In the internal market, flexibility is used to increase collective self-consumption to minimize costs for imported and acquired energy on external markets or to aggregate demand and shift it when external spot markets offer lower prices. By reducing imported energy, they also reduce the costs for the electricity grids and the collective connection capacity, up to achieving independence from the rest of the electricity system and creating independent virtual power plants. Further economic benefits can be achieved when the internal market also includes non-residential users since the latter provide different and complementary energy consumption/management profiles concerning residential users, so enhancing communities' self-sufficiency [17].
In the external market, flexibility becomes services to electricity grids. Thanks to directive 2019/944/EU, energy communities have the right to access these markets through aggregators; participating in flexibility mechanisms such as balancing, ancillary services, etc. the community maximizes the total income.

A. Related works
Research results in the available literature have already evaluated the potential of ECs to provide services to the grid. For example, the model proposed in [18] and developed in Python determines the operation strategy of a pool of batteries, installed at both residential and utility levels, to ensure optimal economic benefit while stacking ancillary services as Frequency Containment Reserve and peak shaving between 5 pm and 8 pm. A four-week simulation is performed adopting the IEEE European low voltage test feeder -solved via OpenDSS -and 44 consumers having a 4 kWp PV on the rooftop. Similarly, a two-stages stochastic method based on a Mixed-Integer Linear Programming (MILP) optimization model is used in [19] ] for the optimal operation of a local energy community to participate in providing manual frequency restoration reserve (mFRR). The case study consists of 50 households, distributed 100kW PV systems, a centralized 50 kW/200k Wh Vanadium Redox Flow battery, and 10 electric vehicles.
The mFRR is the grid service also provided by the energy community in [20] through six battery storage dispatch strategies for residential and commercial photovoltaic-battery systems (PV-BESSs). The case study consists of 48 households and 42 commercial buildings. In contrast, Ref. investigated the participation of an ENCO in the automatic frequency reset reserve (aFRR) market in Germany and analyses the influence of aFRR calls (point in time, magnitude, and duration) on battery operations and aging. Besides a 10kW photovoltaic plant and a 10kW/10kWh battery storage system, each household belonging to the ENCO is also mounted with a 100kW thermal heat pump and 300 liters buffer storage. Numerical results show that the delivery of an aFRR service of 1kW for 4 hours returns an income of 13 cent€/kWh per household.. The multi-energy community in [22], comprising electrothermal resources and storage systems (thermal storage, batteries, gas boilers, etc.), participates in both energy and reserve markets. The case study consists of 50 households situated in the north of England. A similar multi-energy community is presented in [23] where the authors propose a day-ahead scheduling strategy for the participation in the joint Energy and ancillary service markets; the proposed strategy is tested on a real regional multi-energy system, including industrial, commercial, and residential areas, 3km away from each other. Much larger is the energy community in [24] where a non-linear stochastic method based on a MILP optimization model optimally operates residential photovoltaic-battery systems for the provision of upward and downward regulation in the ancillary services market. The study consists of 2000 residential users, with 3-6 kWp PV systems and 6-9 kWh battery systems. How to mitigate the ramp rate of the system's net load as reported by the California Independent System Operator is the challenge discussed in Ref. [25]; the ENCO provides flexibility to the grid operator by modifying the power exchanged with the electricity grid in a range between 1.5 and 5kW. For this purpose, a MILP is used to model the flexibilityconstrained energy management of a set of households, each equipped with a 4kW photovoltaic system and a 3kW-5kWh battery storage system. In addition, a load-shifting strategy schedules washing machines, dishwashers, spin dryers, and vacuum cleaners with the minimum cost while a robust optimization approach models the uncertainty of energy market price. The implementation of flexible resources and the aggregation of resources for flexibility in the framework of energy communities raise several technical and practical issues that certainly can be solved but undertaking an economic commitment that is probably not compatible with the real context of small or local ENCO when consisting mainly of residential users.
As an example, let us consider an ENCO of residential PV-BESSs as the one shown in Fig. 1, the control of these distributed energy resources requires a Home Energy Management System (HEMS) installed at each home. Being in the context of a community, the HEMS left the maximization of the individual self-consumption and begins the cooperation with the community's members to maximize the collective self-consumption and to participate in flexibility markets. To this end, the HEMS has necessarily to be able to exchange data and information, especially with the aggregator [26], [27] implementing the most modern technologies such as smart contracts and Blockchain, [28], [29] or 5G [30]. Besides the HEMS measures the power flow to the meter [31], [32] and it governs the charge/discharge of the batteries sending set points to the ac/dc converter. These three functionalitiescommunication, measurement, and control -are likely basic requirements for the member's participation in an ENCO. Besides this, it would be desirable that the HEMS has its own computational resource, to solve simple algorithms autonomously; by doing so, the HEMS is not a simple gateway, totally dependent on the aggregator for any decision about the management of powers behind the meter, rather it can support the aggregator in the more complex management of the entire ENCO. Moreover, implementing and solving optimization models for the optimal operation of an aggregation of a hundred prosumers requires a complex infrastructure of computational and communication resources as well as a continuous flow of information such as electricity market prices, transmission/distribution system operator service auctions, weather, and demand forecasts, etc. Cloud-based platforms [33] have consequently become a key element of the energy community concept and an important cost factor that impacts the economic feasibility of ECs. Cloud platforms represent the communication, monitoring, and control systems necessary for the normal operation of ECs and the exploitation of the flexible resources distributed within the ECs themselves, replicating the fundamental role of communication systems for the VPPs [34] and smart grids in general [35]. A clear example of the sophisticated set of processes and devices, useful for the implementation of flexible resources and the aggregation of resources for flexibility, is provided in [36]. In this paper the author presents a performance analysis of a commercial VPP communication system providing mFRR ancillary service by aggregating two DERs, a refinery facility and a paper mill plant, to obtain a flexible capacity of 30 MW. The paper also provides important information on the IEC 60870-5-104 protocol used for the exchange of VPP operational data, thus highlighting that this type of infrastructure and communication system protocols cannot be applied to ECs with residential users as it would obviously be too expensive.
In conclusion, on the one hand, accessing the ancillary service markets through an aggregator is a right for the energy communities. The grid operators are also aware that the ECs participation is of vital importance as distributed energy resources, without coordination and control, can cause reverse power flows and increase the bus voltages and line currents, up to causing blackouts, imposing costly reinforces of both network equipment and electrical lines [37].

B. Article Contribution
From the perspective of small operators and their respective local energy communities, optimization models present in the literature might be so complex to require the adoption of expensive commercial tools. For example, optimal coordinating the charge/discharge of a hundred residential batteries in as many housing every 5 minutes for an entire day requires designing and solving mixed non-linear optimization problems with tens of thousands of decision variables or, in an equivalent way, staff with specific knowledge and skills and high-level modeling software for mathematical optimization (eg. GAMS, CPLEX, etc). The personnel/software combination may require energy communities to incur high costs, not sufficiently balanced by savings and government subsidies. For this reason, this paper does not propose any programming optimization model, but it proposes a heuristic method for calculating practically the capacity of a set of residential PV-BESSs in providing upward flexibility services in the framework of ECs, exploiting the over generation and the battery charge but avoiding the load curtailment. The proposed method is a simple, intuitive, and inexpensive solution for technical-practical issues for small ECs; in fact, it can be easily translated into software code and solved even in the absence of specific skills and high-level computational tools. The proposed heuristic method has been designed to calculate the upward service capacity in a few minutes (e.g. 5 minutes), assuming a scenario where the grid operator, the distribution system operator (DSO), or the transmission system operator (TSO), urgently needs an upward service in the specific area where the small ENCO is located. Although several research contributions in the available literature consider the potential of ECs in providing services to the grid, as per the author's knowledge, the proposed heuristic method in the context of flexibility services and ECs is new. A mixed-integer linear model of a typical residential PV-BESSs is used in combination with the proposed heuristic method. The latter is divided into six steps and procedures; the pseudocode of each procedure is provided in the paper. Implementing and solving this combination does not require any complex infrastructure of computational resources and the use of cost-effective single board computers is compatible with the application. Besides, the flow of information between the aggregator and the PV-BESSs is non-continuous and contains only the service capacities of PV-BESSs and any corrections adopted by the aggregator; further information such as electricity market prices, bids for auctions, and measured values of state variables are not required. Two are the service capacities returned by the proposed method where the first is time-varying while the second capacity is flat and remains constant over the considered time interval. The flat capacity may better capture the interest of a potential buyer, i.e. the grid operators, and provide the ECs with more chances to sell the upward service. Thus, to sum up, the contribution of the paper, it's worth highlighting that: • a simple and intuitive heuristic method is proposed as a solution for technical-practical issues for small ECs, designed to calculate the upward service capacity in a few minutes (e.g. 5 minutes) • the proposed method can be easily translated into software code and solved even in the absence of specific skills and high-level computational tools, i.e. using costeffective single-board computers • the proposed method calculates the service capacity by exploiting the PV overgeneration and the state of charge of batteries of each prosumer, individually; in this case, the proposed method allows the application of a distributed approach • when the service capacity calculated above varies so relevantly over time to compromise the interest of the potential purchaser (i.e. the DSO / TSO), the proposed method applies a centralized approach that returns a service capacity that remains constant over time. • the proposed method can be effectively used for real-time applications even in the presence of limited computing capacity. Although this paper focuses on a small ENCO, the proposed algorithm is also feasible for large communities, with hundreds and hundreds of residential PV-BESS; this is because all the steps that comprise the proposed algorithm are very easy to calculate even in the presence of so many residential photovoltaic-battery systems. The paper is organized as follows: Section 2 presents the mixed-integer linear model of a typical residential PV-BESS; Section 3 presents the proposed algorithm to calculate the capacity of residential PV-BESS in providing upward flexibility services in an ECs framework; Section 4 presents a numerical experiment on a set of four residential PV-BESS and real data, so to test the efficiency of the proposed algorithm as a valid and feasible solution for technicalpractical issues even for small energy communities. Conclusions and future aims end this paper.

II. THE MIXED-INTEGER LINEAR MODEL FOR A RESIDENTIAL PV-BESS
This section describes the mixed-integer linear model of a typical residential PV-BESS. Model inputs are the PV generation , ( ) and the load demand , ( ); model outputs are the power flow at the meter , ( ), the power flow and the state of charge of the batteries, , ( ) and ( ). Model constraints operate the batteries considering the balance between PV generation and load demand therefore the batteries charge during an over generation and discharge during an under generation. In so doing, individual self-consumption is maximized. The model of the PV-BESS, hereinafter named Model(t), is the following: ,

( ) Local
Step 2 calculating the service capacity exploiting the BESS charge , ( ) Local Step 3 flattening the PV service capacity ̅ , ( ) Local Step 4 flattening the BESS service capacity ̅ , ( ) Local Step 5 joining unflatten BESS service capacities ̅ , ( ) Cloud Step 6 final ENCO service capacity -Cloud The constraint in (1) indicates whether an over-generation or an under generation is currently taking place; being M1 the largest value of a difference between the PV power and the load demand, the binary variable 1 equals 1 in case of over generation and it is 0 in case of under generation. In the case of over generation, the battery power is positive, it is also lower or equal to the over generation in (2) and greater or equal to zero in (3). In the case of under generation, the power of batteries is lower or equal to zero in (2) and it is greater or equal to the under generation in (3). Consequently, the state of charge of the batteries ( ) updates in (4) where the power of the batteries , ( ), the length of time interval ∆ and the nominal capacity of the batteries , are multiplicated by the efficiency coefficient c for a charging process if 1 equals 1 or by the efficiency d of a discharging process if 1 equals 0. The power of the PV-BESS at the meter, , ( ), is calculated in (5) whereas the direction of such a power flow is calculated in (6); since M2 is the greatest value of this power, the binary variable 2 equals 1 when the power flows from the PV-BESS to the electricity grid and it equals 0 vice versa. So, , ( ) and , ( ) in (7) and (8) are the power exported and imported by the PV-BESS from the electricity grid, respectively. The constraint in (9) set that the power of batteries does not exceed the rated power; the coefficient m = 1, 2,… takes into account those batteries which can be recharged with a current exceeding the rated value. Finally, the constraint in (10) set the state of charge of the batteries within a min-max range. In the next section, the author uses the PV-BESS model illustrated above in the framework of an ENCO where the PV-BESS participates to provide upward services to the grids; to this end, the author modifies one of the model's inputs that is the load demand. For example, let us suppose that the upward service consists in increasing the power that the PV-BESS exports to the grid of the desired quantity; in this case, the author adds such a desired quantity to the input load demand therefore the model reduces/stops charging the batteries or discharges them largely.

III. THE PROPOSED METHOD FOR CALCULATING THE CAPACITY FOR AN UPWARD GRID SERVICE
This section describes the heuristic method proposed by the author to calculate the capacity of a set of residential PV-BESS to provide an upward service to the grid in the context of ECs. The upward service capacity is here defined as the maximum power that a single PV-BESS, or a set of these systems, may export to the distribution grid for a certain time interval, e.g. one hour. The proposed algorithm comprises 6 steps as reported in Tab. I. Steps 1 and Step 2 calculate the upward service capacity of a single PV-BESS; in particular, in Step1 the service capacity , ( ) is calculated by exploiting the power of the PV generator that exceeds the load demand (i.e. the overgeneration) while in Step2 the service capacity , ( ) is calculated by exploiting the state of charge of batteries. The service capacity of the single PV-BESS is the sum of the two VOLUME XX, 2017 9 capacities calculated above, that is ( ) = , ( ) + , ( ); similarly, the service capacity of the entire ENCO is the sum of all PV-BESS capacities. Since such an ENCO service capacity may vary relevantly over time, the interest of the potential purchaser (i.e. the DSO/TSO) might be compromised. For this reason, steps 3 and 4 flatten the previous capacities and return service capacities, ̅ ( ) = ̅ , ( ) + ̅ , ( ), which remains constant over time.
Step 5 collects those service capacities that remained unflatten, it combines and joins them together to obtain flat service capacities ̅ , ( ) again. Step6 ends the proposed method, communicating the TSO/DSO the final ENCO service capacity. It is important to note that all steps from 1 to 4 can be performed locally by each PV-BESS; on the contrary, steps 5 and 6 are necessarily performed by the aggregator. All the steps are explained in detail below.
Step 1: service capacity exploiting the PV over generation, , ( ) Let us consider Fig. 2a where the black line plots the difference between the PV generation and the load demand of a certain PV-BESS; at time t=start such a difference equals 2kW therefore an over-generation is in progress. This difference slowly decreases and then drops abruptly to zero at =̂0, then it decreases below zero to indicate an under generation. Consistently, the black line in Fig. 2b plots the corresponding SOC of batteries; it increases in the range from a) b) FIGURE 2. Over generation, service capacities and state of charge of batteries start and ̂0 because the over-generation charges the batteries while it decreases from ̂0 to end because the batteries feed the load. The following Procedure 1 calculates the capacity of a PV-BESS for an upward service exploiting the abovementioned over-generation Procedure 1: capacity for an upward service exploiting the over generation (flowchart of this procedure is reported in Appendix A) The FOR loop in (1) scrolls the index t from start to end; in case of over generation, the condition in (2) is fulfilled therefore the service capacity , ( ) is set equal to the over generation in (3); else, the service capacity is set equal to zero in (5). The PV generation is consequently updated in (7) by subtracting the service capacity and the model of the PV-BESS is solved in (8) to calculate the state of charge of the batteries, useful for the next loop, i.e. the time t+1. When the over-generation is exploited so to create a service capacity, the black line of Fig. 2a is replaced by the dashed line traced in the same figure; the dashed line is equal to zero from start to ̂0 since no over generation exists anymore, then it overlaps the black line up to t=end. The corresponding SOC of batteries is in Fig. 2b where the dashed line remains flat and equal to zero from start to ̂0 because the PV generation equals the load demand; from ̂0 to end, it descends because the batteries feed the load. At t=end, the state of charge is about 38%.
Step 2: service capacity exploiting the charge of batteries, , ( ) Procedure 3 reported below calculates the capacity for an upward service exploiting the charge of the batteries; to this end, the load demand is repeatedly increased by the small quantity ∆ so to force the batteries to discharge at rated power and until the minimum value of SOC. Procedure 2 is: Procedure 2: capacity for an upward service exploiting the charge of the batteries (flowchart of this procedure is reported in Model(t; end) 8 ENDWHILE 9 NEXT 10 FOR t= start TO end 11 The first FOR loop in (1) saves a copy of the load demand in a temporary variable in (2). The second FOR loop in (4) increases the load demand so to force the batteries to discharge at the rated power. Such an increase is applied while the condition in (5) is fulfilled that is a) the difference between the PV generation and the load demand is lower than the rated power of batteries and b) the state of charge of batteries at time t=end is greater or equal to SOCmin. The increase of load demand is in (6), it is a constant value and equals ∆. The model of the PV-BESS is simulated in (7) from the current time and to t=end. The third FOR loop in (10) calculates the service capacity in (11) as the difference between the load demand and the temporary variable. The fourth FOR loop in (13) resets the load demand to the original value in (14). The example case illustrated in Fig. 2 includes this Step 2, exploiting the SOC left by Step 1. In particular, the grey line in Fig. 2a is the PV generation minus the load demand and minus the two service capacities returned by Steps1 and this Step2. This grey line is negative from start to ̂0 because the load increase of this Spet2 has induced an under generation; after ̂0 the grey line overlaps the two lines. Consistently, the grey line of Fig. 2b plots the corresponding SOC of the batteries; in the time interval from start to ̂0 , the grey line linearly decreases as the batteries discharge at rated power, then it decreases with a slope equal to the other two lines. At t=end, the state of charge is almost zero.
Substituting a variable service capacity , ( ) for a flat one ̅ , ( ) needs a check. This is because the variable capacity exploits the entire over generation therefore the batteries remain in stand-by mode or have no role; on the contrary, the flat capacity exploits only a part of the over-generation therefore the batteries charge or discharge -as far as possible -to keep the service capacity close to the desired flat value. For example, the continuous line in Fig. 3a trace the service capacity , ( ) as returned by Step1 whereas the continuous line in Fig. 3b trace and the corresponding state of charge of the batteries , ( ). Such a state of charge remains unchanged from to ̂2 because Step1 has entirely converted the over-generation into a service capacity. After ̂2 , the over-generation ends, the service capacity goes to zero, and the state of charge decreases because the batteries feed the load demand.  ) and ̅ , ( ) is the part of the over-generation which no longer participates in the service capacity. Such a part now recharges the batteries therefore the state of charge increases from the start to ̂1 when it reaches the maximum value, i.e. ̅ , (̂1) = , max . After the time ̂1 , batteries are full therefore the over-generation which no longer participates in service capacity is necessarily exported to the grid, so causing a deviation , ( ) of the service capacity concerning the desired value that lasts up to ̂2 . After ̂2 , the over-generation is zero and the service capacity equals the desired value again; from this time onwards, the batteries quickly discharge because they feed the load demand and also provide the entire service capacity. The following procedure 3 verifies the presence of a deviation , ( ) of the flat service capacity concerning the desired value; to this aim, the power flow at the meter, , ( ), is calculated in the absence (baseline) and the presence of the service capacity. Procedure 3 is: The first FOR loop in (1) saves a copy of the load demand (2) and the power flow at the meter (3) in two temporary variables. The second FOR loop in (5) modifies the load demand in (6) by adding the flat service capacity and simulates the PV-BESS model in (7). So the power flow at the meter is compared with the original value plus the service capacity in (8); in the absence of deviations, the error , ( ) is set equal to zero in (9) or equal to the deviation in (11). All deviations, if any, are delivered to the next Step4 to compensate them as much as possible. Finally, the load demand is set to the original value in (13).
Step 4: flattening the service capacity exploiting the batteries charge, ̅ , ( ) The service capacity , ( ) calculated in Step2 varies over time, now this capacity is flattened so that it remains constant -or flat-and equal to the mean value: Substituting a variable service capacity , ( ) for a flat one ̅ , ( ) needs a check. This is because the variable capacity operates the batteries at rated power, avoiding the load curtailment; on the contrary, the flat service capacity considers multiple factors (e.g, the deviations calculated in Step 3) therefore the operation of the batteries is more sophisticated than previous, as illustrated below. For example, the continuous and the dashed lines of Fig. 4a plot the variable capacity , ( ) and the flat capacity ̅ , ( ), respectively; the latter remains constant and equal to the desired value from start to ̂3 , then it reduces up to ̂4 . The sag of ̅ , ( ) in ̂3 ÷̂4 is due to the increase of the load demand; such a sag cannot be locally resolved by the PV-BESS, this sag is delivered to Step5 and solved by the aggregator. On the other hand, this Step4 achieves an important result: the operation of the batteries compensates for the deviations , returned by Step3 from ̂1 to ̂2that is the light-grey area of Fig. 4a. Indeed, the batteries profile , ( ) traced in Fig. 4b is close to zero from start to ̂1 as the batteries export power to provide the service capacity on one side and they import the over-generation that Step2 has not exploited so to maintain the service capacity flat on the other side. Similarly, the batteries profile remains close to zero from ̂2 to ̂3 because the batteries continue to export power to provide the service capacity on one side and they import power to compensate for , on the other side. Then the batteries profile exceeds the service capacity so indicating that the load demand is increasing. At time ̂3 , , ( ) reaches the maximum value that is , ( ) = , , therefore the further increase of the load demand in the range ̂3 ÷̂4 causes an equal decrement in the service capacity. The following procedure 4 verifies the possibility to replace the variable service capacity , ( ) with the corresponding flat service capacity ̅ , ( ); to this aim, the power flow at the meter,  The first FOR loop in (1) saves a copy of the load demand and the grid profile in two temporary variables in (2) and (3) respectively. The second FOR loop in (5) updates the load demand in (6) by adding the flat service capacity and the deviations calculated in Step3; then, the model of the PV-BESS is simulated in (t). The new grid profile is compared with the original value in (8) therefore in the absence of deviation the error ,Batt ( ) is set equal to zero in (9) or equal to the deviation in (11). The so-calculated error ,Batt ( ) is delivered to the next Step5 where the aggregator joins those unflatten service capacities, attempting to obtain further flat capacities. Lastly, the load demand is set to the original value in (13).
Step 5: joining unflatten service capacities, ̅ , ( ) At the end of Step 4, each PV-BESS communicates its service capacity to the aggregator. In the best scenario, all service capacities are flat; in other scenarios, some capacities contain errors i.e. they are not perfectly flat. For example, Fig. 5 shows two unflatten service capacities, ̅ , ( ) and ̅ , ( ), sent by the i-th and j-th PV-BESSs. In this Step5 the aggregator collects the unflatten capacities in a set named  and performs a further investigation, trying to combine these capacities to obtain flat service capacities, as described below. For example, the two unflatten service capacities, ̅ , ( ) and ̅ , ( ), shown in Fig. 5a form a couple; since the minimum of ̅ , ( ) is greater than the minimum of ̅ , ( ) then index i precedes index j in . This couple is now used to form a joined service capacity named ̅ , ( ). To this end, the dotted line in Fig. 5a is the sum of the unflatten service capacities; the minimum value is about 1.55 kW and it is also the value of the joined service capacity. In fact, 1.55 kW coincides with the constant value of the dashed line in Fig. 5b which is the joined service capacity ̅ , ( ). Finally, the joined service capacity has to be divided into two contributions, one for the i-th PV-BESS and one for the j-th PV-BESS. These two contributions are plotted in Fig. 5b and named ̅ , * ( ) and ̅ , * ( ), respectively; the symbol * distinguishes these contributions from the previous ones ̅ , ( ) and ̅ , ( ). The following procedure 5 calculates the joined service capacity and the contributions of each PV-BESS: The Bubblesort function in (1) applies the well-known sorting algorithm where the position of each couple of adjacent capacities in  is reversed if the minimum of the first capacity is lower than the minimum of the second capacity. Once the sort is complete, the FOR loop in (2) creates a joinedcombined -service capacity from each couple; the value of the joined capacity is set in (3) equal to the minimum of the sum of the two capacities forming the couple. The IF statement divides the joined capacity into two contributions, favouring the index i over index j since the i-th service capacity ̅ , ( )is greater than the j-th capacity ̅ , ( ). Hence, if the condition in (4) is fulfilled then the contribution for the ith PV-BESS is set equal to the joint capacity in (5) whereas the contribution for the j-th PV-BESS is set equal to zero in (6); otherwise the contribution for the i-th PV-BESS remains equal to the previous value in (8) whereas the contribution for the j-th PV-BESS is set to the balance in (9).

Step 6: final decision
The aggregator has concluded Step5 combining couples of unflatten service capacities to obtain a joined and flat service capacity from each couple; in this Step6 the aggregator communicates to the PV-BESSs their respective contributions in case of success or their exclusion from the service otherwise. The aggregator also calculates the upward service capacity of the ENCO summing the service capacities of PV-BESSs that have been admitted to the service. Lastly, the aggregator communicates to the DSO/TSO the upward service capacity of the ENCO.

IV. THE CASE STUDY AND THE NUMERICAL EXPERIMENTS
In this section, the case study for the energy community is performed. The results are based on real data from four energy meters captured with a 3-minute temporal resolution. Finally, a comparison between flatten and unflatten service capacities for the investigated community is presented. The case study of this paper is illustrated in Fig. 6. Four modern houses are connected to the distribution grid, and they are equipped with a PV-BESS and a home energy management system (HEMS). The latter supervises the main local power flows; first and foremost is the power flow at the meter. Each HEMS communicates with an aggregator because the ENCO under investigation aims to provide upward service to the grid. The aggregator is the intermediary between the ENCO and the grid operators, i.e. the DSO and TSO. The aggregator coordinates the community's members along with their PV-BESSs in serving the grid. In line with this, the numerical experiments presented in this Section recreate a scenario where the grid operator, DSO or TSO, urgently needs an upward grid service. At this scope, the rapid data exchange conceptually shown in Fig. 7 is considered. So, the DSO/TSO sends an urgent query to the aggregator (see label A in Fig. 7) which represents the ENCO sited into the specific geographical area where the service is needed. The DSO/TSO asks the aggregator for the maximum capacity for a constant upward service for one hour. The aggregator has to reply within a very short time, e.g. five minutes, and it is also aware that, in case of acceptance by the DSO/TSO, the upward service must be activated fast as well, e.g. 5 minutes. The aggregator promptly interrogates the HEMSs (see label B in Fig. 7) which calculate their capacity for an upward service, applying the procedures from Steps1 to Step4 illustrated in Section III. The aggregator receives the service capacities from all HEMSs (see label C in Fig. 7) and it applies the procedure in Step5. Finally, the aggregator executes Step6, communicating to the PV-BESSs their contributions or their exclusion from the service and reports to the DSO/TSO the ENCO capacity (see label D in Fig. 7). The numerical experiments illustrated in this section are carried out using the power flows plotted in Fig. 8, captured with a 3minute temporal resolution at the meters of four real users.

A Calculating the capacity for the upward service
Let us consider a request for an upward service from 14:00 to 15:00; each HEMS applies the procedures from Steps1 to Step4 considering the technical data and the state of charge of batteries reported in Tab. II, and PV generation and load demand forecasts reported in Tab. III. Worth noting that the variation of solar radiation has not been considered; PV generation forecast is assumed to be error-free. This assumption can be considered valid since the PV generation forecast is performed 5 minutes before the time interval from 14:00 to 15:00 on a sunny day.
The difference between the PV generation and load demand from 14:00 to 15:00 for all HEMSs is in Fig. 9a while the corresponding SOC of the batteries is shown in Fig. 9b. A label with the numbers from 1 to 4 is placed close to each line to indicate to which HEMS the line refers.

STEP1 AND STEP 2
For HEMS1, the difference between the PV generation and the load demand in Fig. 9a is negative from 14:00 to 15:00 therefore Step1 returns a service capacity 1, ( ) equal to zero; so this service capacity is not visible in Fig. 10a. Consistently, the SOC of the batteries in Fig. 10b coincides with the SOC in the absence of service in Fig. 9b. On the other hand, 1 (15: 00) is 44% therefore HEMS1 concludes that a service capacity may exist exploiting the energy stored in the batteries. And in fact, at Step2 HEMS1 discharges the batteries as fast as possible and a service capacity 1, ( ) is achieved. This capacity is illustrated in Fig. 11a, it is about 1.5kW at 14:00 and decreases very slowly up to 14:45 when it falls quickly due to an increase in load demand. The corresponding SOC is illustrated in Fig. 11b, 1 ( ) decreases linearly from about 90% to 17% approximately, thereby confirming that Step 2 operates the batteries at the rated power, i.e. 1, ( ) = 1, , for the entire time interval. For HEMS2, the difference between the PV generation and load demand in Fig. 9a is positive and it is approximately 1kW for the entire time interval from 14:00 to 15:00; the SOC of the batteries increases from 63% to 82% as in Fig. 9b. The HEMS2 concludes that a service capacity may be obtained by exploiting both the over generation and the state of charge of the batteries. And in fact, Step 1 converts the entire over generation into a service capacity while the state of charge remains constant and equal to 63% as shown in Fig. 10a and  10.b, respectively; soon after, Step 2 discharges the batteries as quickly as possible, thus obtaining a 3kW service capacity from 14:00 to 14:50 when 2 (14: 50) equals zero as in Fig.  10b.  For HEMS3, Fig. 9a shows that a 3kW over generation occurs from 14:00 to about 14:15, then it drops to zero in about five minutes; in the same time interval, the state of charge of the batteries increases from about 45% to about 68%, then it remains almost constant up to 15:00. So, Step 1 converts the entire over generation and the entire charge of batteries into a service capacity as shown in Fig. 10a and Fig. 11a, respectively. For HEMS4, Fig. 9a shows a negligible over generation therefore negligible is the corresponding service capacity 4, ( ) in Fig. 10a; on the contrary, 4 (14: 00) in Fig.  10b is almost 100% and it remains unchanged until 14:30 when the load demand discharges the batteries to 80%. Therefore, this Step 2 returns a service capacity 4, ( ) of about 3kW from 14:00 to 14:30 when it decreases to 1.2kW and returns to 3kW at about 15:00. Worth noting that 4 ( ) in Fig. 10b decreases linearly to zero so demonstrating that also Step 4 operates the batteries at the rated power.  All the service capacities as returned by Steps 1 and 2 are shown in Fig. 12, overlapped to each other; the white-coloured areas represent the upward service capacity , ( ) obtained by the use of the over generation while the grey-coloured areas represent the upward service capacities ,Batt ( ) obtained by the use of the energy stored in the batteries. Worth remember that the capacity 1, ( ) is not visible in Fig. 12 as it is zero. The upward service capacity of the entire energy community is the sum of users' capacities, and it coincides with the topmost line in Fig. 12

STEP 3 AND STEP 4
The upward service capacities ̅ ,PV ( ) and ̅ ,Batt ( ) as returned by Step 3 and Step 4 are illustrated in Fig. 13a and Fig. 13b, respectively. For HEMS1, Step 3 does not yield any useful results as ̅ 1,PV ( ) was null; Step 4 also fails the attempt to flatten ̅ 1,Batt ( ) as the sudden increase in the load demand at 14:50 -which already conditioned Step 2 -also affects this Step 4 so reducing ̅ 1,Batt ( ) to zero. For HEMS2, both Step 3 and Step 4 conclude successfully. The service capacity Before concluding this section, let us examine Fig. 14; the profiles of the batteries during Step3 and Step4 are plotted in Fig. 14a and Fig. 14b, respectively. These two figures provide a clear idea -or confirm -the fundamental role of the batteries energy storage systems in providing the upward service capacities illustrated above in this section.

STEP 5
The four HEMSs communicate their upward service capacities to the aggregator. Since the attempts of both HEMS1 and HEMS4 to flatten their respective service capacities have partially failed, the aggregator saves these unflatten capacities, ̅ 1, ( ) and ̅ 4, ( ), in the set , it calculates the minimum of each capacity and sorts the set  by decreasing values. These two capacities, shown again in Fig. 15a for sake of simplicity, form a couple, now used to form a joined and constant service capacity. To this end, the dotted line in Fig. 11a is the sum of these two capacities; the minimum value of the dotted line is about 2.88 kW and it is the constant value of the joined service capacity 1, ( ). Figure 11b illustrates such a joined capacity along with the contributions, ̅ 1, * ( ) and ̅ 4, * ( ), for HEMS1 and HEMS4, respectively.

STEP 6
In this final step, the aggregator communicates to HEMS1 and HEMS4 their capacities as modified in Step5 and confirms to HEMS2 and HEMS3 their service capacities since they do not belong to the set . All service capacities are shown in Fig.  16, overlapped each other. The white-coloured areas represent the upward service capacities that exploit the over generation while the grey-coloured areas represent the upward service capacities that exploit the energy stored in the batteries. The service capacity of the energy community is the topmost line of Fig. 16; it is perfectly flat, it is 7.80 kW and it remains unchanged for all the time from 14:00 to 15:00. The aggregator communicates this service capacity to the DSO/TSO and waits for a positive reply.

B. A comparison between flatten and unflatten service capacities
At the end of Step 1 and Step 2, the average capacity of the ENCO in providing an upward service is 9.85kW, as reported in the first row of Tab. IV. All HEMSs participate in the service, the contributions vary within the range where the minimum is 11.22% for the HEMS1 and the maximum is 34.56% for HEMS2. The batteries participate relevantly in the service as they provide 78.37% of the energy required for the service itself. At the end of Steps3 and Step4, the average capacity of the ENCO has changed, it decreased from 9.85 kW to 7.80 kW (-20.88%), as reported in the second row of Tab. IV. The contributions of HEMSs also changed in comparison to the previous ones; for example, the participation of HEMS1 has decreased by about 68.91%, on the contrary, the participation of HEMS2 has increased by 9.21%. The participation of the batteries in the upward service slightly decreased by 2.86%. Finally, Fig. 17 illustrates how the meter profiles of the four users vary due to the upward service in the time interval from 14am to 15am. The dotted line refers to the case in which no service is provided (the profile for the whole day is shown in Fig. 8) while the continuous line refers to the upward service provided to the grid operator.

C. Validation of the proposed heuristic method
Performance of the proposed heuristic method is now compared with the solution of two optimization problems aiming at the same scope, to quantify the eventual benefits and drawbacks. The first optimization problem is the optimized version of Step 1 and Step 2 of the proposed heuristic method to calculate the service capacity of each user exploiting the PV over generation and the BESS charge, separately. The second optimization problem is the optimized version of Step 3, Step 4, and Step5 of the proposed heuristic method to calculate the service capacity of the energy community and flattening this service capacity.
The two optimization problems are as follows: OPTIMIZATION PROBLEM #1: The object function is: , exp( ) . The constraints are: equations of the mixed-integer linear model for a residential PV-BESS of Section 2. This optimization problem is executed for each user individually, that is it is executed four times; each run of this problem maximizes the power exported to the electricity grid by each user therefore it returns the upward service capacity of user1, user2, user3, and user4 as if they operated independently of each other, that is 1 ( ), ; the average value ̅ serv ( ) of this sum will be the expected value of the flat service capacity offered by the user community and, for this reason, it is an input for optimization problem #2. The decision variables are the charge/discharge powers , ( ) of each user's BESS.

OPTIMIZATION PROBLEM #2:
The object function is: ) 2 . The constraints are: equations of the mixed-integer linear model for a residential PV-BESS of Section 2. This optimization problem is executed only one time and includes all four users together. The problem finds the optimal combination of charge/discharge of the batteries to obtain the greatest / flat service capacity. To this end, the authors assume that the largest / flattest value of this service capacity is ̅ serv ( ) ie the average value of the sum of the users' service capacity when calculated separately (see optimization problem #1); therefore the objective function minimizes the square deviation between the average value ̅ serv ( ) and the power exported to the electricity grid by the four users. Users now operate as members of a community. The decision variables of the problem are the charge/discharge power , ( ) of BESSs, all together. Figure 17 shows the users' service capacities as returned by optimization problem # 1. All the service capacities are overlapped to each other; the whitecolored areas represent the upward service capacity , ( ) obtained exploiting the over-generation while the gray-colored areas represent the upward service capacities ,Batt ( ) obtained exploiting the energy stored in the batteries. These results returned by optimization problem #1 are very similar to those returned from Steps 1 and 2 of the proposed heuristic method and shown in Fig. 12. Indeed, the average value of users' capacities as calculated via the proposed method is 9.58kW whereas that calculated by optimization problem # 1 is 9.25kW, so confirming the effectiveness of Steps 1 & 2 of the proposed method. Figure 18 shows instead the flatten service capacity of the energy community as returned by optimization problem #2; such a capacity equals 9.25kW and the quadratic offset value is nearly zero. So, flatten service capacity of optimization problem #2 is 15.67% greater than the one of proposed heuristic method (i.e. 7.80kW) so confirming the goodness of Steps 3, 4, and 5, of the proposed heuristic method. The high similarity between the results returned by the proposed method and the optimization problems is also evident when focusing on batteries operation. In this sense, Fig. 19 shows the users' batteries operation as returned by Steps 1 and 2 of the proposed method and the optimization problem # 1. Batteries operations for User1 and User4 coincide perfectly in both cases, regardless of whether the proposed method or the optimization problem # 1 is adopted. Conversely, batteries' operation for User2 and User3 are different from each other, but the hourly average values are perfectly identical. Similarly, Fig. 20 shows the users' batteries operation as returned by Steps 1, 2 and 3, of the proposed method and the optimization problem #2. Batteries' operations for User2 and User3 suggest that the proposed method is equivalent to optimization problem#2. For example, the proposed method discharges the batteries of user 2 at a constant power of 2.5kW for the entire time interval while optimization problem # 2 applies lower power values in the first 20 minutes and power values close to 2.5kW for the rest of the time. The opposite applies for users 1 and 4 since the batteries, discharge calculated by optimization problem #2 is greater than that computed by the proposed method. These worse performances of the proposed method concerning the optimization problem #2 are certainly to be attributed to Step 5 of the proposed method; in this Step5 the two capacities of User 1 and User 4 are used to form a joined/flatten service capacity; the value of this flatten capacity is set to the minimum of the sum of the two capacities and this precautionary choice (i.e., adopt the minimum) is penalizing for the proposed method. If the number of users participating in the energy community is sufficiently high, it could be assumed that users who provide a service capacity below an assigned threshold are discarded in order not to penalize the entire aggregate.

V DISCUSSION
In this article the methodology for method for calculating the capacity of a set of residential photovoltaic-battery systems in providing upward flexibility services in the framework of energy communities. The essential steps were defined using pseudo-code provided for each step from 1 to 5 and step 6 as decision making. Such approach helps to understand how easy is the application of the proposed method, so much so that the use of cost-effective single board computers is compatible with the application. The efficiency of the proposed method as a valid and feasible solution for technical-practical issues even for small energy communities was tested through numerical experiments; the test case is a set of four residential photovoltaic-batteries systems together with their real 3minute profiles captured at meters. The proposed method was applied assuming that the DSO/TSO urgently needs an upward service for one hour and the proposed method returns a perfectly flat capacity equal to 7.80 kW. The flatten service capacity is lower than the average time-variable service capacity, the difference is one fifth and it is a non-negligible reduction; on the other hand, such a reduction is a justified cost if, in exchange, the flatten service capacity captures the interest of the TSO/DSO and the activation of the service. Performance of the proposed heuristic method was compared to the solution of two optimization problems aiming at the same scope, to quantify the benefits and drawbacks. These optimization problems are the optimized version of Steps 1 and 2, and Steps 3, 4, and 5, of the proposed heuristic method. Results returned by the first optimization problem are very similar to those returned by the proposed heuristic method indeed the average value of users' capacities are 9.25kW and 9.58kW, respectively, so confirming the effectiveness of Steps 1 & 2 of the proposed method. Similarly, the flatten service capacity of the energy community as returned by optimization problem #2 is 15.67% greater than the one of the proposed heuristic method so confirming the goodness of Steps 3, 4, and 5, of the proposed heuristic method. Lastly, the proposed method has been tested on a small energy community but is easily applied to even larger communities with hundreds and hundreds of residential photovoltaicbattery systems. This is because all the steps, including Step 5 where the aggregator combines the remaining unflatten service capacities, are very easy to calculate even in the presence of such many residential photovoltaic-battery systems.
Generally under this investigation the uncertainty in power systems were not considered [38]. In the investigated local energy communities the uncertainties of PV production and load could be included and solved by e.g. information gap decision theory [39], [40], stochastic programming [41] or robust optimization [42].

V CONCLUSION AND FUTURE AIMS
This paper proposed a method for calculating the capacity of a set of residential photovoltaic-battery systems in providing upward flexibility services in the framework of energy communities. The proposed method is composed of six steps. The indicated steps are as follows: • the first two steps calculate a time-variable service capacity by exploiting the over generation and the charge of the batteries, • the third and fourth steps flatten the time-variable service capacity to obtain a service capacity that remains constant over a considered time interval, • the fifth step combines those service capacities that have remained unflatten to obtain further constant service capacities, • the sixth step calculates the capacity of the energy community and communicates it to the DSO/TSO. A first and immediate goal for the future is to study how to redistribute the grid service between the photovoltaic-battery systems, assuming the sudden interruption of communication between the aggregator and one or more of these systems. The lack of communication even for few minutes is an important common problem for energy communities in practice that can cause the non-delivery of a part of the committed service and, depending on the extent and duration of the outage, the imposition of penalties. Additionally for future also uncertainties will be considered during investigation.

APPENDIX A
The following figures illustrate the flowcharts of procedures from 1 to 5, illustrated in Section II.