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!
import pandas as pd
import pypsaimport 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!
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!
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 and lifetime .
In [5]:
Copied!
from pypsa.costs import annuityfrom pypsa.costs import annuity
In [6]:
Copied!
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!
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!
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!
ts.head(3)ts.head(3)
Out[9]:
| load_mw | pv_pu | wind_pu | |
|---|---|---|---|
| timestamp | |||
| 2019-01-01 00:00:00 | 5719.26 | 0.0 | 0.1846 |
| 2019-01-01 03:00:00 | 5474.74 | 0.0 | 0.3146 |
| 2019-01-01 06:00:00 | 5413.39 | 0.0 | 0.4957 |
Model initialisation
In [10]:
Copied!
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)
/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 in problem formulation above) must be set in n.snapshot_weightings.
In [11]:
Copied!
n.snapshot_weightings.loc[:, :] = RESOLUTIONn.snapshot_weightings.loc[:, :] = RESOLUTION
Adding carriers (this is only necessary for convenience in plotting later):
In [12]:
Copied!
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!
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!
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!
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!
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!
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!
n.add("Bus", "hydrogen", carrier="hydrogen")n.add("Bus", "hydrogen", carrier="hydrogen")
In [19]:
Copied!
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!
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!
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!
n.optimize()n.optimize()
/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()INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/17 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 17/17 [00:00<00:00, 198.32it/s]Writing continuous variables.: 0%| | 0/8 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 8/8 [00:00<00:00, 389.50it/s]INFO:linopy.io: Writing time: 0.13sSet parameter WLSAccessIDSet parameter WLSSecretSet parameter LicenseID to value 2537914Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.deRead LP format model from file /tmp/linopy-problem-800yp1gz.lpReading time = 0.09 secondsobj: 70086 rows, 32126 columns, 132904 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO: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]:
('ok', 'optimal')Model evaluation
Total system cost by technology:
In [23]:
Copied!
tsc = (
pd.concat([n.statistics.capex(), n.statistics.opex()], axis=1).sum(axis=1).div(1e9)
)
tsctsc = ( pd.concat([n.statistics.capex(), n.statistics.opex()], axis=1).sum(axis=1).div(1e9) ) tsc
Out[23]:
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: float64In [24]:
Copied!
tsc.sum()tsc.sum()
Out[24]:
np.float64(10.13258693337856)The optimised capacities in GW (GWh for Store component):
In [25]:
Copied!
n.statistics.optimal_capacity().div(1e3)n.statistics.optimal_capacity().div(1e3)
Out[25]:
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: float64Energy balances on electricity side (in TWh):
In [26]:
Copied!
n.statistics.energy_balance(bus_carrier="electricity").sort_values().div(1e6)n.statistics.energy_balance(bus_carrier="electricity").sort_values().div(1e6)
Out[26]:
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: float64Energy balances plot as time series (in MW):
In [27]:
Copied!
n.statistics.energy_balance.plot.area(linewidth=0, bus_carrier="electricity")n.statistics.energy_balance.plot.area(linewidth=0, bus_carrier="electricity")
Out[27]:
(<Figure size 759x300 with 1 Axes>,
<Axes: xlabel='snapshot', ylabel='Energy Balance []'>,
<seaborn.axisgrid.FacetGrid at 0x70170a8d2510>)
Price time series for electricity and hydrogen:
In [28]:
Copied!
n.buses_t.marginal_price.plot(figsize=(7, 2))n.buses_t.marginal_price.plot(figsize=(7, 2))
Out[28]:
<Axes: xlabel='snapshot'>
2026-11-02
2024-05-27