Post · 10 min read· pp. 59–71

1-Node Capacity Expansion

In this example, we build a replica of model.energy. This tool calculates the cost of meeting a constant electricity demand from a combination of wind power, solar power and storage for different regions of the world. It includes capacity investments and dispatch optimisation. We deviate from model.energy by including an electricity demand profiles rather than a constant electricity demand.

In [2]:

Copied! diagram

ipynb
import pandas as pd

import pypsa

import pandas as pd import pypsa

Techno-economic assumptions

We take techno-economic assumptions from the technology-data repository which collects assumptions on costs and efficiencies:

In [3]:

Copied! diagram

ipynb
YEAR = 2030
url = f"https://raw.githubusercontent.com/PyPSA/technology-data/master/outputs/costs_{YEAR}.csv"
costs = pd.read_csv(url, index_col=[0, 1])
costs.loc[costs.unit.str.contains("/kW"), "value"] *= 1e3
costs = costs.value.unstack().fillna({"discount rate": 0.07, "lifetime": 20, "FOM": 0})

YEAR = 2030 url = f"https://raw.githubusercontent.com/PyPSA/technology-data/master/outputs/costs\_{YEAR}.csv" costs = pd.read_csv(url, index_col=[0, 1]) costs.loc[costs.unit.str.contains("/kW"), "value"] *= 1e3 costs = costs.value.unstack().fillna({"discount rate": 0.07, "lifetime": 20, "FOM": 0})

Based on this, we calculate the marginal costs (€/MWh):

In [4]:

Copied! diagram

ipynb
costs["marginal_cost"] = costs["VOM"] + costs["fuel"] / costs["efficiency"]

costs["marginal_cost"] = costs["VOM"] + costs["fuel"] / costs["efficiency"]

We also calculate the capital costs (i.e. annualised investment costs, €/MW/a or €/MWh/a for storage), using a small utility function to calculate the annuity factor to annualise investment costs based on is the discount rate rr and lifetime nn.

In [5]:

Copied! diagram

ipynb
from pypsa.costs import annuity

from pypsa.costs import annuity

In [6]:

Copied! diagram

ipynb
a = costs.apply(lambda x: annuity(x["discount rate"], x["lifetime"]), axis=1)

a = costs.apply(lambda x: annuity(x["discount rate"], x["lifetime"]), axis=1)

In [7]:

Copied! diagram

ipynb
costs["capital_cost"] = (a + costs["FOM"] / 100) * costs["investment"]

costs["capital_cost"] = (a + costs["FOM"] / 100) * costs["investment"]

Wind, solar and load time series

In [8]:

Copied! diagram

ipynb
RESOLUTION = 3  # hours
url = "https://tubcloud.tu-berlin.de/s/9toBssWEdaLgHzq/download/time-series.csv"
ts = pd.read_csv(url, index_col=0, parse_dates=True)[::RESOLUTION]

RESOLUTION = 3 # hours url = "https://tubcloud.tu-berlin.de/s/9toBssWEdaLgHzq/download/time-series.csv" ts = pd.read_csv(url, index_col=0, parse_dates=True)[::RESOLUTION]

In [9]:

Copied! diagram

ipynb
ts.head(3)

ts.head(3)

Out[9]:

load_mwpv_puwind_pu
timestamp
2019-01-01 00:00:005719.260.00.1846
2019-01-01 03:00:005474.740.00.3146
2019-01-01 06:00:005413.390.00.4957

Model initialisation

In [10]:

Copied! diagram

ipynb
n = pypsa.Network()
n.add("Bus", "electricity", carrier="electricity")
n.set_snapshots(ts.index)

n = pypsa.Network() n.add("Bus", "electricity", carrier="electricity") n.set_snapshots(ts.index)

text
/tmp/ipykernel_2785/309965534.py:1: PyPSA2Warning: pandas reads strings as `str` dtype since 3.0. PyPSA converts them back to object dtype on import, but keeps `str` from PyPSA 2.0 on. Set `pypsa.options.future.string_dtype` to True to opt in now or to False to keep the current behaviour.
  n = pypsa.Network()

The weighting of the snapshots (e.g. how many hours they represent, see wtw_t in problem formulation above) must be set in n.snapshot_weightings.

In [11]:

Copied! diagram

ipynb
n.snapshot_weightings.loc[:, :] = RESOLUTION

n.snapshot_weightings.loc[:, :] = RESOLUTION

Adding carriers (this is only necessary for convenience in plotting later):

In [12]:

Copied! diagram

ipynb
carriers = [
    "wind",
    "solar",
    "hydrogen storage",
    "battery storage",
    "load shedding",
    "electrolysis",
    "turbine",
    "electricity",
    "hydrogen",
]
colors = [
    "dodgerblue",
    "gold",
    "black",
    "yellowgreen",
    "darkorange",
    "magenta",
    "red",
    "grey",
    "grey",
]
n.add("Carrier", carriers, color=colors)

carriers = [ "wind", "solar", "hydrogen storage", "battery storage", "load shedding", "electrolysis", "turbine", "electricity", "hydrogen", ] colors = [ "dodgerblue", "gold", "black", "yellowgreen", "darkorange", "magenta", "red", "grey", "grey", ] n.add("Carrier", carriers, color=colors)

Adding load:

In [13]:

Copied! diagram

ipynb
n.add(
    "Load",
    "demand",
    bus="electricity",
    p_set=ts.load_mw,
)

n.add( "Load", "demand", bus="electricity", p_set=ts.load_mw, )

Add a load shedding generator with high marginal cost of 2000 €/MWh:

In [14]:

Copied! diagram

ipynb
n.add(
    "Generator",
    "load shedding",
    bus="electricity",
    carrier="load shedding",
    marginal_cost=2000,
    p_nom=ts.load_mw.max(),
)

n.add( "Generator", "load shedding", bus="electricity", carrier="load shedding", marginal_cost=2000, p_nom=ts.load_mw.max(), )

Adding the variable renewable generators works almost identically, but we also need to supply the capacity factors to the model via the attribute p_max_pu.

In [15]:

Copied! diagram

ipynb
n.add(
    "Generator",
    "wind",
    bus="electricity",
    carrier="wind",
    p_max_pu=ts.wind_pu,
    capital_cost=costs.at["onwind", "capital_cost"],
    marginal_cost=costs.at["onwind", "marginal_cost"],
    p_nom_extendable=True,
)

n.add( "Generator", "wind", bus="electricity", carrier="wind", p_max_pu=ts.wind_pu, capital_cost=costs.at["onwind", "capital_cost"], marginal_cost=costs.at["onwind", "marginal_cost"], p_nom_extendable=True, )

In [16]:

Copied! diagram

ipynb
n.add(
    "Generator",
    "solar",
    bus="electricity",
    carrier="solar",
    p_max_pu=ts.pv_pu,
    capital_cost=costs.at["solar", "capital_cost"],
    marginal_cost=costs.at["solar", "marginal_cost"],
    p_nom_extendable=True,
)

n.add( "Generator", "solar", bus="electricity", carrier="solar", p_max_pu=ts.pv_pu, capital_cost=costs.at["solar", "capital_cost"], marginal_cost=costs.at["solar", "marginal_cost"], p_nom_extendable=True, )

Adding a 3-hour battery:

In [17]:

Copied! diagram

ipynb
n.add(
    "Store",
    "battery storage",
    bus="electricity",
    carrier="battery storage",
    max_hours=3,
    capital_cost=costs.at["battery inverter", "capital_cost"] / 3
    + costs.at["battery storage", "capital_cost"],
    efficiency_store=costs.at["battery inverter", "efficiency"],
    efficiency_dispatch=costs.at["battery inverter", "efficiency"],
    e_nom_extendable=True,
    e_cyclic=True,
)

n.add( "Store", "battery storage", bus="electricity", carrier="battery storage", max_hours=3, capital_cost=costs.at["battery inverter", "capital_cost"] / 3

  • costs.at["battery storage", "capital_cost"], efficiency_store=costs.at["battery inverter", "efficiency"], efficiency_dispatch=costs.at["battery inverter", "efficiency"], e_nom_extendable=True, e_cyclic=True, )

Adding a hydrogen storage system consisting of electrolyser, hydrogen turbine and underground storage, which can all be flexibly optimised:

In [18]:

Copied! diagram

ipynb
n.add("Bus", "hydrogen", carrier="hydrogen")

n.add("Bus", "hydrogen", carrier="hydrogen")

In [19]:

Copied! diagram

ipynb
n.add(
    "Link",
    "electrolysis",
    bus0="electricity",
    bus1="hydrogen",
    carrier="electrolysis",
    p_nom_extendable=True,
    efficiency=costs.at["electrolysis", "efficiency"],
    capital_cost=costs.at["electrolysis", "capital_cost"],
)

n.add( "Link", "electrolysis", bus0="electricity", bus1="hydrogen", carrier="electrolysis", p_nom_extendable=True, efficiency=costs.at["electrolysis", "efficiency"], capital_cost=costs.at["electrolysis", "capital_cost"], )

In [20]:

Copied! diagram

ipynb
n.add(
    "Link",
    "turbine",
    bus0="hydrogen",
    bus1="electricity",
    carrier="turbine",
    p_nom_extendable=True,
    efficiency=costs.at["OCGT", "efficiency"],
    capital_cost=costs.at["OCGT", "capital_cost"] / costs.at["OCGT", "efficiency"],
)

n.add( "Link", "turbine", bus0="hydrogen", bus1="electricity", carrier="turbine", p_nom_extendable=True, efficiency=costs.at["OCGT", "efficiency"], capital_cost=costs.at["OCGT", "capital_cost"] / costs.at["OCGT", "efficiency"], )

In [21]:

Copied! diagram

ipynb
n.add(
    "Store",
    "hydrogen storage",
    bus="hydrogen",
    carrier="hydrogen storage",
    capital_cost=costs.at["hydrogen storage underground", "capital_cost"],
    e_nom_extendable=True,
    e_cyclic=True,
)

n.add( "Store", "hydrogen storage", bus="hydrogen", carrier="hydrogen storage", capital_cost=costs.at["hydrogen storage underground", "capital_cost"], e_nom_extendable=True, e_cyclic=True, )

Model run

In [22]:

Copied! diagram

ipynb
n.optimize()

n.optimize()

text
/tmp/ipykernel_2785/1261279110.py:1: PyPSA2Warning: From PyPSA 2.0 on, the objective leaves out the capital costs of existing capacity on extendable assets, which improves LP conditioning. Pass `include_objective_constant` to `n.optimize` to choose per call. Set `pypsa.options.future.exclude_objective_constant` to True to opt in now or to False to keep the current behaviour.
  n.optimize()
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io:Writing objective.
text
Writing constraints.:   0%|          | 0/17 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 17/17 [00:00<00:00, 198.32it/s]
text
text
Writing continuous variables.:   0%|          | 0/8 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 8/8 [00:00<00:00, 389.50it/s]
text
INFO:linopy.io: Writing time: 0.13s
text
Set parameter WLSAccessID
text
Set parameter WLSSecret
text
Set parameter LicenseID to value 2537914
text
Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.de
text
Read LP format model from file /tmp/linopy-problem-800yp1gz.lp
text
Reading time = 0.09 seconds
text
obj: 70086 rows, 32126 columns, 132904 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 32126 primals, 75926 duals
Objective: 1.01e+10
Solver: gurobi
Runtime: 1.52s
Dual bound: 1.01e+10
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Generator-ext-p-lower, Generator-ext-p-upper, Link-ext-p-lower, Link-ext-p-upper, Store-ext-e-lower, Store-ext-e-upper, Store-ext-p-lower, Store-ext-p-upper, Store-ext-p_store-lower, Store-ext-p_store-upper, Store-energy_balance were not assigned to the network.

Out[22]:

text
('ok', 'optimal')

Model evaluation

Total system cost by technology:

In [23]:

Copied! diagram

ipynb
tsc = (
    pd.concat([n.statistics.capex(), n.statistics.opex()], axis=1).sum(axis=1).div(1e9)
)
tsc

tsc = ( pd.concat([n.statistics.capex(), n.statistics.opex()], axis=1).sum(axis=1).div(1e9) ) tsc

Out[23]:

text
component  carrier         
Generator  solar               1.684343
           wind                4.180646
Link       electrolysis        0.739954
           turbine             1.424007
Store      battery storage     1.124633
           hydrogen storage    0.688179
Generator  load shedding       0.290825
dtype: float64

In [24]:

Copied! diagram

ipynb
tsc.sum()

tsc.sum()

Out[24]:

text
np.float64(10.13258693337856)

The optimised capacities in GW (GWh for Store component):

In [25]:

Copied! diagram

ipynb
n.statistics.optimal_capacity().div(1e3)

n.statistics.optimal_capacity().div(1e3)

Out[25]:

text
component  carrier         
Generator  load shedding         10.901160
           solar                 26.089521
           wind                  32.583318
Link       electrolysis           3.118498
           turbine                9.692634
Store      battery storage       42.143840
           hydrogen storage    3672.190855
dtype: float64

Energy balances on electricity side (in TWh):

In [26]:

Copied! diagram

ipynb
n.statistics.energy_balance(bus_carrier="electricity").sort_values().div(1e6)

n.statistics.energy_balance(bus_carrier="electricity").sort_values().div(1e6)

Out[26]:

text
component  carrier          bus_carrier
Load       -                electricity   -66.266089
Link       electrolysis     electricity   -15.656979
Store      battery storage  electricity    -0.765607
Generator  load shedding    electricity     0.145412
Link       turbine          electricity     3.990917
Generator  solar            electricity    28.551848
           wind             electricity    50.000498
dtype: float64

Energy balances plot as time series (in MW):

In [27]:

Copied! diagram

ipynb
n.statistics.energy_balance.plot.area(linewidth=0, bus_carrier="electricity")

n.statistics.energy_balance.plot.area(linewidth=0, bus_carrier="electricity")

Out[27]:

text
(<Figure size 759x300 with 1 Axes>,
 <Axes: xlabel='snapshot', ylabel='Energy Balance []'>,
 <seaborn.axisgrid.FacetGrid at 0x70170a8d2510>)

No description has been provided for this image

Price time series for electricity and hydrogen:

In [28]:

Copied! diagram

ipynb
n.buses_t.marginal_price.plot(figsize=(7, 2))

n.buses_t.marginal_price.plot(figsize=(7, 2))

Out[28]:

text
<Axes: xlabel='snapshot'>

No description has been provided for this image

diagram 2026-11-02

diagram 2024-05-27