1 Introduction

Governments around the world retaliate against the negative impacts of climate change by introducing new laws to encourage the use of renewable resources instead of conventional fossil fuels [1,2,3,4]. For instance, the European Council aimed to reduce annual greenhouse gas (GHG) emissions by 40% compared with 1990 levels and increase overall energy consumption from renewable sources by 32% [5]. In line with the world trend, Spain shares the same goal: it is now heavily reliant on fossil fuel and natural gas. Spain primarily relies on importing oil from Saudi Arabia, Algeria, Nigeria, Gibraltar, France, Italy, Libya, Morocco, Mexico, Iran, and Iraq, as well as Natural gas from the Russian Federation, United States, Qatar, Algeria, and Nigeria [6]. Recently, Spain proposed achieving 42% of the total energy share by 2030 from renewable sources by adopting 60 gigawatts of renewable generation and 74% of gross national electricity consumption from Wind and Solar. By continuing the following path, Spain will plan to achieve 100% of the country’s gross energy consumption from renewable sources along with zero carbon emissions by 2050 [6]. National Energy and Climate Plans (NECPs) actively promote three strategies to adopt 100% renewable energy. Firstly the promotion of large renewable projects; secondly, deployment of self-sustainable energy consumption and distributed consumption for small industries; and lastly, the integration of renewable energy on grid systems [6]. In recent years, the Spanish Government has imposed many steps to produce renewable electricity to reduce annual GHG emissions. In 2012, a 4600 MW capacity, and later in 2017, another 3900MW capacity of the solar photovoltaic plant was added to the existing power generation system [7]. In the past, numerous optimization approaches were taken to utilize smaller-scale renewable energy projects as they were more economically viable [8].

Due to the intermittency of renewable generation, it is pretty challenging to conciliate power production to mitigate carbon footprint. Many measures can be taken to overcome this challenge [9,10,11]. Energy consumption can be adjusted to meet the power generation from consumers’ endpoint [12]. Similarly, energy generation can also be adjusted by combining various primary generators, such as wind turbines, and solar photovoltaic panels, and secondary generation sources, such as diesel generators, and fuel cells as complementary systems to each other to diminish the mismatch [13, 14]. Another means of minimizing the gap when renewable energy generation is lower than energy consumption is to use energy storage systems [10].

Interconnected renewable distributed generators and Energy Storage Systems (ESS) can be used together to form a Microgrid (MG), where energy penetration level determines the amount of annual total load energy administered by the MG system. MG can be integrated with a conventional grid or as a standalone unit [15, 16]. The optimal size is essential to cut operations down and improve the dependability of MG. Numerous studies were found in the previous research literature on the optimal size of the MG considering the location-specific meteorological and energy demand data. For example, a hybrid renewable system consisting of PV, WT, DG, and batteries was optimally sized using a self-adaptive differential evolution algorithm while considering the generation and consumption data Yanbu, Saudi Arabia, was shown in [17]. Another study showed that a system composed of PV, WT, and bio-diesel generator achieved minimum LCOE for India by using Homer Optimization software [18]. However, these studies did not cover the comparative analyses between various system configurations, different energy storage mediums, and the environmental impact caused by annual GHG emissions considering the grid-integrated scenario. These comparative analyses are significant since; they clearly show MG’s economic reliability and feasibility along with the environmental impact while taking into account the uncertainty of renewable generation and load demand. Very little empirical research showed the environmental impact and the economic assessment deeming the carbon tax law and the uncertainty of load demand. For instance, the Social Cost of CO\(_2\) emission (SCC) was observed at 15 €/ton CO\(_2\) e 200 €/ton CO\(_2\) using GAMS software for a PV system designed for a hotel in Greece [19]. Besides, both renewable generation and the load demand are intermittent, and energy storage behavior varies by generation and consumption. According to another literature, SCC was found 17 €/ton CO\(_{2}\) using Distributed Energy Resources Customer Adoption Model (DER-CAM) software for residential load in the same city [20]. Techno-economic feasibility study for standalone PV systems had also been tested for more than 40 locations to find the best-performing location in Saudi Arabia using RETScreen Clean Energy Management software [21]. A study on a hybrid renewable system composed of PV, Thermal, and battery systems was conducted using Transient System Simulation Tool (TRNSYS) software for a location in Cyprus.

Sustainable renewable generations prefer using fossil fuel and coal on the conventional grid. Still, MG’s annual operating cost and GHG emissions factor overruled whether it is feasible to use the MG. Numerous pieces of literature show the economic aspect of using grid-integrated microgrids for various circumstances. Microgrid-connected grid (MG-CG) energy penetration level determines how much energy would be taken from MG in the grid integration scenario. MG’s load-balancing operation and economic parameters were observed considering \(80\%\) of the total MG-CG energy penetration scenario for the US electric grid [22, 23]. Another analysis was examined in France, considering LCOE by exploiting half of MG’s total annual energy demand in the nuclear power plant connected integration scenario. The carbon tax was reduced under 100 €/ton CO\(_2\) while taking the higher renewable generation penetration. Despite a significant reduction in GHG emission, a very high amount of system losses were found in these studies because of higher renewable energy penetration [22]. Moreover, these studies did not conclude any optimization method to reduce the LCOE [22, 23]. Another analysis was examined in Kerman city of Iran, where a Gird-Connected MG system composed of photovoltaic, bio-diesel, fuel cell, electrolyzer, and hydrogen tank achieved minimum LCOE considering reliability and renew ability cost [24]. Power generation facilities are mostly reliant on fossil fuels, it would be extremely difficult to completely replace them with renewable power generation technology. However, no such study has been done to check energy penetration level scenarios for the hybrid energy storage comprised of hydrogen and traditional battery banks incorporated with RES.

The main contribution of this work is the combination of previously described works with their respective research gap and finding the optimal MG configuration based on economic feasibility and environmental impact. These are as follows:

  • Design of a grid-connected hybrid renewable system composed of wind turbine (WT), solar photovoltaic (PV), lead-acid battery (BAT), fuel-cell (FC) generator, electrolyzer module (EM), and H\(_2\) tank (HT) for two cities with different geography located in Spain.

  • Design of a load demand model that provides hourly energy consumption for 50 identical houses with some common utility loads.

  • An algorithm is proposed to dispatch the excess energy to various storage systems that are more economically feasible and use the stored energy when there is an energy generation deficit.

  • Particle Swarm Optimization (PSO) is used to reduce the components needed for grid-integrated MG to run cost-effectively, and the ultimate goal is to optimize the LCOE.

  • Comparison of the LCOE and annual GHG emissions for battery running MG, hydrogen running MG, and hybrid energy storage running MG considering 25%, 50%, 75%, and 100% MG-CG energy penetration level scenarios and meteorological data of two cities.

The objective of this study was to evaluate the technological, financial, and environmental performance of a microgrid that supplies electricity to fifty households in a small residential neighborhood in the Spanish cities of Madrid and Seville. The first stage involved calculating the hourly power usage by utilizing a load table with corresponding daily use times. The seasonal influence was then added to the load curve for the full year using the Gaussian distribution formula. In the second stage, an optimization approach called the particle swarm optimization algorithm was used to size MG for the lowest cost depending on the demand for and access to renewable resources. It was believed that the MG consisted of components like PV, WT, BAT, FC, EM, and HT. Using an energy dispatch strategy (EDS), techno-economic and ecological evaluation scenarios were formed for every Microgrid unit. Life cycle greenhouse gas emissions (kg CO\(_2\) equivalent emitted/year) along with levelized cost of energy (LCOE, $/kWh) were the mathematical variables that were assessed. In terms of peak power, the proposed model was designed to accommodate four distinct degrees of load fulfillment – 25%, 50%, 75%, and 100%. The assumption was that the current electricity supply would fulfill the unfilled load.

2 Model Development

This section presents the renewable energy potential in the selected cities, the components needed for the MG model, and problem formulation for economic and environmental impact assessment.

2.1 Renewable Energy Potential in Spain (Madrid and Seville)

In this study, two cities in Spain, e.g., Madrid and Seville, are selected as case studies. Both cities possess a high potential for solar energy; for instance, the annual average solar energy potential in Madrid was estimated as 4.5 kWh/m \(^2\) /day, along with the average wind speed of 5.0 m/s at 50 m height. On the other hand, Seville has a slightly higher annual average solar potential of 5.4 kWh/m\(^2\)/day and an average wind speed of 4.5 m/s at the same height [25]. The hourly direct normal irradiance (DNI) of Seville is almost \(20\%\) higher than Madrid, but the average wind speed of Madrid is slightly better than Seville as shown in Fig. 1. Presented hourly data was collected from the NASA Power [25]. In a nutshell, Madrid city possesses better wind energy harnessing potential, whereas Seville has higher solar potential. The collected data are used while developing MG economic and environmental impact assessment models.

Fig. 1
figure 1

Solar and wind energy potential for Madrid and Seville cities in Spain

2.2 Proposed MG Model

The grid-connected MG system is composed of a PV, WT, BAT, HT, EM, FC, and Energy Dispatch System (EDS) as shown in Fig. 2. The following parts of this section present the mathematical interpretations of the MG component.

Fig. 2
figure 2

Proposed microgrid model

2.2.1 PV Model

The solar model is described using two essential parts: the solar irradiance model, followed by the PV module. The optimal performance of a photovoltaic (PV) module is attained by orienting it at a specific tilt angle. The hourly radiation on a tilted surface of a PV can be estimated using EQ. (1) shown in Klucher model [26].

$$\begin{aligned} IR(t) = I_{\text {d}}(t)+I_{\text {df}}(t)+I_{\text {r}}(t) \end{aligned}$$
(1)

\(I_{\text {d}}\), \(I_{\text {df}}\), and \(I_{\text {r}}\) are direct, sky-diffuse, and ground-reflected components of solar irradiance on the tilted surface. The hourly data of solar DNI, DHI, and clearness index are collected from the NASA Power [25] for two selected locations to calculate the hourly radiation. The direct component of solar insolation is estimated using EQ. (2).

$$\begin{aligned} I_{\text {d}}(t) = \text{ DNI }(t) - \text {DHI}(t) \Bigg ( \dfrac{\text {cos} \theta }{\text {cos} \theta _\text {z}}\Bigg ) \end{aligned}$$
(2)

Here, \( \theta = 40 ^{\circ }\) is the solar incidence and \(\theta _\text {z}=38^{\circ } \) is the zenith angles. The sky-diffuse component is estimated using EQ. (3).

$$\begin{aligned} I_{\text {df}}(t)&=\! \text{ DHI }(t)\left( 0.5\left( 1+\text{ cos }\dfrac{\beta }{2}\right) \right) \!\left( 1+f_\text {k} (t)\left( \text{ sin }\dfrac{\beta }{2}\right) ^3\right) \nonumber \\&\quad (1+f_\text {k} (t) (\text{ cos }\theta ))^2 \text {sin}(\theta _\text {z} )^3) \end{aligned}$$
(3)

The effect of cloudy condition \(f_\text {k}(t)\) is the correlation of the horizontal diffuse component and the global horizontal irradiance. The component, \(f_\text {k}(t)\), is evaluated using EQ. (4).

$$\begin{aligned} f_\text {k}(t) = 1-\Big \{\dfrac{\text {DHI}(t)}{\text {DNI}(t)}\Big \}^2 \end{aligned}$$
(4)

The ground-reflected component is evaluated under isotropic solar irradiance assumption using EQ. (5).

$$\begin{aligned} I_{\text {r}}(t) = \dfrac{\rho }{2}\text {GHI}(1-\text {cos}\beta ) \end{aligned}$$
(5)

Here, \(\beta =20 ^{\circ }\) is the tilt angle, and \(\rho =0.2\) is the albedo which is the measure of the diffuse reflection of solar radiation to the total solar radiation. The photovoltaic cell is a semiconductor device consisting of a p-n junction, in which the magnitude of the generated photo-current is directly proportional to the intensity of incident solar radiation. The hourly generated energy by the PV module is estimated using the solar radiation that produces the photo-current [27].

$$\begin{aligned} E_{\text {pv}}(t)=N_{\text {pv}} \times \left( V_{\text {max}} \times I_{\text {max}}(t) \right) =\gamma .V_{\text {oc}}.I_{\text {sc}} \end{aligned}$$
(6)

Here, \(N_{\text {pv}}\) is the number of PV panels, \(V_{\text {oc}}\) is the open circuit voltage, \(I_{\text {sc}}\) is the short circuit current, \(V_{\text {max}}\) is the terminal voltage, \(\gamma \) is the fill factor, and all the other parameter values are given on Table 1. Output current \((I_{\text {max}})\) is calculated using EQ. (7) is used in order to estimate the output current from one solar panel [27].

$$\begin{aligned} I_{\text {max}}(t)=N_\text {p} I_{\text {ph}}(t)-N_\text {p} I_\text {s}(t) \times \Bigg [\exp \Big (q\Big (\dfrac{v}{N_\text {s}kT_\text {c}A}\Big )-1\Big )\Bigg ] \nonumber \\ \end{aligned}$$
(7)

\(I_{\text {ph}}\) is the photo-current, and \( I_\text {s} \) is the saturation current calculated using EQ. (9) [27, 28].

$$\begin{aligned} I_{\text {ph}}(t)= & {} [I_{\text {sc}}+K_\text {t} (T(t)-T_{\text {ref}} )]\times IRR(t) \end{aligned}$$
(8)
$$\begin{aligned} I_\text {s}(t)= & {} I_{rs} \times \Big \{ \dfrac{T(t)}{T_{\text {ref}}}\Big \}^3\times \exp \Bigg [\dfrac{qE_\text {g}\Big (\dfrac{1}{T_{\text {ref}}}-1\Big )}{kA}\Bigg ] \end{aligned}$$
(9)

Here, hourly solar radiation \(\text{ IRR }(t)\) is obtained from EQ. (1). \(E_\text {g} = 1.11eV\) is the Band-gap energy of semiconductor, \( q = 1.6 \times 10^{-19} C\) is charge of one electron, k = 1.38 \(\times \) 10\(^{-23}\) J/K is the Boltzmann’s constant. The rest of the parameter values are given in Table 1.

Table 1 PV module specification [29]

2.2.2 WT Model

The hourly output energy generated by WT can be estimated using various approaches, including the linear, quadratic, and wei-bull distribution models. In Ref. [30], the linear model of wind function works best to calculate the hourly electrical energy generated by the WT model that is shown in EQ. (10).

$$\begin{aligned} E_{\text {wt}}(t) = \left\{ \begin{array}{ll} N_{\text {wt}}.P_{\text {wt}} \times \Big (\dfrac{v(t)-v_{in}}{v_{\text {rate}}-v_{\text {in}}}\Big ) \text { for } v_{\text {in}}\le v(t)\le v_{\text {rate}} \\ N_{\text {wt}}.P_{\text {wt}} \text { for } v_{\text {rate}}<v(t)<v_{\text {out}} \\ 0 \text { for } v(t) < v_{\text {in}} \text { and } v>v_{\text {out}} \end{array}\right. \end{aligned}$$
(10)

Here, v(t) is the hourly wind speed collected from NASA Power [25]. The manufacturers generally provide the power curves at various wind speeds. \(P_{\text {wt}}=1000W\) is the rated power, \(v_{\text {rate}}=12m/s\) is the rated speed, \(v_{\text {in}}=3m/s\) is the cut-in speed, and \(v_{\text {out}}=23m/s\) is the cut-off speed of the wind turbine [31].

2.2.3 BAT Model

The amount of available energy in a storage system at a particular point in time is determined using EQ. (11) [32].

$$\begin{aligned} \text {SOC}(t)= & {} N_{\text {bat}} \Bigg [ \text {SOC}(t-1) + \dfrac{\eta _{\text{ ch }}(t).\text {BAT}_{\text{ ch }}.\Delta t}{C_{\text {bat}}} \nonumber \\{} & {} + \dfrac{\text {BAT}_{\text{ dch }}(t).\Delta t}{\eta _{\text{ dch }}.C_{\text {bat}}} \Bigg ] \end{aligned}$$
(11)

Here, \(N_{\text {bat}}\) is the number of the battery, \(C_{\text {bat}}=1000 Ah\) is the battery capacity, \(\eta _{\text{ ch }}=80\%\) and \(\eta _{\text {dch}}=95\%\) are the battery charging and discharging efficiencies respectively. Finally, t represents the hours during the considered period. Hourly charging and discharging rates of the battery are calculated using EQ. (12) and EQ. (13), respectively.

$$\begin{aligned} \text {BAT}_{\text{ ch }}= & {} \text {min} \left\{ E(t) - L(t) \left[ \frac{(\text {SOC}_{\text {max}}-\text {SOC}(t)).C_{\text {bat}}}{\eta _{\text{ ch }}} \right] \right\} \nonumber \\ \end{aligned}$$
(12)
$$\begin{aligned} \text {BAT}_{\text{ dch }}= & {} \text {min} \Big \{ L(t) - E(t) \Big [ \left( \text {SOC}(t)-\text {SOC}_{min} \right) .\eta _{\text{ dch }}.C_{\text {bat}} \Big ] \Big \} \nonumber \\ \end{aligned}$$
(13)
$$\begin{aligned} \text {SOC}_{\text {min}} \le \text {SOC}(t) \le \text {SOC}_{\text {max}} \end{aligned}$$

2.2.4 EM Model

Electron transfer through the EM is used to separate water into hydrogen and oxygen. The mathematical formulation of the reaction is shown in EQ. (14).

$$\begin{aligned} 2H_2O + Electrical \;\; Energy \rightarrow 2H_2 + O_2 \end{aligned}$$
(14)

The total power consumed by the EM to produce H\(_2\) per hour (3600 s) is estimated using EQ. (16) [33].

$$\begin{aligned} H_{2_{Produced}}(t)= & {} \dfrac{I_{\text {em}} \times N_{\text {em}}}{2 \times F} \times \eta _{i} \times 3600\nonumber \\= & {} N_{\text {em}} \times \dfrac{P_{\text {em}}(t)}{2 \times V_{\text {em}} \times F} \times 3600 \end{aligned}$$
(15)
$$\begin{aligned} P_{\text {em}}= & {} I_{\text {em}} \times V_{\text {em}} \end{aligned}$$
(16)

Here, \(N_{\text {em}}\) is the number of EM, \(P_{\text {em}}=1000W\) is the rated power, \(V_{\text {em}}=2V\) is the cell voltage, and \(\eta _{i} = 100\%\) is the current efficiency, 1 F=96487C is a charge of an electron [33].

2.2.5 HT Model

H\(_2\) gas produced by the EM is needed to be compressed to be stored on the H\(_2\) tank through the adiabatic process. The mathematical model for the compressor for calculation of total electrical power consumed while compressing and storing in the cylinder is also included. The hourly energy consumed by the hydrogen compressor is calculated using EQ. (17) as of Ref. [34].

$$\begin{aligned} E_{compressor} = C_\text {p}\frac{T_1}{\eta _\text {c}}\left( \left( \frac{P_2}{P_1} \right) ^\frac{r-1}{r} -1\right) m_\text {c} \end{aligned}$$
(17)

Here, \(\eta _\text {c}=75\%\) is the compressor efficiency, \(C_\text {p}=14304\;KJ\;(kg\;K)^{-1}\) is the specific heat of hydrogen at constant pressure, \(T_1=293\;K\) is the temperature, and \(P_1=0.6MPa\) and \(P_2=20MPa\) are the inlet and outlet gas pressures of the hydrogen tank, and \(r=1.4\) is the isentropic exponent of H\(_2\). Finally, the gas flow rate is assumed to be \(2.351 s^{-1}\) for calculation purposes. According to 15, 1 kWh rated EM produces 9.33mol of H\(_2\) gas and 0.0536 kWh of energy to be compressed as 9.33mol of H\(_2\) at the pressure of 20MPa [34, 35]. H\(_2\) generated by the EM and consumed by FC is presented in \(Mol-h^{-1}\) unit. Then, the gas is compressed to fill the hydrogen tank. To convert \(Mol-h^{-1}\) unit in energy analogous representation of kWh and compressed gas volume of liters EQ. (18) and EQ. (19) are used, respectively [36].

$$\begin{aligned} E_{\text {tank}}(kWh)= & {} M_{\text {tank}} \times 2 \times \dfrac{LHV (kWh \; kg^{-1})}{1000} \end{aligned}$$
(18)
$$\begin{aligned} V_{\text {tank}}(liter)= & {} M_{\text {tank}} \times T_{\text {tank}} \times \dfrac{R}{P_{\text {tank}}} \end{aligned}$$
(19)

Here, \(R=0.08211\; atm \;(mol\;\; K)^{-1}\) is the gas constant, \(LHV = 33\; kWh\;\; kg^{-1}\) is the low heat value of the H\(_2\) and cylinder tank temperature \(T_{\text {tank}}=25^{\circ } C \), and tank pressure \(P_{\text {tank}}=20\;MPa\) is assumed for calculation purpose as of Ref. [34].

2.2.6 FC Model

The FC converts the chemical energy of a fuel to electrical energy, opposite to the EM. The anode of an FC is periodically provided with hydrogen gas while the cathode is fed with pure oxygen. The chemical processes at the anode and cathode are shown in EQ. (20).

$$\begin{aligned} 2H_2 + O_2 \rightarrow 2H_2O + Electrical \;\; Energy \end{aligned}$$
(20)

The hourly energy generated by FC from H\(_2\) consumption can be estimated using EQ. (22) and EQ. (21) respectively [33].

$$\begin{aligned} H_{2_{consumed}}(t)= & {} \dfrac{I_{\text {fc}} \times N_{\text {fc}}}{2 \times F} \times \dfrac{1}{\mu _{\text {fc}}} \times 3600 \nonumber \\= & {} N_{\text {fc}} \times \dfrac{P_{\text {fc}}(t)}{2 \times V_{\text {fc}} \times F} \times 3600 \end{aligned}$$
(21)
$$\begin{aligned} P_{\text {fc}}= & {} I_{\text {fc}} \times V_{\text {fc}} \; \;\; \end{aligned}$$
(22)

Here, \(N_{fcm}\) is the number of FC, \(P_{\text {fc}}=1000W\) is the rated power, \(V_{\text {fc}}=2V\) is the cell voltage of FC [33].

2.2.7 Electrical Load Model

The hourly energy consumption for 50 houses is considered while generating the electrical load model. 24 h of daily load consumption is shown in Table 2 [18].

Table 2 Load demand specifications

By using EQ. 23, the hourly load demand for 8760 h is estimated. \(n=2\;to\;7\%\; of\; LE_i\;\) of power consumption variation is added in the load consumption data by months using the normal distribution function [37], where the peak load demand is seen in May, June, and July representing the summer season and November, December, and January, representing the winter season.

$$\begin{aligned} \text {Load}= & {} \sum _{i=1}^{6} \Big ( \text {LP}_i. LQ_i \times \tau _i \in \tau \Big ) + \sum _{t=1}^{8760}. n \end{aligned}$$
(23)
$$\begin{aligned} n= & {} {\left\{ \begin{array}{ll} &{} \sigma \times 3\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 1 \le t \le 744\;(\text {January}) \\ &{} \sigma \times 5.0\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 745 \le t \le 1,416\;(\text {February}) \\ &{} \sigma \times 5.5\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 1,417 \le t \le 2,137\;(\text {March}) \\ &{} \sigma \times 6.0\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 2,138 \le t \le 2,857\;(\text {April}) \\ &{} \sigma \times 6.5\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 2,858 \le t \le 3601\;(\text {May}) \\ &{} \sigma \times 7\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 3,622 \le t \le 4,341\;(\text {June}) \\ &{} \sigma \times 6.5\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 4,342 \le t \le 5,085\;(\text {July}) \\ &{} \sigma \times 5.5\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 5,086 \le t \le 5,829\;(\text {August}) \\ &{} \sigma \times 5\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 5,830 \le t \le 6,550\;(\text {September}) \\ &{} \sigma \times 4.5\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 6,551 \le t \le 7,29\;(\text {October}) \\ &{} \sigma \times 3\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 7,296 \le t \le 8,015\;(\text {November}) \\ &{} \sigma \times 2.5\%\;\text {of}\;\text {LE}_\text {i} \;\forall \; 8,016 \le t \le 8,760\;(\text {December}) \\ \end{array}\right. } \end{aligned}$$
(24)

Here, i is the index for all the loads defined in Table 2, LP is the load power rating, LQ is the quantity of load, LE is the total energy consumed by a load in a day, \(\tau _\text {i}\) is the time of each load defined by i and \(\tau \) is the total hour in a day, \(\sigma \) is a random number between 0 and 1. The generated avg. hourly load demand for each month is shown in Fig. 3.

Fig. 3
figure 3

Monthly average load demand for both cities

2.3 Economic Assessment Model

The overall cost for the suggested model considering the configuration of the system and maintaining the upkeep of the system considering its component’s lifetime is chosen to analyze the design’s cost-effectiveness and financial sustainability.

2.3.1 Levelized Cost of Energy (LCOE)

The LCOE is established to show the cost-effective benefit of the suggested model. Several studies have been carried out that look at different methods to estimate the cost of energy [17, 24, 38, 39]. In simpler terms, LCOE is the average cost of generating each kilowatt-hour (kWh) of energy throughout its lifespan and for gird connected MG is calculated using EQ. (25).

$$\begin{aligned} LCOE = \dfrac{\text {CRF} \times \text {TNPC} + (G_{\text {e}} - G_{\text {r}})}{\text {AED}} \end{aligned}$$
(25)
Table 3 Prices for microgrid components [24, 41]

Here, CRF is the capital recovery factor, and TNPC is the total net present cost of the system. AED is the annual energy demand. \(G_{e}\) is the net expense for buying the shortage energy from the grid, and \(G_{\text {r}}\) is the net revenue from selling the excess energy to the grid. The cost of per kWh energy, \(0.252(\$/kWh)\) is set as buying from the Spanish power grid [40], and the selling price of the per unit energy from the MG is considered half of the retail price.

2.3.2 Capital Recovery Factor (CRF)

The CRF is calculated using EQ. (26) where \(\text {dr}=6\%\) is the discount rate and LT=20 years is the considered lifespan of the project [24].

$$\begin{aligned} CRF = \dfrac{\text {dr} (1+\text {dr})^{\text {LT}}}{(1+\text {dr})^{\text {LT}} - 1} \end{aligned}$$
(26)

2.3.3 Total Net Present Cost (TNPC)

The TNPC is the aggregate net present cost (NPC) of every component that is used in the model, which can be estimated using EQ. (27) [24] as:

$$\begin{aligned} \begin{aligned} TNPC =\sum _{i=1}^{i_{\text {max}}=7} \text {NPC}_{\text {i}} \end{aligned} \end{aligned}$$
(27)

NPC of each component is calculated by using EQ. (28)

$$\begin{aligned} \begin{aligned} NPC_i =\sum _{i}^{i_{\text {max}}} \left( \text {IC}_\text {i}+\text {MC}_\text {i}+\text {RPC}_\text {i} \right) \end{aligned} \end{aligned}$$
(28)

Here, i represents the components that are used in the model i.e., PV, INV, WT, BAT, EM, FC, and HT.

The installation cost (IC), maintenance and operation cost (MC), and replacement cost (RPC) for each component is calculated using the formula shown as follows:-

$$\begin{aligned} IC_{\text {i}}= & {} N_{\text {i}} \times CC_i \end{aligned}$$
(29)
$$ \begin{aligned} MC_{\text {i}}= & {} N_{\text {i}} \times O \& M_{\text {i}} \times \sum _{ni=1}^{ni_{\text {max}}}\Big ({\dfrac{1 + \text {er}}{1+\text {ir}}\Big )^T_i} \end{aligned}$$
(30)
$$\begin{aligned} RPC_i= & {} N_{i} \times RC_{i} \times \sum _{n=5,10,15}^{N}\Big ({\dfrac{1 + \text {er}}{1+\text {ir}}\Big )^T_i} \end{aligned}$$
(31)

Here, Ni is the optimal number of components i.e.,- \(N_{\text {pv}}\),\(N_{\text {bat}}\),\(N_{\text {wt}}\),\(N_{\text {em}}\), \(N_{\text {fc}}\), \(N_{\text {ht}}\), \(\text {CC}_\text {i}\) is the per unit cost, \( O \& M_\text {i}\) is the per unit maintenance cost, and \(\text {RC}_\text {i}\) is the per unit replacement of the respective component which is given on Table 3. \(\text {ni}\) is the number of components, and n is the number of components that is needed to be replaced. T is the lifespan of the component, \(\text {ir}=6\%\) is the interest rate, and \(er=5\%\) is the price escalation rate.

2.4 Environmental Impact Assessment Model

In general, energy production from renewable energy resources is emission-free; however, emissions are involved if their entire life cycle is considered, e.g., during manufacturing, transportation, installation, and deposition after their lifespan. The following mathematical model, EQ. (32), is used in the literature while assessing the environmental impact of various MG components [42, 43]:

$$\begin{aligned} Emission_{net} = \sum _{t=1}^{k=6} \left( NE_\text {i} \times \xi _\text {i} \right) \end{aligned}$$
(32)

Here, \(NE_\text {i}\) is the annual net energy supplied, and \(\xi _i\) is the emission factor, per kg carbon dioxide equivalent (kg CO\(_2\)e) emission for 1 kWh of energy supplied by each component that is given in Table 4.

Table 4 Emission factors for the energy sources [42]

2.5 Optimization Problem and Constraints

The main objective of this research is the reduction in the LCOE and TNPC of the system. The net present cost of a system depends on the number of components used. PSO is used to search the optimal sizing required to run the system with minimal cost. The objective function is presented as follows:

$$\begin{aligned} F(O)= \text {min}\sum _{n=0}^{n_{\text {max}}} \text {TNPC} \end{aligned}$$
(33)

2.5.1 Constraints

The optimization constraints can be defined as follows:

  • Number of components (\(N_i\)) is an integer number that can vary from \(n_{i_{min}}=[1,1,1,1,1,1]\) to \( n_{i_{\text {max}}} = [1000, 1000, 500, 500, 500, 100]\) that is taken as a boundary constraint for PV, WT, BAT, EM, FC, and HT, respectively.

    $$\begin{aligned} n_{i_{min}} \le N_{i} \le n_{i_{\text {max}}} \end{aligned}$$
  • The operational SOC for the lead-acid battery is kept between 20% to 80%.

    $$\begin{aligned} 20\% \le \text {SOC}(t) \le 80\% \end{aligned}$$
  • H\(_2\) tank is operational when the pressure inside the cylinder lies between 27 bar to 135 bar using the formula \(PV=nRT\) to check the volume for pressure constraints.

    $$\begin{aligned} 27\; bar\le Pressure(t) \le 135\; bar \end{aligned}$$
  • Four different levels of energy penetration, namely 25%, 50%, 75%, and 100% levels, are tested in terms of annual net energy distribution capabilities of the proposed MG to the load demand with respect to the existing grid. A substantial penalty is added to the TNPC in case of mismatches between the total annual supply from the MG to the load for the considered penetration scenario. In 100% of the energy penetration scenario, the yearly total load demand must be consumed from renewable generation and hybrid energy storage, and no amount of energy is bought from the grid. Otherwise, a significant penalty is given to the TNPC to automatically set the \(N_\text {i}\) as a bad solution for the problem.

3 Methodology

This section describes the energy dispatch strategy of microgrid operation and the employed meta-heuristic algorithm, Particle Swarm Optimization, for the formulated optimization problem. PV model returns the hourly energy generation using hourly DNI, DHI, clearness index, and temperature. WT model gives the hourly energy generation from wind speed.

3.1 Energy Dispatch Strategy (EDS)

An energy dispatched strategy is proposed in Fig. 4 to smartly distribute the renewable energy between energy storage, load, and the grid. Each of the components used in the proposed MG model is designed using the mathematical formula to calculate the hourly energy it may produce or consume based on given resources.

Fig. 4
figure 4

Proposed EDS

Hourly energy generation and consumption are evaluated; when the generation is higher, the algorithm goes reserve state to store the excess energy in the energy storage; otherwise, the deficit state. In the reserve state, the algorithm checks the SOC(t) of the BAT system as it is required to keep the SOC between 20 and 80% of total storage. When the SOC of the battery exceeds the 80% limit, excess energy then will go to the EM to convert extra energy into H\(_2\) gas. Each tank can store a finite amount of compressed H\(_2\), defined by H\(_2\) tank capacity. If the produced H\(_2\) gas exceeds the tank capacity or the amount of excess energy exceeds the installed EM capacity, then the extra hourly energy will be sold to the grid. In the deficit state, if the battery remains SOC(t)\(>20\%\), the excess energy required to satisfy the load demand will be delivered from the battery pack. Otherwise, the algorithm checks if the stored H\(_2\) can be used in FC to assure the load demand. If the required energy shortage exceeds the FC generation capacity limit, or the stored H\(_2\) gas is drained, the necessary energy is needed to ensure the load demand is bought from the grid.

Fig. 5
figure 5

Algorithm flowchart of PSO

3.2 Particle Swarm Optimization (PSO)

The PSO, a widely used and efficient meta-heuristic algorithm, finds the optimal solutions for complex mathematical and engineering problems [45,46,47,48]. Several meta-heuristic algorithms were used in numerous studies on the performance and reliability of microgrids; PSO’s operating times were noticeably quicker and implementations were simpler compared to other meta-heuristic algorithms [49,50,51]. This research utilizes PSO as a methodology to ascertain the ideal quantity of components required for the system, taking into account the minimization of TNPC and the attainment of the lowest achievable LCOE. The algorithmic flowchart of PSO is presented in Fig. 5.

At first, 100 sets of random swarms of particles are generated. Each group of particles represents the number of components set such as \(N_{\text {pv}}\), \(N_{\text {bat}}\), \(N_{\text {wt}}\), \(N_{\text {em}}\), \(N_{\text {fc}}\), \(N_{ht}\). The fitness value is measured on EQ. (33) as the objective function for each number of components set if a particular number of components doesn’t meet the constraint, a penalty is added to the objective function forcing the PSO algorithm to discard the fitness value. By doing so, only the optimal number of components will be taken, and the rest will be filtered out as the best solution for each iteration cycle. Each swarm of particles contains an individual best, and each iteration has its global best. After each iteration, the position and weight of the particle are evaluated. Updating the position, weight, and fitness is continuous until the iteration reaches its maximum number or the termination requirements are satisfied. Consequently, the optimal variable and the objective values are achieved. The best value from 3 successive runs with a 1000 iteration cycle, the best sets of solutions is taken for the system.

Fig. 6
figure 6

Objective function convergence curve

4 Results and Discussion

The technical, economic, and environmental parameters of the proposed energy management system are presented in this section. PSO determined the optimum number of components needed for the system to run economically feasible considering each grid-microgrid penetration level. The PSO algorithm runs for an average of 20 min for each scenario. The convergence curves for 75% penetration grid scenario for both cities are shown in Fig. 6. The convergence curve represents the objective function’s value in relation to how long it took to minimize the value of the objective function.

The majority of convergence occurred during the initial phase of the iteration cycle. When the curve remains constant across numerous iterations, it can be concluded that the PSO algorithm is unable to identify the best size for the MG while taking into account the specified limitations. The LCOE for the hybrid energy storage running system considering four different MG-CG energy penetration level scenarios for two cities is shown in LCOE and is found best ranging from 0.06 \(\$/kWh\) to 0.23 \(\$/kWh\) for 75% MG-CG energy penetration level for Madrid and Seville respectively. Fig 7.

Fig. 7
figure 7

LCOE comparisons in two cities of Spain under various RER penetration levels

Table 5 Optimal sizing and energy output
Table 6 Economic and environmental impact assessment parameters

For the 25% penetration level, the LCOE is found to be the highest and TNPC as shown in Table 6, and the majority expense is in buying the rest 75% of energy from the grid. But for 75% of the penetration scenario, the system is sized such that it could provide 75% of annual load demand, and the rest of the energy is bought from the conventional grid. For the 100% grid penetration scenario, the MG system is bound to provide 100% of annual load demand. All the expense is in building the system considering investment, maintenance, and replacement costs. For Seville, LCOE is found lowest among all the systems, Table 5 shows the number of components needed for Seville is lower than the same penetration level as Madrid, which is because Seville has better renewable potentiality. This can be revised from the amount of annual energy sold to the grid. The GHG emission for each penetration scenario is shown in Fig. 8. The annual total emission is highest at 62.145 tCO\(_2\)e/yr for Madrid and 73.57 tCO\(_2\)e/yr for Seville on 100% MG energy penetration level considering the LCA of each component used in the MG system.

Fig. 8
figure 8

Annual GHG emission comparisons in two cities of Spain under various RER penetration levels

Fig. 9
figure 9

Monthly energy dispatch (75% RER penetration level)

Annual emission is almost reduced to half for both cities compared to the grid, which may produce 166.56 tCO\(_2\)e/yr for generating the same amount of energy. As the penetration level increases, the number of components is also rising to cope with the energy demand. After estimating the life-cycle emission of each element, it is seen for a 100% grid-mg penetration scenario, to satisfy the same amount of load demand, GHG emission will be lesser than the conventional grid method.

4.1 75% MG Energy Penetration

The average energy distribution monthly for both cities considering a 75% MG penetration scenario is shown in Fig. 9. In Madrid, June’s average peak renewable generation is seen at 3.684 MW-day. The battery model stored the highest amount of energy in March, about 668.97 kW-day, and consumed the peak energy of about 73.13 kW-day in June.

In Seville, peak renewable generation is seen at 3.033 MW-day, and energy from batteries is provided and consumed the highest 1.342 MW-day 1.271 MW-day for June. Peak load consumption for both cities is 3.130 MW-day for the middle of the year. The maximum excess energy sold to the grid is 1.101 MW-day in June for Madrid, But there is no energy sold to the grid for Seville for the same 75% Grid penetration scenario. Renewable generation was lower in December, so EDS purchased the maximum energy from the grid, about 1.207 MW-day for Madrid and 1.265 MW-day for Seville. The hourly SOC level of the Battery is displayed in Fig. 10. When the generation is higher, in May, June, and July, the battery SOC level is higher compared to November, December, and January. In Madrid, it is seen that most of the time battery is at its peak capacity (80% SOC) because a lesser battery pack is used than in Seville.

Fig. 10
figure 10

Battery SOC

Excess energy produced by renewable means then fills up the Hydrogen storage through EM. Annual H\(_2\) on the cylinder is shown in Fig. 11 for both cities. A higher amount of H\(_2\) is produced in EM and then stored in the HT in the months of May, June, and July the renewable generation is at its peak. The stored H\(_2\) is in use in January, February, November, and December when the renewable generation is lower.

Fig. 11
figure 11

H\(_2\) on Cylinder

Table 7 Comparison with similar studies in the literature

4.2 Microgrid Profile for each Penetration Scenario

The optimal sizing required for the system and their respective annual generation and energy dispatch from the grid for two cities considering four different MG-CG energy penetration levels is given in Table 5. Here, for a 25% penetration scenario, the minimum number of components is required, which results in a lower generation. The annual load demand is about 1000.2 MWh, so to adequate it, the rest of the energy is bought from the grid, and no energy is sold to the grid either. But for 100% of energy penetration scenarios, a full 1000.2 MWh of load demand is provided from the MG system; considering renewable generation intermittency and load demand uncertainty, PSO optimized the MG system to transfer excess energy more economically viable than just storing it on battery storage. So for both cities, when the penetration level is at its peak, the highest generation amount is seen along with the highest amount of energy sold to the conventional grid. In Madrid’s peak penetration level, the used number of components is higher than Seville’s same penetration level. Still, Madrid has lower renewable generation capabilities, so even though the installed capacity is higher, it cannot deliver the same energy level as Seville.

The economic and environmental assessment parameter is displayed in Table 6. The lowest TNPC and highest grid revenue expenditure for both cities are seen for the 25% penetration level. But as the penetration level went higher, the expense of buying energy from the grid advanced to the lowest. EDS algorithm smartly maintains the Energy on HES so that in a 100% penetration scenario, even considering renewable generation intermittency and load uncertainty, the MG system could provide 100% of energy from the grid.

Annual GHG for each penetration is given in Table 6. Here the maximum amount of emission is recorded for 25%. Even though the 25% penetration level, the number of components used is lower. To satisfy the rest of the 75% load demand, EDS needed to buy energy from the grid. Using the emission model, the total emission can easily be calculated for the corresponding penetration level. GHG emission is found to lower as the penetration level is increased and the amount of energy is needed to buy from the grid. If no MG is used, the conventional grid might produce 166.56 tCO\(_2\)e/yr, which is twice the 100% MG penetration for generating the same amount of energy.

4.3 Comparison with Similar Studies in the Literature

Comparative studies with similar literature are shown in Table 7. Grid integration scenarios with different MG penetration levels affected the outcome. So, the LCOE is significantly improved compared to previous studies. Moreover, the carbon footprint is reduced, as shown in Table 6.

5 Conclusions and Recommendations

A strategic approach is presented to evaluate the LCOE, operating cost, and annual GHG emission of the microgrid systems in two cities in Spain. The proposed model utilized various energy storage devices, batteries, hydrogen, and a combination of both, along with different prominent renewable energy resources. The article presented problem formulation to assess the economic and environmental impacts of the MG systems under consideration. Then, it employed a popular and efficient meta-heuristic technique, PSO, to solve the presented formulation. The employed solution strategy outperformed the reported approaches in the literature as per the obtained results. Based on the analyzed results, this article provides the following recommendations for microgrid owners:

  • The TNPC gradually increases along with the penetration level, as higher penetration levels mean more energy from the MG system. TNPC found the lowest for lower penetration levels for both cities.

  • Seville has more renewable generation potential than Madrid, as seen in the same penetration level; Seville needed fewer components than Madrid to provide the same annual load demand.

  • LCOE is found lowest at 0.11 \(\$/kWh\) considering 75% MG-CG energy penetration level in Madrid and at 0.06 \(\$/kWh\) considering 100% MG-CG energy penetration level in Seville.

  • Annual GHG emission on the LCA model of each component is found lowest on 25% MG energy penetration level around 2.93 tCO\(_2\)e/yr and 8.47 tCO\(_2\)e/yr for Madrid and Seville, respectively. Annual emission is almost reduced to half, 62.14 tCO\(_2\)e/yr for Madrid and 73.57 tCO\(_2\)e/yr for Seville compared to the grid annual emission 166.56 tCO\(_2\)e/yr for generating the same amount of energy for 100% of MG energy penetration.

The findings of this study are thought to help determine the best arrangement required for hydrogen-battery hybrid energy storage integrated with the conventional power grid integrated with renewable generators, minimizing the energy cost per unit that can serve as a guide for the financially viable operation of grid-connected microgrids. Furthermore, by evaluating life cycle assessments for various grid energy penetration scenarios and offering an ideal energy storage system, the results also help to ensure a consistent power supply, lower greenhouse gas emissions, and facilitate the implementation of microgrid projects in two distinct regions of Spain with disparate geo-architectures and natural resource bases. With the ultimate goal of speeding up the development of renewable energy resources and energy diversification plans, all of these initiatives seek to lower the cost of green energy resources, particularly FC, EM, and hydrogen compressors, and to increase the competitiveness of products for use in the energy industry and market. Future research should be done to apply this methodology-using different optimization algorithms-to other nations. The inclusion of technical, economic, and environmental viewpoints in an evaluation would help local politicians make well-informed decisions about foreseeable energy regulations.