Sector-Coupling with pypsa#

Note

Also in this tutorial, you might want to refer to the PyPSA documentation: https://pypsa.readthedocs.io.

Note

If you have not yet set up Python on your computer, you can execute this tutorial in your browser via Google Colab. Click on the rocket in the top right corner and launch “Colab”. If that doesn’t work download the .ipynb file and import it in Google Colab.

Then install the following packages by executing the following command in a Jupyter cell at the top of the notebook.

!pip install pypsa pandas numpy matplotlib highspy
import pypsa
import pandas as pd
import matplotlib.pyplot as plt

plt.style.use("bmh")

Previous Capacity Expansion Model#

To explore sector-coupling options with PyPSA, let’s load the capacity expansion model we built for the electricity system and add sector-coupling technologies and demands on top.

This example has single node for Germany and 4-hourly temporal resolution for a year. It has wind and solar solar generation, an OCGT generator as well as battery and hydrogen storage to supply a fixed electricity demand.

Some sector-coupling technologies have multiple ouputs (e.g. CHP plants producing heat and power). PyPSA can automatically handle links have more than one input (bus0) and/or output (i.e. bus1, bus2, bus3) with a given efficieny (efficiency, efficiency2, efficiency3).

url = "https://tubcloud.tu-berlin.de/s/pzytNg9gtkgPpXc/download/network-cem.nc"
n = pypsa.Network(url)
INFO:pypsa.io:Retrieving network data from https://tubcloud.tu-berlin.de/s/pzytNg9gtkgPpXc/download/network-cem.nc
WARNING:pypsa.io:Importing network from PyPSA version v0.27.1 while current version is v0.31.0. Read the release notes at https://pypsa.readthedocs.io/en/latest/release_notes.html to prepare your network for import.
INFO:pypsa.io:Imported network network-cem.nc has buses, carriers, generators, global_constraints, loads, storage_units
n
PyPSA Network
Components:
 - Bus: 1
 - Carrier: 6
 - Generator: 4
 - GlobalConstraint: 1
 - Load: 1
 - StorageUnit: 2
Snapshots: 2190
n.buses.index
Index(['electricity'], dtype='object', name='Bus')
n.generators.index
Index(['OCGT', 'onwind', 'offwind', 'solar'], dtype='object', name='Generator')
n.storage_units.index
Index(['battery storage', 'hydrogen storage underground'], dtype='object', name='StorageUnit')

Hydrogen Production#

The following example shows how to model the components of hydrogen storage separately, i.e. electrolysis, fuel cell and storage.

First, let’s remove the simplified hydrogen storage representation:

n.remove("StorageUnit", "hydrogen storage underground")

Add a separate Bus for the hydrogen energy carrier:

n.add("Bus", "hydrogen")
Index(['hydrogen'], dtype='object')

Add a Link for the hydrogen electrolysis:

n.add(
    "Link",
    "electrolysis",
    bus0="electricity",
    bus1="hydrogen",
    carrier="electrolysis",
    p_nom_extendable=True,
    efficiency=0.7,
    capital_cost=50e3,  # €/MW/a
)
Index(['electrolysis'], dtype='object')

Add a Link for the fuel cell which reconverts hydrogen to electricity:

n.add(
    "Link",
    "fuel cell",
    bus0="hydrogen",
    bus1="electricity",
    carrier="fuel cell",
    p_nom_extendable=True,
    efficiency=0.5,
    capital_cost=120e3,  # €/MW/a
)
Index(['fuel cell'], dtype='object')

Add a Store for the hydrogen storage:

n.add(
    "Store",
    "hydrogen storage",
    bus="hydrogen",
    carrier="hydrogen storage",
    capital_cost=140,  # €/MWh/a
    e_nom_extendable=True,
    e_cyclic=True,  # cyclic state of charge
)
Index(['hydrogen storage'], dtype='object')

We can also add a hydrogen demand to the hydrogen bus.

In the example below, we add a constant hydrogen demand the size of the electricity demand.

p_set = n.loads_t.p_set["demand"].mean()
p_set
54671.88812785388
n.add("Load", "hydrogen demand", bus="hydrogen", carrier="hydrogen", p_set=p_set)  # MW
Index(['hydrogen demand'], dtype='object')

Heat Demand#

For the heat demand, we create another bus and connect a load with the heat demand time series to it:

n.add("Bus", "heat")
Index(['heat'], dtype='object')
url = "https://tubcloud.tu-berlin.de/s/mSkHERH8fJCKNXx/download/heat-load-example.csv"
p_set = pd.read_csv(url, index_col=0, parse_dates=True).squeeze()
p_set.head()
snapshot
2015-01-01 00:00:00     61726.043437
2015-01-01 04:00:00    108787.133591
2015-01-01 08:00:00    101508.988082
2015-01-01 12:00:00     90475.260586
2015-01-01 16:00:00     96307.755312
Name: 0, dtype: float64
n.add("Load", "heat demand", carrier="heat", bus="heat", p_set=p_set)
Index(['heat demand'], dtype='object')
n.loads_t.p_set.div(1e3).plot(figsize=(12, 4), ylabel="GW")
<Axes: xlabel='snapshot', ylabel='GW'>
_images/a0bd0e12376d87fb097cf66bdf579454009825146ebe3b175d18504e3ab0d599.png

Heat pumps#

To model heat pumps, first we have to calculate the coefficient of performance (COP) profile based on the temperature profile of the heat source.

In the example below, we calculate the COP for an air-sourced heat pump with a sink temperature of 55° C and a population-weighted ambient temperature profile for Germany.

The heat pump performance is given by the following function:

\[ COP(\Delta T) = 6.81 - 0.121 \Delta T + 0.00063^\Delta T^2 \]

where \(\Delta T = T_{sink} - T_{source}\).

def cop(t_source, t_sink=55):
    delta_t = t_sink - t_source
    return 6.81 - 0.121 * delta_t + 0.000630 * delta_t**2
url = "https://tubcloud.tu-berlin.de/s/S4jRAQMP5Te96jW/download/ninja_weather_country_DE_merra-2_population_weighted.csv"
temp = pd.read_csv(url, skiprows=2, index_col=0, parse_dates=True).loc[
    "2015", "temperature"
][::4]
cop(temp).plot(figsize=(10, 2), ylabel="COP");
_images/6e8dbddadfc5e9ac5ca9eb8d3893268f1d7db991720127f5adf989bce1b59bf2.png
plt.scatter(temp, cop(temp))
plt.xlabel("temperature [°C]")
plt.ylabel("COP [-]")
Text(0, 0.5, 'COP [-]')
_images/79d24447c57247bb3c7277983012f2c5a4e4eed205daa2d1ca54cac74177f80f.png

Once we have calculated the heat pump coefficient of performance, we can add the heat pump to the network as a Link. We use the parameter efficiency to incorporate the COP.

n.add(
    "Link",
    "heat pump",
    carrier="heat pump",
    bus0="electricity",
    bus1="heat",
    efficiency=cop(temp),
    p_nom_extendable=True,
    capital_cost=3e5,  # €/MWe/a
)
Index(['heat pump'], dtype='object')

Let’s also add a resistive heater as backup technology:

n.add(
    "Link",
    "resistive heater",
    carrier="resistive heater",
    bus0="electricity",
    bus1="heat",
    efficiency=0.9,
    capital_cost=1e4,  # €/MWe/a
    p_nom_extendable=True,
)
Index(['resistive heater'], dtype='object')

Combined Heat-and-Power (CHP)#

In the following, we are going to add gas-fired combined heat-and-power plants (CHPs). Today, these would use fossil gas, but in the example below we assume green methane with relatively high marginal costs. Since we have no other net emission technology, we can remove the CO\(_2\) limit.

n.remove("GlobalConstraint", "CO2Limit")

Then, we explicitly represent the energy carrier gas:

n.add("Bus", "gas", carrier="gas")
Index(['gas'], dtype='object')

And add a Store of gas, which can be depleted (up to 100 TWh) with fuel costs of 150 €/MWh.

n.add(
    "Store",
    "gas storage",
    carrier="gas storage",
    e_initial=100e6,  # MWh
    e_nom=100e6,  # MWh
    bus="gas",
    marginal_cost=150,  # €/MWh_th
)
Index(['gas storage'], dtype='object')

When we do this, we have to model the OCGT power plant as link which converts gas to electricity, not as generator.

n.remove("Generator", "OCGT")
n.add(
    "Link",
    "OCGT",
    bus0="gas",
    bus1="electricity",
    carrier="OCGT",
    p_nom_extendable=True,
    capital_cost=20000,  # €/MW/a
    efficiency=0.4,
)
Index(['OCGT'], dtype='object')

Next, we are going to add a combined heat-and-power (CHP) plant with fixed heat-power ratio (i.e. backpressure operation). If you want to model flexible heat-power ratios, have a look at this example: https://pypsa.readthedocs.io/en/latest/examples/power-to-gas-boiler-chp.html

n.add(
    "Link",
    "CHP",
    bus0="gas",
    bus1="electricity",
    bus2="heat",
    carrier="CHP",
    p_nom_extendable=True,
    capital_cost=40000,
    efficiency=0.4,
    efficiency2=0.4,
)
Index(['CHP'], dtype='object')

Electric Vehicles#

To model electric vehicles, we first create another bus for the electric vehicles.

n.add("Bus", "EV", carrier="EV")
Index(['EV'], dtype='object')

Then, we can attach the electricity consumption of electric vehicles to this bus:

url = "https://tubcloud.tu-berlin.de/s/9r5bMSbzzQiqG7H/download/electric-vehicle-profile-example.csv"
p_set = pd.read_csv(url, index_col=0, parse_dates=True).squeeze()
p_set.loc["2015-01-01"].div(1e3).plot(figsize=(4, 4), ylabel="GW")
<Axes: xlabel='snapshot', ylabel='GW'>
_images/2e3c079faf49fce70b3608843f901d6cbc697ba59c7abaaa7847da7bead364cc.png
n.add("Load", "EV demand", bus="EV", carrier="EV demand", p_set=p_set)
Index(['EV demand'], dtype='object')

Let’s have a quick look at how the heat, electricity, constant hydrogen and electric vehicle demands relate to each other:

n.loads_t.p_set.div(1e3).plot(figsize=(10, 3), ylabel="GW")
plt.axhline(
    n.loads.loc["hydrogen demand", "p_set"] / 1e3, label="hydrogen demand", color="m"
)
plt.legend()
<matplotlib.legend.Legend at 0x7fd2b45288d0>
_images/3169ffab16b91c475be6f08a05b648afeb830a44559ee266571f00378ea9f5f4.png

The electric vehicles can only be charged when they are plugged-in. Below we load an availability profile telling us what share of electric vehicles is plugged-in at home – we only assume home charging in this example.

url = "https://tubcloud.tu-berlin.de/s/E3PBWPfYaWwCq7a/download/electric-vehicle-availability-example.csv"
availability_profile = pd.read_csv(url, index_col=0, parse_dates=True).squeeze()
availability_profile.loc["2015-01-01"].plot(ylim=(0, 1))
<Axes: xlabel='snapshot'>
_images/99741588d6b18ade167f81fc258e9aa429ca3bba0a11a1c7024b0cdfba312412.png

Then, we can add a link for the electric vehicle charger using assumption about the number of EVs and their charging rates.

number_cars = 40e6  #  number of EV cars
bev_charger_rate = 0.011  # 3-phase EV charger with 11 kW
p_nom = number_cars * bev_charger_rate
n.add(
    "Link",
    "EV charger",
    bus0="electricity",
    bus1="EV",
    p_nom=p_nom,
    carrier="EV charger",
    p_max_pu=availability_profile,
    efficiency=0.9,
)
Index(['EV charger'], dtype='object')

We can also allow vehicle-to-grid operation (i.e. electric vehicles inject power into the grid):

n.add(
    "Link",
    "V2G",
    bus0="EV",
    bus1="electricity",
    p_nom=p_nom,
    carrier="V2G",
    p_max_pu=availability_profile,
    efficiency=0.9,
)
Index(['V2G'], dtype='object')

The demand-side management potential we model as a store. This is not unlike a battery storage, but we impose additional constraints on when the store needs to be charged to a certain level (e.g. 75% full every morning).

bev_energy = 0.05  # average battery size of EV in MWh
bev_dsm_participants = 0.5  # share of cars that do smart charging

e_nom = number_cars * bev_energy * bev_dsm_participants
url = "https://tubcloud.tu-berlin.de/s/K62yACBRTrxLTia/download/dsm-profile-example.csv"
dsm_profile = pd.read_csv(url, index_col=0, parse_dates=True).squeeze()
dsm_profile.loc["2015-01-01"].plot(figsize=(5, 2), ylim=(0, 1))
<Axes: xlabel='snapshot'>
_images/7c7ee95b7574511a0b5ce7ad07c5702448edac632aab55a1356e023bee9cf6e7.png
n.add(
    "Store",
    "EV DSM",
    bus="EV",
    carrier="EV battery",
    e_cyclic=True,  # state of charge at beginning = state of charge at the end
    e_nom=e_nom,
    e_min_pu=dsm_profile,
)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[45], line 1
----> 1 n.add(
      2     "Store",
      3     "EV DSM",
      4     bus="EV",
      5     carrier="EV battery",
      6     e_cyclic=True,  # state of charge at beginning = state of charge at the end
      7     e_nom=e_nom,
      8     e_min_pu=dsm_profile,
      9 )

File /opt/hostedtoolcache/Python/3.11.10/x64/lib/python3.11/site-packages/pypsa/components.py:986, in Network.add(self, class_name, name, suffix, overwrite, **kwargs)
    984 if isinstance(v, pd.Series) and single_component:
    985     if not v.index.equals(self.snapshots):
--> 986         raise ValueError(msg.format(f"Series {k}", "network snapshots"))
    987 elif isinstance(v, pd.Series):
    988     # Cast names index to string + suffix
    989     v = v.rename(
    990         index=lambda s: str(s) if str(s).endswith(suffix) else s + suffix
    991     )

ValueError: Series e_min_pu has an index which does not align with the passed network snapshots.

Then, we can solve the fully sector-coupled model altogether including electricity, passenger transport, hydrogen and heating.

n.optimize(solver_name="highs")
n.statistics()
n.statistics()["Capital Expenditure"].div(1e9).sort_values().dropna().plot.bar(
    ylabel="bn€/a", cmap="tab20c", figsize=(7, 3)
)

Exercises#

Here are a few things you can do to explore this system:

  • exclude one of transport sector, heating sector, hydrogen demand and investigate what impact it has on system operation and investments

  • vary the charging rates and availability profiles of electric vehicles