The Role of Flexibility in Photovoltaic and Battery Optimal Sizing towards a Decarbonized Residential Sector

: The ambitious environmental goals set by the 2030 Climate Target Plan can be reached with a strong contribution coming from the residential sector and the exploitation of its ﬂexibility, intended as the capacity of a building to shift its consumption to maximize the use of renewable energy. In the literature, the impact of ﬂexibility has been mainly studied for the optimization of the control logic, assuming that the photovoltaic system and the electric storage have already been installed. Conversely, in this work, we adopt a different perspective that analyses the system from the designer point of view. Different scenarios with a variable degree of ﬂexibility have been created and tested in a residential district considering various demand proﬁles (i.e., home appliances, heat pumps, and electric vehicles consumption). The proﬁles have been then used as input for an optimization tool that can design the optimal system according to a speciﬁc target function. Firstly, the system has been optimized according to economic indicators. However, results suggested that adopting only an economic perspective in the design phase could lead to results that are not in line with the European environmental targets. Thus, the system has been optimized also considering energy indicators to design a system that could give a relevant contribution to the energy transition of the residential sector. Results suggest that demand ﬂexibility coupled with storage can boost the installation of photovoltaic systems due to the improved economic proﬁtability and at the same time guarantee a relevant contribution to the decarbonization of the sector.


Introduction
In the 2030 Climate Target Plan, the European Commission updated the target for reduction of greenhouse gas (GHG) emissions compared to the levels of 1990 by 2030, 55% compared to the 40% of the previous plan. To achieve the given target, it is fundamental to accelerate the energy transition through a massive increase of renewable energy sources (RES), but also energy efficiency and the electrification of the heating and transport sectors. In recent years, the penetration of RES into the electricity system has rapidly increased with a global photovoltaic (PV) installed capacity of 710 GW and 689 GW of wind in 2020 [1]. The recast Renewable Energy Directive 2018/2001/EU requires that at least 32% of the energy demand will be supplied by RES by 2030 [2]. However, both solar and wind energy have intrinsic variability that can affect the reliability of the electricity grid when the penetration is significantly high. For this reason, it is important to decrease the mismatch between the generation and the demand, either by shifting generation (e.g., using storage) or by making the demand flexible to RES generation and grid requirements [3].
A key role in this sense can be played by the building sector. As stated in many reports, currently, the building sector accounts for 30-40% of the global energy consumption [4] (i.e., space heating or domestic hot water, cooling, ventilation, pumps, lighting, or appliances demand). This share represents a significant potential because part of these loads may be shifted, in time becoming flexible. Indeed, conventionally energy retrofitting scenarios are mainly focused on cost-effective energy-saving, without taking into consideration the effects of the flexibility and electrification of heating/cooling as studied in Mancini et al. [5]. In the scientific literature, the concept of "Energy Flexible Building" has been defined according to the context or the target community [6]. However, a significant contribution to a uniform definition has been undertaken in the program "Energy in Building and Communities" (EBC) of the International Energy Agency (IEA) in the project "Annex 67" (IEA EBC ANNEX 67) [7]. The works performed in Annex 67 not only contribute to properly define the concept of energy flexible building, but also to collect proper indices able to evaluate this property. A different and interesting perspective is to see energy flexibility "as the capacity of a building to react to one or more forcing factors to minimize CO 2 emissions and maximize the use of RES" [8]. This point of view links the definition of flexibility with the need to exploit PV systems in building applications through selfconsumption. Currently, due to scalability, modularity, low maintenance cost, and long lifetime, photovoltaic systems are widely installed in both residential and commercial buildings to supply their demand. Particularly profitable is the case when generation and consumption are simultaneous (as in commercial application [9]) where the ratio between the photovoltaic energy directly consumed on-site and produced (i.e., self-consumption) is close to 100%. In some European Countries, the match of generation and consumption not only favors the renewable energy sources (RES) exploitation, but also the reduction of the energy drawn from the power grid, which corresponds to reduce CO 2 emissions.
In residential buildings, conversely from commercial ones, the management of photovoltaic overproduction at a given time is more challenging because only part of the household demands are in the daily hours, while a not negligible part of the consumption is concentrated in the morning or evening when the solar irradiation is low or absent. For this reason, several methods have been proposed to optimize the exploitation of photovoltaic systems and can be arranged in three groups [10]. The first possible solution is to directly inject the generation surplus into the grid. This is the simplest solution, which can be advantageous only under net-metering or net-billing schema, where there is remuneration for each kWh fed into the grid and subsequently consumed at a different time. However, even in this case (i.e., in net-billing schemes) the profitability is not so high because the cost of electricity sold is always lower than the cost of energy bought, so the larger is the difference, the lower the benefits for the users are [11]. The second option is to use a battery energy storage system (BESS) to store the excess of the photovoltaic generation and use it when required. Many studies have demonstrated the benefits of this approach from an energy point of view [12,13]. Generally, this solution is demonstrated to be very effective, but at the moment not cost-effective, resulting in long payback time. A third possible method is based on the control and management of the loads whenever possible during the daily hours. This is referred to as demand-side management (DSM) and has obvious benefits from users' perspective because it is cost-effective, easy to implement, and with short payback time [14]. Load shifting can be simply applied by the customer by modifying its habits or by installing a centralized building energy management system (BEMS) based on particular control logic, and able to optimize the energy flows maximizing the use of photovoltaic generation [15,16]. The electrical load flexibility, strictly connected also with the energy flexible building definition, will become widely adopted over the next few years when the electrification of heating/cooling and private transport sector will become prominent in residential buildings. In particular, the scientific literature already demonstrated the possibility to increase self-consumption through the active control of heat pumps [17] and smart electric vehicle chargers [18]. It is relevant to note that an interesting solution to optimally increase self-consumption and decrease CO 2 emissions can be the combination of load shifting strategies with a storage system. This strategy also represents the maximization of the flexibility of a building. Indeed, the use of batteries and flexible loads not only has benefits in terms of energy and environmental performance indicators, but also on photovoltaic and battery sizing, and this can be particularly advantageous at the district scale. Recent studies have demonstrated that collective self-consumption encouraged by the concept of renewable energy community (REC) (introduced by the EU directive 2018:2001 [2]), can achieve a higher target in terms of self-consumption, self-sufficiency, and CO 2 emission reduction [19].
Within this context, this work wants to present the impact given by the combination of flexible loads and photovoltaic systems with battery storage in terms of energy and environmental indices by optimally sizing the system, in a district-scale residential building case study. To do this, we propose to directly apply the early design optimization tool firstly presented for a single building in Lovati et al. [20] and then extended and compared for multiple-buildings [21] considering two different cost functions: the net present value (NPV) and the Levelized Cost of Energy (LCOE) applied to different scenarios according to a different level of loads flexibility and self-sufficiency target. The considered case study is a district composed of fifty single-family houses with proper geometry and electric demand, located under the same secondary substation as part of the same portion of the distribution grid with shared generation and consumption. The novelty of this study is not only that of adequately designing the photovoltaic and battery systems considering the constraints of the building district by optimizing an economic target, but also and above all highlighting the importance of demand flexibility in collective self-production and how flexibility has an impact on the optimal system configuration and the economic, energy, and environmental targets.
The rest of the paper is structured as follows. Section 2 presents the methodology and recalls the main characteristics of the early design optimization tool presented in Lovati et al. [20]. Section 3 describes in detail the case-study and the consumption profiles. In Section 4, the simulation settings, the scenarios considered, and the main results are reported. In Section 5, we summarize the conclusions and the future directions.

Methodology
In this work, we based our methodology on the early-design optimization tool for photovoltaic systems presented in Lovati et al. [20], applied to a district of buildings instead of a single one. Essentially, the tool takes as inputs different parameters used to find the optimum of a cost function and providing as a main output the photovoltaic system size and the battery capacity, but also some key performance indicators useful for the technoeconomic characterization of the system under study. The five inputs required by the tool are basically: • 3D model: Required in OBJ format, it includes the buildings under study, the surfaces available for the photovoltaic installation, and the close shading objects (e.g., trees, close buildings). This information is useful to identify a suitable area where photovoltaic modules can be installed. • Weather file: Required in EnergyPlus Weather (EPW) format, it describes the irradiation context (also considering the horizon line) and the temperature conditions needed to calculate the expected electricity generation of each photovoltaic module. • Electricity demand: The hourly profile of the annual electric demand of the building (e.g., heat pumps and auxiliary systems, appliances, lighting system, elevators, etc.). • Technical parameters: These include some optional indices which can affect the generated and consumed electricity profiles. The parameters are the performance ratio (PR), the PV module efficiency, the linear annual efficiency losses, and the temperature coefficient of the modules. For the battery instead, the maximum depth of discharge, round-trip efficiency, and the capacity degradation rate. A percentage for annual linear growth can be specified for the electricity demand. The time horizon to calculate the system performance is also an input. • Economic inputs: These data include the investment and operational cost for the photovoltaic system and battery, the price of purchased and sold electricity, a possible premium related to a net billing scheme, the annual discount rate of the investment, and the linear annual growth of the price of purchased and sold electricity.
Starting from the input geometry, the tools divide the area available for the installation of photovoltaic modules in a grid and places a sensor (equivalent to a solarimeter) in the center of each portion. For each solarimeter, the hourly plane of array irradiance is calculated using the ray-tracing simulation software RADIANCE (version 5.3, Lawrence Berkeley National Laboratory, University of California, Los Angeles, CA, USA) [22]. Given the irradiance on the surfaces, the techno-economic parameters and the demand profile, the optimization algorithm selects the optimal configuration of the system in terms of photovoltaic system capacity, photovoltaic module position, and battery capacity according to a target function. The optimization algorithm adopted is a simple direct search method [23] that iteratively improves its own solution. The optimization starts from the initial condition, a system with 0 kWp of nominal power for the photovoltaic system and 0 kWh as the initial battery capacity. At each iteration, the algorithms add the photovoltaic capacity found by the direct search algorithm (multiple of the single-module nominal power) to one of the available surfaces. If new surfaces are available, the direct search is repeated considering the actual configuration of the system as the initial condition. If the addition of new photovoltaic modules does not improve the reward function, the optimization algorithm firstly tries to move the modules on a different surface, otherwise it increases the battery capacity with a minimum step of 0.1 kWh. This process is repeated until the addition of photovoltaic modules or a new battery capacity or the move of modules in a different position does not improve the reward function. In Figure 1, the behavior of the reward function through the optimization process has been reported. In general, small increases in terms of the battery capacity or photovoltaic system nominal power lead to small variations of the reward function, while large decreases are mainly caused by bad movements (for example in North-facing surfaces) or exaggerated increase in system size that could lead to a drastic decrease of the reward function. Three different cost functions are currently implemented in the tool: the maximization of the net present value (NPV), the minimization of the Levelized Cost of Electricity (LCOE), and the maximization of the internal rate of return of the investment (IRR). In this work, we consider two of them: the maximization of NPV and the minimization of LCOE. The net present value of the investment of photovoltaic and battery system over a time horizon T is given by: [9]: where E sc and E sold are the electricity of the self-consumed and injected into the grid, while c sc and c sold are the respective associated costs.
• E sc and E sold are the electricity of the self-consumed and injected into the grid; • c sc and c sold are the price of electricity bought or sold for the final user, respectively; • OPEX PV are the operating expense cost of operation and maintenance for PV system based on the installed PV nominal power (P PVnom ); • cr BESS are the cost of BESS replacement per BESS capacity (C BESS ); • CAPEX PV,BESS is the sum of the investment cost for the PV and BESS system accordingly to the PV nominal power and the installed BESS capacity; • DR is the discount rate.
The target is to maximize the NPV, so at each iteration, the maximum net present value over the considered horizon is taken. While the simplified LCOE can be expressed as: In this case, the optimization algorithm objective is to minimize the levelized cost of electricity (LCOE, expressed as €/kWh) constrained to self-sufficiency greater than a certain threshold. At every iteration, the system is simulated, and the LCOE is calculated. If the self-sufficiency threshold is not guaranteed, a penalization is applied. The output is the configuration of the system that guarantees the minimum LCOE and respects the constraint related to self-sufficiency. From the optimization output, it is possible to extrapolate a relevant number of parameters that are useful to characterize a given system. The ones that are relevant for the discussion presented in the rest of the paper are presented here: • Self-sufficiency: Indicates the percentage of energy that can be supplied by PV and BESS. • Normalized NPV: Is the NPV normalized over the initial investment. • GHG emission reduction: Indicated the reduction of GHG emission due to the adoption of PV and BESS system, compared to the reference year which is 1990.
For the calculation of the objective functions, at each iteration, the optimization algorithm calculates the generation profile of the current system, ideally summing the generation profile of all the modules in the actual configuration (assuming that all modules operate at their maximum power). Since the position of modules and the size of the photovoltaic system change during the optimization process, this step must be repeated at each iteration. To keep the computational time reasonable, the model for the calculation of the energy produced by the system for a single simulation time-step is represented by the following simplified equation: where E i is the energy produced by the i module, PR is the performance ratio of the system, η is the efficiency of modules, A is the area of the modules, γ is the temperature coefficient for power, t is the simulation time-step equal to one hour, I i is the plane of the array irradiance calculated for the i-module at the beginning of the process with RADIANCE [22], a well known ray-tracing software mainly used for day-lighting applications, T re f is the reference temperature equal to 25 • C, and T mod,i is the i module temperature calculated with the following equation: where T amb is the air temperature from the weather file, I i is the plane of array irradiance, and k is the Ross coefficient that for this specific case has been set equal to 0.034 • C m 2 /W for the "sloped roof-not so well cooled" system configuration [24]. For the same reasons, the electric storage has been modeled through a simple energy balance considering a static round trip efficiency, set equal to 90% in this work. Degradation of the battery is considered through a decrease of the capacity due to aging, while no temperature-related losses are considered. We refer to Lovati et al. [25] for a more detailed explanation.

Case Study
The objective of this study is to analyze the impact of different aggregated demand profiles and how flexibility can improve the penetration of photovoltaic systems towards more sustainable districts. As a future scenario, we have assumed that the heating and cooling demands are covered by heat pumps, that all buildings in the district have been renovated from the energy point of view and that, on average, one vehicle per household is electric. For these reasons, the techno-economic inputs were set according to 2030 scenarios. Finally, the 3D model of the district has been generated with a 3D CAD (Rhino 6, Robert McNeel & Associates, Seattle, WA, USA). The used case study is composed of a district of fifty single-family houses where the geometry has been kept as simple as possible as shown in Figure 2. Each single-family house is a two-storey building and the buildings are organized on a uniform grid with roofs North-South or East-West oriented. Tilted roofs and façades have been assumed as surfaces available for the installation of photovoltaic modules. The location chosen for the case study is the city of Bolzano (North-East of Italy).

Residential Appliances
The yearly electric consumption profile for residential appliances has been calculated aggregating the individual electric demand of the fifty single-family houses of the district. For each building, the electricity consumption profile of the only appliances (without considering heating and cooling demand) has been generated using the LoadProfileGenerator software (LPG version 9.5, N. Pflugradt) [26]. LPG is a behavior-based tool that, based on the German population habits, calculates the demand profiles for the different households. It takes as input the weather data of the location selected, the distribution of people (age, employment, etc.), type of buildings, time resolution, and the number of households to be simulated, and returns the electric consumption profiles. In the context of this paper, we only used LPG to generate the electricity demand profiles related to the residential appliances (e.g., oven, PC, lighting, . . . ) where the consumption related to the user habits can be considered similar also for the Italian population. On the contrary, consumption related to the heating and cooling needs has been calculated with the approach discussed in the following section. In our case, the inputs used are the following: • Number of households is chosen equal to fifty according to the number of singlefamily houses of the district; • Type of buildings considered is the single-family house as represented in Figure 2; • Distribution of people considered is the one present in the default settings of LPG; • Location chosen is the city of Bolzano, in the North-East of Italy. According to this, the Typical Meteorological Year (TMY) of the selected location has been used for the weather data [27]; • Time resolution is set equal to one hour because this is the time resolution used by the optimization tool described in Section 2.
The aggregated electricity consumption profile, calculated by summing the individual household profiles, ranges between the peak value of 57.2 kW and a minimum of 7.3 kW, with an average power consumption of 20.3 kW. As an example, Figure 3 shows the district demand profile for a selected week. It is possible to notice the daily cycle characterized by a relevant decrease of the demand during night-hours. Moreover, it is also possible to notice the typical behavior of residential consumption profiles with two peaks, one in the morning and one in the evening, with a decrease in the central hours of the day.

Heat Pump Consumption Profiles
As mentioned in the Introduction, in future years, heat pumps will play a relevant role in the electrification of heating and cooling in the residential sector. Thus, it has been assumed that the thermal demand of the buildings is completely covered by heat pumps, both for the heating and the cooling season. However, a detailed model should be required to accurately simulate the electricity demand of a heat pump. Nevertheless, this is beyond the scope of this document, so a simplified method has been proposed. The complete process represented in Figure 4 has been included in a tool named EDGE-HP (Electric Demand GEnerator for Heat Pumps) developed within the Horizon 2020 project BIPVBOOST [28]. Scheme of the simplified method used to calculate the heat pump electric consumption profile.
In the following section, we summarize the steps required to obtain the electric consumption profile of a single building. To obtain the district aggregated profile, we repeated the process for all the houses.

1.
Calculate the yearly cumulative thermal demand of the building. Within the European H2020 project 4RinEU, several dynamic simulations were performed to estimate the annual cumulative thermal demand of different buildings in different climates, before and after different renovation interventions [29] with TRNSYS [30], a well-known dynamic simulation software. We refer to the project report for the details [29]. Since the objective of this work is to consider a future scenario, it has been assumed that all the single-family houses of the district have been renovated with a standard prefabricated façade to improve thermal insulation. Simulation results suggest that for the Continental climate, the specific thermal demand of a renovated single-family house for heating and cooling is in the range of 42.1-50.7 kWh/m 2 /y for heating and equal to 0 kWh/m 2 /y for cooling. Thus, according to the simulation results, for each building, the specific thermal demand has been randomly selected within the given interval. The obtained value has been multiplied by the area of the building, calculated by multiplying the average area A ave of households in the region by a coefficient to introduce variability between buildings of the district. The following formula has been used to calculate the floor area of each building where A ave has been set equal to the country average dwelling size (93.6 m 2 [31]) and k i,area is a coefficient used to add variability between buildings. In this case, k i,area has been considered equal to 1, since only the district aggregated profile has been used for the simulations. Finally, to calculate the annual cumulative consumption of the building i for heating and cooling, the area A i has been multiplied by the specific thermal demand for heating E h,s,i and cooling E c,s,i according to the following formula: 2.
Calculate the dimensionless hourly thermal demand of the buildings from the NUTS2 (nomenclature of territorial units for statistics, basic regions for the application of regional policies) code of the region [31], the outdoor air temperature, and the hour of the day. The relationship between the inputs and the dimensionless thermal demand was obtained in a previous study founded by the Hotmaps H2020 project from synthetic load profiles and are available at the project repository on GitLab [32]. For the details of the calculations, we refer to the project report [33].

3.
Apply a reduction factor during some hours of the day. This is an optional function and simulates the effect of different control logic based on the hour of the day. The reduction factor simulates a smart control and shifts part of the night thermal load during daytime hours. In practice, the thermal load during the defined hours is multiplied by a coefficient between zero and one. Two different scenarios have been considered in the current work: The scenario without demand shifting where the reduction factor has been set to zero. Conversely, for the scenario with demand shifting, the reduction factor has been considered equal to 0.5.

4.
Scale the modified dimensionless profile for matching the yearly cumulative thermal demand calculated at point 2. In this way, the integral of the thermal demand profile is equal to the annual cumulative thermal demand for both heating and cooling.

5.
Divide the thermal consumption profiles by a temperature-dependent coefficient of performance COP (heating) or by the energy efficiency ratio EER (cooling) from the performance map of a commercial reversible air to water heat pump. However, even if the detailed modeling of the heat pump is out of the scope of this work, it is important to notice that the losses of the thermal system have not been considered. In reality, shifting the electric consumption will cause an increase in thermal losses.
The method described in this section has been compared with a detailed dynamic simulation performed with TRNSYS (version 17, University of Wisconsin-Madison, Madison, WI, USA). The building used for the comparison is a small multi-family house with ten dwellings located in Germany used as a reference building in the Horizon 2020 project HYBUILD [34]. The total heated area is equal to 500 m 2 , the heating demand is equal to 50.1 kWh/m 2 /y for heating and 3.3 kWh/m 2 /y for cooling. The thermal demand of the building is completely covered with an air-to-water heat pump. The electric consumption of the heat pump obtained with the TRNSYS dynamic simulation (only space heating and cooling) has been compared with the profile obtained with the tool EDGE-HP presented in this section. Since EDGE-HP is intended to be used as a simplified way to obtain electric consumption profiles for early-design evaluations and not as a heat pump simulation tool, the self-consumption and self-sufficiency indexes of a theoretical system have been selected for the comparison between the two approaches. For the comparison, the photovoltaic generation has been calculated assuming a horizontal photovoltaic system of 12 m 2 and a module efficiency of 22.5%. In Figure 5, the comparison between the self-consumption and self-sufficiency indicators calculated with the consumption profiles obtained, respectively, with TRNSYS and EDGE-HP have been reported together with a selected week. From the figure, it is clear that EDGE-HP describes the behavior of the heat pump simulated with TRNSYS well, even if the profile is smoother. This difference can be explained by the fact that the TRNSYS temperature control considers a hysteresis, while EDGE-HP calculations are mainly based on external air temperature. However, the self-consumption and selfsufficiency indicators calculated with the two approaches agree, and the differences have been considered acceptable. Thus, in the following pages, EDGE-HP has been used to obtain the electric consumption profiles for space heating and cooling.

Electric Vehicle Charging Profiles
In this section, we briefly summarized the methodology behind the generation of the electric vehicle charging profile, which has been obtained using a tool based on the the open-source RAMP software engine. For a detailed description of the model and the software, we recommend the original publication [35] and the RAMP-mobility GitHub page. The RAMP-mobility tool is composed of two modules, one for the simulation of mobility profiles, and the other for the simulation of charging profiles. Each vehicle is simulated through a bottom-up stochastic behavior, starting from data available for all the European countries. Starting from population and mobility data and the type of day the software calculates the mobility demand and vehicle usage.
Once the mobility demand of each driver has been calculated, the second module is used for the simulation of the charging profiles considering the probability of finding a charging station, its charging speed (slow, medium, or fast charging), the battery capacity, and the charging strategy adopted. In this work, we used the "Night charge" strategy for the scenarios not considering flexibility, as it is assumed as the actual standard for the residential sector, and the "RES integration" strategy for the scenarios considering the flexibility of the demand, where the charging events are only allowed during daytime hours (see Figure 6). In the last case, the main assumption is that a well-distributed grid of charging stations is installed in the district, and it allows the drivers to charge their vehicles during the daytime (for example at parking, offices, supermarkets, schools, etc.). Finally, it has been assumed that on average, one vehicle per household is electric, thus fifty vehicles have been simulated and aggregated to obtain the profile at the district scale. Figure 6. A week-example of the electric vehicle charging profiles considering the "RES integration" and "Night charge" strategies implemented in RAMP [35].

Simulation Results
This section presents first of all the considered scenarios based on the combination of different electric consumption profiles, the key performance indicators used to evaluate the system performance, and the techno-economic inputs for the optimization tool described in Section 2. Then, the principal results of the optimization procedure to properly size PV and battery system are reported and commented on. Two aspects are considered corresponding to two different cost functions: the role of demand flexibility and the impact on greenhouse gas emissions.

Scenarios and Key Performance Indicators
The approaches described in the previous section have been coupled to obtain the profiles at the district scale incrementally varying the degree of flexibility. In the first scenario (Scenario A), the state-of-the-art situation considers the "night charge" mode for the electric vehicles and fixed heat pump profile. Scenario B introduces RES integration strategies for electric vehicle charging. Scenario C keeps into account the RES generation for mobility and assumes a smart control logic able to shift part of the demand of heat pumps during daytime hours. After several attempts with 20, 50, and 80%, the percentage of the night load that can be shifted has been fixed equal to 50%. This percentage has been considered as a reasonable compromise between the complexity and the technology required in a real application to obtain such flexibility and a value that could have a relevant impact on results. In the last case (i.e., Scenario D), the appliances have been excluded to consider only flexible loads. Table 1 summarizes the four scenarios used in the optimization procedure. In the performed simulations, the following parameters have been considered for the energy system evaluation: • PV nominal power and BESS capacity: The optimization tool provides the cumulative nominal power for the PV energy system and the battery capacity to be installed in the considered district as the output according to the specific analyzed scenarios and the related cost functions. • Self-sufficiency: Indicates the percentage of load that can be supplied by PV and BESS.
• Normalized NPV: Is the NPV normalized over the initial investment. • GHG emission reduction: Indicated the reduction of GHG emission due to the adoption of PV and BESS system compared to the reference year which is 1990.  Table 2, the considered values for the PV and battery systems as well as the cost of electricity and the considered time horizon have been summarized. Note that the values indicated with * are stochastic variables that have been considered uniformly distributed in the indicated ranges. Additionally, the cost of the photovoltaic and BESS systems have been considered fixed and not correlated with the system capacity.

Flexibility Impact-NPV Cost Function
In this section, the results obtained with the optimization of the district photovoltaic and battery system using an economic target have been presented and discussed. The solution found by the optimization algorithm is the one that maximizes the economic outcome of the investment in terms of net present value (maximum net present value calculated at the end of the time horizon), regardless of the energy indicators. In Figure 1, an example of optimization has been reported to show the behavior of the reward function as a function of the number of iterations done. It can be seen that the optimization algorithm is quite fast to improve the value of the reward function in the first iterations (addition of photovoltaic modules and battery capacity) while the optimal positioning of the photovoltaic modules requires several iterations. The process has been repeated for all the scenarios and the results compared. To facilitate the comparison, the net present value has been normalized with respect to the initial investment.
In Table 3, the results of the economic optimization of the system have been reported for all the flexibility scenario. For each optimization, the selected indicators are presented. The results of the optimization using Scenario A (lower degree of flexibility) are relevant from several perspectives. Firstly, the self-sufficiency indicator is well below the value of the other scenarios. Secondly, the output does not consider the installation of electric storage (i.e., the battery capacity results 0 kWh) and finally, the normalized net present value is in line with the highest values. These results can be interpreted as follows: for this type of load, the most convenient solution in economic terms is to install photovoltaic without battery. Since in Scenario A the vehicle charge is done during the night and the heat pumps are not flexible enough to shift part of the night-load during the daytime, the photovoltaic system covers only the daytime load of appliances and heat pumps (that is lower with respect to night load) with direct self-consumption. For these reasons, the self-sufficiency index is only 19.8%, far away from the targets for the decarbonization of the residential sector. Thus, even if this solution guarantees an optimal economic outcome of the investment (optimal net present value), it cannot be considered satisfactory due to the low contribution given by photovoltaic. On the other side, results obtained for Scenario B suggest that an infrastructure that allows the charging of electric vehicles during the daytime coupled with batteries can significantly improve self-sufficiency. However, for Scenario B, it is possible to notice a decrease of the Normalized net present value caused by the higher initial investment required to install the optimal nominal power of the photovoltaic system and battery capacity: in this case, the economically optimal ratio between storage capacity and nominal power installed results equal to 0.63 kWh/kWp. The contrary effect can be discussed also comparing the result obtained for Scenario C: in this scenario, heat pumps are considered flexible and 50% of their electric load is shifted during the daytime. In the optimal solution, there is only a small decrease of the self-sufficiency indicators compared to the one obtained with Scenario B, but such results are obtained with around half the battery capacity (ratio between storage capacity and nominal power installed: 0.34 kWh/kWp). In other words, the flexibility of heat pumps to shift part of their load during the daytime coupled with an infrastructure that allows the charge of electric vehicles during the daytime, can lead to almost the same results seen for Scenario B in terms of self-sufficiency, but with a lot less storage capacity. The consequence is a decrease in the initial investment confirmed by the increase in the net present value normalized with respect to the initial costs. Finally, the results obtained with Scenario D (considering flexible heat pumps and electric vehicle charge during the daytime) confirm that flexibility coupled with modest storage capacity (ratio between storage capacity and photovoltaic nominal power well below 0.5 kWh/kWp) can lead to good levels of self-sufficiency and also be an attractive investment from an economic point of view.

Environmental Impact-LCOE Cost Function
Since the role of flexibility has already been highlighted in the previous section, in the following discussion, only Scenario D was considered (flexible heat pumps and electric vehicle charge during the daytime). Moreover, results have been obtained through the optimization of the system using a different perspective: instead of the maximization of the economic outcome of the investment, the system was designed according to the new ambitious energy targets set by the 2030 Climate Target Plan corresponding to at least 55% reduction of greenhouse gas emissions compared to 1990 levels.
Since the tool used for the optimization cannot directly optimize the system according to a specific carbon emissions target, it has been decided to adopt the available objective function that minimizes the levelized cost of electricity, constrained to guarantee a certain threshold in terms of self-sufficiency. Thus, as a first attempt, the self-sufficiency minimum threshold has been set equal to 55%, and at the end of the optimization, results have been checked to verify that the specific emissions related to the self-consumed energy respect the target of emissions reduction with respect to the 1990 levels. The Italian Piano Nazionale Integrato per l'Energia ed il Clima (PNIEC) [44] considers 55% as the 2030 target percentage for electricity generation from renewable energy sources in Italy. Assuming that ideally, the objective is to generate the electricity that is consumed, it is possible to use 55% as the minimum threshold for self-sufficiency. The results of the optimization of the system have been reported in Table 4. In addition to the indicators introduced in Section 2, the levelized cost of electricity (LCOE), calculated on the entire lifetime of the system, has also been reported. Looking at the indicators reported in Table 4, the final solution respects the objectives fixed for the optimization since the minimum self-sufficiency threshold is guaranteed. However, looking at the size of the components, it is possible to notice that the optimizer selects a configuration with a low ratio between storage capacity and photovoltaic nominal power 0.2 kWh/kWp, also compared with the results obtained in the previous section. This can be mainly explained by the low cost of photovoltaic modules expected for 2030 that lead the optimizer to choose a slightly oversized system in terms of energy generation (self-consumption only 42.4%, the remaining 57.6% is lost or sent to the grid without receiving any credit). However, we can also accept to use a sub-optimal solution and mitigate this effect by designing a system more balanced between generation and consumption. Thus, the tool has been used also for the simulation of sub-optimal configurations obtained starting from the solutions obtained in the previous section for Scenario D and iteratively increasing the size of the photovoltaic system and battery capacity as long as the self-sufficiency minimum threshold has been satisfied. Table 5 reports two possible solutions, one with a ratio between storage capacity and photovoltaic nominal power equal to 1 kWh/kWp (Scenario D S1), and the other with a ratio equal to 0.75 kWh/kWp (Scenario D S2): Table 5. Sub-optimal configurations for the Scenario D.

Scenario D S1
Scenario D S2 Both the solutions reported for Scenario D S1 and S2 guarantees the self-sufficiency threshold, of course at the cost of an increased levelized cost of electricity compared to the optimal solution reported in Table 4. However, the normalized net present value is increased up to 1.1 (economically attractive on a long term horizon), and also selfconsumption is drastically improved (56% for both S1 and S2 instead of 48% of the optimal solution), confirming that the systems are both more balanced with respect to generation and consumption, and the impact on the local grid would be reduced. Finally, for the three solutions, the carbon emission reduction with respect to 1990 levels have to be checked. Assuming that the aggregate carbon emission intensity in 1990 was equal to 0.5493 kg CO 2 eq/kWh [45], the total emissions considering 1990 levels can be estimated by multiplying the cumulative annual energy consumption for Scenario D by the corresponding emission factor. On the contrary, actual emissions for the district considering the designed photovoltaic system can be calculated by multiplying the cumulative energy taken from the grid by the actual specific emissions of the Italian electricity mix (0.33854 kg CO 2 eq/kWh [46]) summed to the cumulative self-consumed energy multiplied by the related specific emissions. The specific emissions of the self-consumed energy have been calculated accounting for the emissions related to module production, installation, production of the mounting structure and frame, cables, inverter and battery production, etc. according to the following formula: where Em SC are the specific emissions related to the self-consumed energy, Em PV,spec = 2870 kg CO 2 eq/kWh [47] are the specific emissions related to the photovoltaic system, Em BESS,spec = 103 kg CO 2 eq/kWh [48] are the specific emissions of the battery, C PV and C BESS are the photovoltaic system and battery capacity, and E SC is the cumulative energy self-consumed during the system lifetime. Finally, the greenhouse gases emissions reduction has been estimated with the following formula: As reported in Table 6, the target emissions reduction is satisfied only for Scenario D S1 and Scenario D S2, while Scenario D can guarantee only 46% of reduction with respect to 1990 levels. This effect can be again explained by the fact that for Scenario D, the system is oversized towards generation, causing an increase of the specific emissions related to the production, transport, and installation of the system. Moreover, in this scenario, most of the energy produced (57.6%) is lost, and thus does not participate in emissions reduction. In conclusion, in this section, it has been shown that it is possible to achieve good economic results even if the solution is not economically optimal and, at the same time, contributing to the decarbonization of the residential sector. Results confirm that the flexibility of the demand coupled with a design approach that not only considers the economic aspects, but also the contribution to the energy transition and the impact on the local grid can be a successful approach towards sustainable smart cities and energy communities. Moreover, it has been shown that a combination of energy storage and flexibility of the demand is fundamental to achieve the ambitious targets set by the 2030 Climate Target Plan that cannot be achieved only by increasing photovoltaic penetration. As a final note, in this article the actual emission factor for the calculation of the emission reduction has been adopted. The scope was to highlight the role of photovoltaic penetration and flexibility in the energy transition of the residential sector. In future years, the emission factor of the Italian energy mix is expected to decrease according to the European climate targets (55% emission reduction by 2030, carbon neutrality by 2050). In this scenario, the energy purchased from the grid will have a lower impact on carbon emissions. However, this condition will only be achieved in an advanced phase of the decarbonization process, which has not been analyzed in this work.

Conclusions
In this work we have analyzed the impact of demand flexibility on the optimal configuration of a district-scale shared photovoltaic and battery system. For this purpose, four scenarios considering different levels of demand flexibility have been created, and the system has been optimized from two different perspectives. The first one corresponds to an economic point of view, the other one gives the priority to the role that the residential sector can play to achieve the emissions reduction targets set by the 2030 Climate Target Plan.
The results obtained for the different flexibility scenarios can be summarized as follows. The demand in the residential sector, considering also the contribution given by the electrification of heating and transport, coupled with the installation of photovoltaics, cannot guarantee alone satisfactory levels of self-sufficiency when the best economic configuration is taken into account. To overcome this, the proper use of storage and load shifting during daytime hours could play a relevant role to boost the installation of photovoltaic systems and the increase of the renewable energy share. However, conversely to the storage systems which require an initial investment, load shifting exhibit good results in terms of self-sufficiency with limited costs. It is relevant to remark that none of the scenarios used for the economic optimization lead to a level of self-sufficiency in line with the 2030 Climate Target Plan objectives. This means that the installation of photovoltaic systems cannot be seen only as a pure economic investment, otherwise, the risk is to miss the environmental targets. On the other hand, it has been demonstrated that it is possible to achieve emissions reduction targets guaranteeing the economic sustainability of the systems.
Based on the outcomes of the present work, the following comments can also drive the decarbonization of the residential sector. From the transport sector point of view, an infrastructure that directly integrates electric vehicle charging with photovoltaic necessarily means that drivers must have the opportunity to charge the batteries during daytime hours. To achieve this goal, huge investments in private home charging stations could not necessarily be the optimal solution. On the contrary, a strategic plan to divide the investment or public subsidies between private and public charging stations, covering also public parking, offices, municipalities, schools, supermarkets, sports centers and all other strategic locations, could have a higher impact on the decarbonization of the sector. The electrification of the heating and cooling demand is crucial because they consist of a relevant part of the residential energy consumption. However, heat pumps or other electric heating and cooling devices must be coupled with batteries or must be smart and flexible to achieve the decarbonization targets. As seen, batteries could increase self-sufficiency, but also requires a higher initial investment. The results of this study suggest that it should give the priority to the investment in flexible, connected, and smart heat pumps that can have a dialogue with the owned or shared photovoltaic system (or with the grid manager in an energy community scenario) to maximize self-sufficiency. An example in this direction can be found in the Italian Decreto Rilancio [49], published in 2020 to face the economic crisis related to COVID-19. The installation of smart controls for heating/cooling devices are considered eligible to benefit from public subsidies. Furthermore, the Renewable Energy Directive 2018/2001/EU highlights the importance of collective self-consumption and requires all the European countries to contribute to the energy transition entitling the prosumers to produce, consume, store, sell, and share renewable energy within the communities. Results presented in this article goes in the same direction and confirm the relevant role of energy sharing to achieve the environmental targets.
As further research directions based on the impact of flexibility, it will be important that works related to the optimization of the system operation will include this variable also in the design stage because the coupling of the two approaches would have relevant benefits related to the energy transition that the residential sector is facing.

Data Availability Statement:
The data presented in this study are available on request from the corresponding author.