Note

You can download this example as a Jupyter notebook or start it in interactive mode.

Single Node Sector Coupling#

[1]:
from urllib.request import urlretrieve

import matplotlib.pyplot as plt
import pandas as pd

import pypsa

plt.style.use("bmh")
[2]:
fn = "network-cem.nc"
url = "https://tubcloud.tu-berlin.de/s/kpWaraGc9LeaxLK/download/" + fn
urlretrieve(url, fn)
[2]:
('network-cem.nc', <http.client.HTTPMessage at 0x7fd410e8d590>)

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).

[3]:
n = pypsa.Network("network-cem.nc")
WARNING:pypsa.io:Importing network from PyPSA version v0.21.3 while current version is v0.32.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
[4]:
n
[4]:
PyPSA Network
-------------
Components:
 - Bus: 1
 - Carrier: 6
 - Generator: 4
 - GlobalConstraint: 1
 - Load: 1
 - StorageUnit: 2
Snapshots: 2190
[5]:
n.buses.index
[5]:
Index(['Germany'], dtype='object', name='Bus')
[6]:
n.generators.index
[6]:
Index(['OCGT', 'onwind', 'offwind', 'solar'], dtype='object', name='Generator')
[7]:
n.storage_units.index
[7]:
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:

[8]:
n.remove("StorageUnit", "hydrogen storage underground")

Add a separate Bus for the hydrogen energy carrier:

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

Add a Link for the hydrogen electrolysis:

[10]:
n.add(
    "Link",
    "electrolysis",
    bus0="electricity",
    bus1="hydrogen",
    carrier="electrolysis",
    p_nom_extendable=True,
    efficiency=0.7,
    capital_cost=50e3,  # €/MW/a
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['electrolysis'], dtype='object')
[10]:
Index(['electrolysis'], dtype='object')

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

[11]:
n.add(
    "Link",
    "fuel cell",
    bus0="hydrogen",
    bus1="electricity",
    carrier="fuel cell",
    p_nom_extendable=True,
    efficiency=0.5,
    capital_cost=120e3,  # €/MW/a
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['fuel cell'], dtype='object')
[11]:
Index(['fuel cell'], dtype='object')

Add a Store for the hydrogen storage:

[12]:
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
)
[12]:
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.

[13]:
p_set = n.loads_t.p_set["demand"].mean()
[14]:
p_set
[14]:
54671.88812785388
[15]:
n.add("Load", "hydrogen demand", bus="hydrogen", carrier="hydrogen", p_set=p_set)  # MW
[15]:
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:

[16]:
n.add("Bus", "heat")
[16]:
Index(['heat'], dtype='object')
[17]:
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()
[18]:
p_set.head()
[18]:
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
[19]:
n.add("Load", "heat demand", carrier="heat", bus="heat", p_set=p_set)
[19]:
Index(['heat demand'], dtype='object')
[20]:
n.loads_t.p_set.div(1e3).plot(figsize=(12, 4), ylabel="GW")
[20]:
<Axes: xlabel='snapshot', ylabel='GW'>
../_images/examples_sector-coupling-single-node_31_1.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}\).

[21]:
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
[22]:
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]
[23]:
cop(temp).plot(figsize=(10, 2), ylabel="COP");
../_images/examples_sector-coupling-single-node_36_0.png
[24]:
plt.scatter(temp, cop(temp))
plt.xlabel("temperature [°C]")
plt.ylabel("COP [-]")
[24]:
Text(0, 0.5, 'COP [-]')
../_images/examples_sector-coupling-single-node_37_1.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.

[25]:
n.add(
    "Link",
    "heat pump",
    carrier="heat pump",
    bus0="electricity",
    bus1="heat",
    efficiency=cop(temp),
    p_nom_extendable=True,
    capital_cost=3e5,  # €/MWe/a
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['heat pump'], dtype='object')
[25]:
Index(['heat pump'], dtype='object')

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

[26]:
n.add(
    "Link",
    "resistive heater",
    carrier="resistive heater",
    bus0="electricity",
    bus1="heat",
    efficiency=0.9,
    capital_cost=1e4,  # €/MWe/a
    p_nom_extendable=True,
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['resistive heater'], dtype='object')
[26]:
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.

[27]:
n.remove("GlobalConstraint", "CO2Limit")

Then, we explicitly represent the energy carrier gas:

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

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

[29]:
n.add(
    "Store",
    "gas storage",
    carrier="gas storage",
    e_initial=100e6,  # MWh
    e_nom=100e6,  # MWh
    bus="gas",
    marginal_cost=150,  # €/MWh_th
)
[29]:
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.

[30]:
n.remove("Generator", "OCGT")
[31]:
n.add(
    "Link",
    "OCGT",
    bus0="gas",
    bus1="electricity",
    carrier="OCGT",
    p_nom_extendable=True,
    capital_cost=20000,  # €/MW/a
    efficiency=0.4,
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['OCGT'], dtype='object')
[31]:
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

[32]:
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,
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['CHP'], dtype='object')
[32]:
Index(['CHP'], dtype='object')

Electric Vehicles#

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

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

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

[34]:
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()
[35]:
p_set.loc["2015-01-01"].div(1e3).plot(figsize=(4, 4), ylabel="GW")
[35]:
<Axes: xlabel='snapshot', ylabel='GW'>
../_images/examples_sector-coupling-single-node_59_1.png
[36]:
n.add("Load", "EV demand", bus="EV", carrier="EV demand", p_set=p_set)
[36]:
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:

[37]:
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()
[37]:
<matplotlib.legend.Legend at 0x7fd40101d090>
../_images/examples_sector-coupling-single-node_62_1.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.

[38]:
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()
[39]:
availability_profile.loc["2015-01-01"].plot(ylim=(0, 1))
[39]:
<Axes: xlabel='snapshot'>
../_images/examples_sector-coupling-single-node_65_1.png

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

[40]:
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
[41]:
n.add(
    "Link",
    "EV charger",
    bus0="electricity",
    bus1="EV",
    p_nom=p_nom,
    carrier="EV charger",
    p_max_pu=availability_profile,
    efficiency=0.9,
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['EV charger'], dtype='object')
[41]:
Index(['EV charger'], dtype='object')

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

[42]:
n.add(
    "Link",
    "V2G",
    bus0="EV",
    bus1="electricity",
    p_nom=p_nom,
    carrier="V2G",
    p_max_pu=availability_profile,
    efficiency=0.9,
)
WARNING:pypsa.io:The following Link have buses which are not defined:
Index(['V2G'], dtype='object')
[42]:
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).

[43]:
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
[44]:
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()
[45]:
dsm_profile.loc["2015-01-01"].plot(figsize=(5, 2), ylim=(0, 1))
[45]:
<Axes: xlabel='snapshot'>
../_images/examples_sector-coupling-single-node_74_1.png
[46]:
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[46], 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 ~/checkouts/readthedocs.org/user_builds/pypsa/envs/latest/lib/python3.13/site-packages/pypsa/networks.py:1169, in Network.add(self, class_name, name, suffix, overwrite, **kwargs)
   1167 if isinstance(v, pd.Series) and single_component:
   1168     if not v.index.equals(self.snapshots):
-> 1169         raise ValueError(msg.format(f"Series {k}", "network snapshots"))
   1170 elif isinstance(v, pd.Series):
   1171     # Cast names index to string + suffix
   1172     v = v.rename(
   1173         index=lambda s: str(s)
   1174         if str(s).endswith(suffix)
   1175         else str(s) + suffix
   1176     )

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.

[47]:
n.optimize(solver_name="highs")
---------------------------------------------------------------------------
ConsistencyError                          Traceback (most recent call last)
Cell In[47], line 1
----> 1 n.optimize(solver_name="highs")

File ~/checkouts/readthedocs.org/user_builds/pypsa/envs/latest/lib/python3.13/site-packages/pypsa/optimization/optimize.py:633, in OptimizationAccessor.__call__(self, *args, **kwargs)
    631 @wraps(optimize)
    632 def __call__(self, *args: Any, **kwargs: Any) -> Any:
--> 633     return optimize(self.n, *args, **kwargs)

File ~/checkouts/readthedocs.org/user_builds/pypsa/envs/latest/lib/python3.13/site-packages/pypsa/optimization/optimize.py:593, in optimize(n, snapshots, multi_investment_periods, transmission_losses, linearized_unit_commitment, model_kwargs, extra_functionality, assign_all_duals, solver_name, solver_options, compute_infeasibilities, **kwargs)
    590 n._multi_invest = int(multi_investment_periods)
    591 n._linearized_uc = linearized_unit_commitment
--> 593 n.consistency_check(strict=["unknown_buses"])
    594 m = create_model(
    595     n,
    596     sns,
   (...)
    601     **model_kwargs,
    602 )
    603 if extra_functionality:

File ~/checkouts/readthedocs.org/user_builds/pypsa/envs/latest/lib/python3.13/site-packages/pypsa/consistency.py:841, in consistency_check(n, check_dtypes, strict)
    835 # TODO: Check for bidirectional links with efficiency < 1.
    836 # TODO: Warn if any ramp limits are 0.
    837
    838 # Per component checks
    839 for c in n.iterate_components():
    840     # Checks all components
--> 841     check_for_unknown_buses(n, c, "unknown_buses" in strict)
    842     check_for_unknown_carriers(n, c, "unkown_carriers" in strict)
    843     check_time_series(n, c, "time_series" in strict)

File ~/checkouts/readthedocs.org/user_builds/pypsa/envs/latest/lib/python3.13/site-packages/pypsa/common.py:148, in deprecated_kwargs.<locals>.deco.<locals>.wrapper(*args, **kwargs)
    145 @functools.wraps(f)
    146 def wrapper(*args: Any, **kwargs: Any) -> Any:
    147     rename_kwargs(f.__name__, kwargs, aliases)
--> 148     return f(*args, **kwargs)

File ~/checkouts/readthedocs.org/user_builds/pypsa/envs/latest/lib/python3.13/site-packages/pypsa/consistency.py:71, in check_for_unknown_buses(n, component, strict)
     69     missing &= component.static[attr] != ""
     70 if missing.any():
---> 71     _log_or_raise(
     72         strict,
     73         "The following %s have buses which are not defined:\n%s",
     74         component.list_name,
     75         component.static.index[missing],
     76     )

File ~/checkouts/readthedocs.org/user_builds/pypsa/envs/latest/lib/python3.13/site-packages/pypsa/consistency.py:35, in _log_or_raise(strict, message, *args)
     33 def _log_or_raise(strict: bool, message: str, *args: Any) -> None:
     34     if strict:
---> 35         raise ConsistencyError(message % args)
     36     else:
     37         logger.warning(message, *args)

ConsistencyError: The following links have buses which are not defined:
Index(['electrolysis', 'heat pump', 'resistive heater', 'EV charger'], dtype='object', name='Link')
[48]:
n.statistics()
[48]:
Optimal Capacity Installed Capacity Supply Withdrawal Energy Balance Transmission Capacity Factor Curtailment Capital Expenditure Operational Expenditure Revenue Market Value
Generator offwind 76925.171 0.0 2.357026e+08 0.000000e+00 2.357026e+08 0.0 0.349777 8.769440e+06 1.216370e+10 4.714053e+06 1.216841e+10 51.626120
onwind 225963.170 0.0 6.796894e+07 0.000000e+00 6.796894e+07 0.0 0.034338 3.392856e+08 2.171187e+10 9.175807e+07 2.180363e+10 320.788152
solar 248437.270 0.0 2.665099e+08 0.000000e+00 2.665099e+08 0.0 0.122459 3.757182e+06 1.155454e+10 2.665099e+06 1.155721e+10 43.365024
Link EV charger 0.000 440000.0 0.000000e+00 0.000000e+00 0.000000e+00 0.0 0.000000 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000
V2G 0.000 440000.0 0.000000e+00 0.000000e+00 0.000000e+00 0.0 0.000000 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000
Load - 0.000 0.0 0.000000e+00 4.789257e+08 -4.789257e+08 0.0 NaN 0.000000e+00 0.000000e+00 0.000000e+00 -6.581318e+10 NaN
StorageUnit battery storage 34106.690 0.0 4.307521e+07 4.673960e+07 -3.664388e+06 0.0 0.300611 3.024390e+08 3.289077e+09 0.000000e+00 3.289077e+09 76.356612
Store gas storage 0.000 100000000.0 0.000000e+00 0.000000e+00 0.000000e+00 0.0 0.000000 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000
[49]:
n.statistics()["Capital Expenditure"].div(1e9).sort_values().dropna().plot.bar(
    ylabel="bn€/a", cmap="tab20c", figsize=(7, 3)
)
[49]:
<Axes: ylabel='bn€/a'>
../_images/examples_sector-coupling-single-node_79_1.png
[ ]: