Post · 13 min read· pp. 567–579

Pathway Planning

In this example, we demonstrate how PyPSA can deal with optimisation problems spanning multiple investment periods, also known as pathway planning.

For models with multiple investment periods, the total set of snapshots is divided into investment periods, which translates into multi-indexed snapshots with investment periods as the first level time steps as the second level. In each investment period, new components may be added to the system. Additionally, any component may only operate as long as allowed by their lifetime.

In contrast to the models with a single investment period (overnight scenarios), the following concepts have to be taken into account.:

  1. The network attribute n.investment_periods: This is the set of periods which specify when new components may be built. These have to be the same as the first level values in the n.snapshots index.
  2. The network attribute n.investment_period_weightings: These specify the weighting of each period in the objective function and the global constraints.
  3. The component attribute build_year: Any one component may only be built when the build year is equal to the current investment period, or larger than the previous investment period. That means, components with build_year=2029 are considered in the investment period 2030, but not in the period 2025.
  4. The component attribute lifetime: Any one component is only considered for dispatch in an investment period if it is still active at the beginning of an investment period. That means, components with build_year=2029 and lifetime=30 are considered in the investment period 2055, but not in the period 2060.

In the following, we set up a three bus network with generators, lines and storage units and run a optimisation for the investment periods 2020, 2030, 2040 and 2050.

In [2]:

Copied! diagram

ipynb
import numpy as np
import pandas as pd

import pypsa

rng = np.random.default_rng()  # Create a random number generator

import numpy as np import pandas as pd import pypsa rng = np.random.default_rng() # Create a random number generator

We set up the network with investment periods and snapshots.

In [3]:

Copied! diagram

ipynb
n = pypsa.Network()
years = [2020, 2030, 2040, 2050]
freq = 24

snapshots = pd.DatetimeIndex([])
for year in years:
    period = pd.date_range(
        start=f"{year}-01-01 00:00",
        freq=f"{freq}h",
        periods=8760 // freq,
    )
    snapshots = snapshots.append(period)

# convert to multiindex and assign to network
n.snapshots = pd.MultiIndex.from_arrays([snapshots.year, snapshots])
n.investment_periods = years

n.snapshot_weightings

n = pypsa.Network() years = [2020, 2030, 2040, 2050] freq = 24 snapshots = pd.DatetimeIndex([]) for year in years: period = pd.date_range( start=f"{year}-01-01 00:00", freq=f"{freq}h", periods=8760 // freq, ) snapshots = snapshots.append(period)

convert to multiindex and assign to network

n.snapshots = pd.MultiIndex.from_arrays([snapshots.year, snapshots]) n.investment_periods = years n.snapshot_weightings

text
/tmp/ipykernel_4316/349236114.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()

Out[3]:

objectivestoresgenerators
periodtimestep
20202020-01-011.01.01.0
2020-01-021.01.01.0
2020-01-031.01.01.0
2020-01-041.01.01.0
2020-01-051.01.01.0
...............
20502050-12-271.01.01.0
2050-12-281.01.01.0
2050-12-291.01.01.0
2050-12-301.01.01.0
2050-12-311.01.01.0

1460 rows × 3 columns

In [4]:

Copied! diagram

ipynb
n.investment_periods

n.investment_periods

Out[4]:

text
Index([2020, 2030, 2040, 2050], dtype='int32', name='period')

Set the years and objective weighting per investment period. For the objective weighting, we consider a discount rate defined by

D(t)=1(1+r)tD(t) = \dfrac{1}{(1+r)^t}

where rr is the discount rate. For each period we sum up all discounts rates of the corresponding years which gives us the effective objective weighting.

In [5]:

Copied! diagram

ipynb
n.investment_period_weightings["years"] = list(np.diff(years)) + [10]

r = 0.01
T = 0
for period, nyears in n.investment_period_weightings.years.items():
    discounts = [(1 / (1 + r) ** t) for t in range(T, T + nyears)]
    n.investment_period_weightings.at[period, "objective"] = sum(discounts)
    T += nyears
n.investment_period_weightings

n.investment_period_weightings["years"] = list(np.diff(years)) + [10] r = 0.01 T = 0 for period, nyears in n.investment_period_weightings.years.items(): discounts = [(1 / (1 + r) ** t) for t in range(T, T + nyears)] n.investment_period_weightings.at[period, "objective"] = sum(discounts) T += nyears n.investment_period_weightings

Out[5]:

objectiveyears
period
20209.56601810
20308.65999110
20407.83977710
20507.09724810

Add the components

In [6]:

Copied! diagram

ipynb
for i in range(3):
    n.add("Bus", f"bus {i}")

# add three lines in a ring
n.add(
    "Line",
    "line 0->1",
    bus0="bus 0",
    bus1="bus 1",
)

n.add(
    "Line",
    "line 1->2",
    bus0="bus 1",
    bus1="bus 2",
    capital_cost=10,
    build_year=2030,
)

n.add(
    "Line",
    "line 2->0",
    bus0="bus 2",
    bus1="bus 0",
)

n.lines["x"] = 0.0001
n.lines["s_nom_extendable"] = True

n.lines

for i in range(3): n.add("Bus", f"bus {i}")

add three lines in a ring

n.add( "Line", "line 0->1", bus0="bus 0", bus1="bus 1", ) n.add( "Line", "line 1->2", bus0="bus 1", bus1="bus 2", capital_cost=10, build_year=2030, ) n.add( "Line", "line 2->0", bus0="bus 2", bus1="bus 0", ) n.lines["x"] = 0.0001 n.lines["s_nom_extendable"] = True n.lines

Out[6]:

bus0bus1typexrgbs_noms_nom_mods_nom_extendable...v_ang_maxsub_networkx_pur_pug_pub_pux_pu_effr_pu_effs_nom_optcapital_cost_piecewise_opt
name
line 0->1bus 0bus 10.00010.00.00.00.00.0True...inf0.00.00.00.00.00.00.00.0
line 1->2bus 1bus 20.00010.00.00.00.00.0True...inf0.00.00.00.00.00.00.00.0
line 2->0bus 2bus 00.00010.00.00.00.00.0True...inf0.00.00.00.00.00.00.00.0

3 rows × 36 columns

In [7]:

Copied! diagram

ipynb
# add some generators
p_nom_max = pd.Series(
    (rng.uniform() for sn in range(len(n.snapshots))),
    index=n.snapshots,
    name="generator ext 2020",
)

# renewable (can operate 2020, 2030)
n.add(
    "Generator",
    "generator ext 0 2020",
    bus="bus 0",
    p_nom=50,
    build_year=2020,
    lifetime=20,
    marginal_cost=2,
    capital_cost=1,
    p_max_pu=p_nom_max,
    carrier="solar",
    p_nom_extendable=True,
)

# can operate 2040, 2050
n.add(
    "Generator",
    "generator ext 0 2040",
    bus="bus 0",
    p_nom=50,
    build_year=2040,
    lifetime=11,
    marginal_cost=25,
    capital_cost=10,
    carrier="OCGT",
    p_nom_extendable=True,
)

# can operate in 2040
n.add(
    "Generator",
    "generator fix 1 2040",
    bus="bus 1",
    p_nom=50,
    build_year=2040,
    lifetime=10,
    carrier="CCGT",
    marginal_cost=20,
    capital_cost=1,
)

n.generators

add some generators

p_nom_max = pd.Series( (rng.uniform() for sn in range(len(n.snapshots))), index=n.snapshots, name="generator ext 2020", )

renewable (can operate 2020, 2030)

n.add( "Generator", "generator ext 0 2020", bus="bus 0", p_nom=50, build_year=2020, lifetime=20, marginal_cost=2, capital_cost=1, p_max_pu=p_nom_max, carrier="solar", p_nom_extendable=True, )

can operate 2040, 2050

n.add( "Generator", "generator ext 0 2040", bus="bus 0", p_nom=50, build_year=2040, lifetime=11, marginal_cost=25, capital_cost=10, carrier="OCGT", p_nom_extendable=True, )

can operate in 2040

n.add( "Generator", "generator fix 1 2040", bus="bus 1", p_nom=50, build_year=2040, lifetime=10, carrier="CCGT", marginal_cost=20, capital_cost=1, ) n.generators

Out[7]:

buscontroltypep_nomp_nom_modp_nom_extendablep_nom_minp_nom_maxp_nom_setp_min_pu...down_time_beforeramp_limit_upramp_limit_downramp_limit_start_upramp_limit_shut_downramp_up_costramp_down_costweightp_nom_optcapital_cost_piecewise_opt
name
generator ext 0 2020bus 0PQ50.00.0True0.0infNaN0.0...0NaNNaNNaNNaN0.00.01.00.00.0
generator ext 0 2040bus 0PQ50.00.0True0.0infNaN0.0...0NaNNaNNaNNaN0.00.01.00.00.0
generator fix 1 2040bus 1PQ50.00.0False0.0infNaN0.0...0NaNNaNNaNNaN0.00.01.00.00.0

3 rows × 49 columns

In [8]:

Copied! diagram

ipynb
n.add(
    "Store",
    "store non-cyclic 2030",
    bus="bus 2",
    e_nom=0,
    capital_cost=2,
    build_year=2030,
    lifetime=21,
    e_cyclic=False,
    e_nom_extendable=False,
)

n.add(
    "Store",
    "store periodic 2020",
    bus="bus 2",
    e_nom=0,
    capital_cost=1,
    build_year=2020,
    lifetime=21,
    e_cyclic=True,
    e_cyclic_per_period=True,
    e_nom_extendable=True,
)

n.stores

n.add( "Store", "store non-cyclic 2030", bus="bus 2", e_nom=0, capital_cost=2, build_year=2030, lifetime=21, e_cyclic=False, e_nom_extendable=False, ) n.add( "Store", "store periodic 2020", bus="bus 2", e_nom=0, capital_cost=1, build_year=2020, lifetime=21, e_cyclic=True, e_cyclic_per_period=True, e_nom_extendable=True, ) n.stores

Out[8]:

buscontroltypecarriere_nome_nom_mode_nom_extendablee_nom_mine_nom_maxe_nom_set...standing_lossefficiency_storeefficiency_dispatchinflowspill_costactivebuild_yearlifetimee_nom_optcapital_cost_piecewise_opt
name
store non-cyclic 2030bus 2PQ0.00.0False0.0infNaN...0.01.01.00.00.0True203021.00.00.0
store periodic 2020bus 2PQ0.00.0True0.0infNaN...0.01.01.00.00.0True202021.00.00.0

2 rows × 45 columns

Add the load

In [9]:

Copied! diagram

ipynb
load_var = pd.Series(
    100 * rng.random(size=len(n.snapshots)), index=n.snapshots, name="load"
)
n.add("Load", "load 2", bus="bus 2", p_set=load_var)

load_fix = pd.Series(75, index=n.snapshots, name="load")
n.add("Load", "load 1", bus="bus 1", p_set=load_fix)

n.loads_t.p_set.head()

load_var = pd.Series( 100 * rng.random(size=len(n.snapshots)), index=n.snapshots, name="load" ) n.add("Load", "load 2", bus="bus 2", p_set=load_var) load_fix = pd.Series(75, index=n.snapshots, name="load") n.add("Load", "load 1", bus="bus 1", p_set=load_fix) n.loads_t.p_set.head()

Out[9]:

nameload 2load 1
periodtimestep
20202020-01-0150.05834375.0
2020-01-0227.99469375.0
2020-01-037.44893675.0
2020-01-0486.77321975.0
2020-01-0544.85944675.0

Run the optimization

In [10]:

Copied! diagram

ipynb
n.optimize(multi_investment_periods=True)

n.optimize(multi_investment_periods=True)

text
/tmp/ipykernel_4316/264390566.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(multi_investment_periods=True)
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['bus 0', 'bus 1', 'bus 2'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following generators have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['generator ext 0 2020', 'generator ext 0 2040', 'generator fix 1 2040'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following stores have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['store non-cyclic 2030', 'store periodic 2020'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following lines have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['line 0->1', 'line 1->2', 'line 2->0'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following lines have zero r, which could break the linear load flow:
Index(['line 0->1', 'line 1->2', 'line 2->0'], dtype='object', name='name')
text
INFO:pypsa.optimization.window:Building the multi-period model over a MultiIndex `snapshot`. Opt into the flat representation via `pypsa.options.optimization.model_snapshot_index = 'flat'`.
text
WARNING:pypsa.optimization.constraints:Stores ['store periodic 2020']: Per-period cyclic (e_cyclic_per_period=True) overrides global cyclic (e_cyclic=True). Storage will cycle within each investment period, not across the entire horizon.
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/24 [00:00<?, ?it/s]
text
Writing constraints.:  92%|█████████▏| 22/24 [00:00<00:00, 218.25it/s]
text
Writing constraints.: 100%|██████████| 24/24 [00:00<00:00, 212.45it/s]
text
text
Writing continuous variables.:   0%|          | 0/9 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 9/9 [00:00<00:00, 349.62it/s]
text
INFO:linopy.io: Writing time: 0.16s
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-ol1brca1.lp
text
Reading time = 0.03 seconds
text
obj: 28111 rows, 12417 columns, 52930 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 17527 primals, 43441 duals
Objective: 1.80e+07
Solver: gurobi
Runtime: 0.06s
Dual bound: 1.80e+07
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, Line-ext-s-lower, Line-ext-s-upper, Store-fix-e-lower, Store-fix-e-upper, Store-ext-e-lower, Store-ext-e-upper, Store-fix-p-lower, Store-fix-p-upper, Store-ext-p-lower, Store-ext-p-upper, Store-fix-p_store-lower, Store-fix-p_store-upper, Store-ext-p_store-lower, Store-ext-p_store-upper, Kirchhoff-Voltage-Law, Store-energy_balance were not assigned to the network.

Out[10]:

text
('ok', 'optimal')

In [11]:

Copied! diagram

ipynb
c = "Generator"
df = pd.concat(
    {
        period: n.components[c].get_active_assets(period)
        * n.components[c].static.p_nom_opt
        for period in n.investment_periods
    },
    axis=1,
)
df.T.plot.bar(
    stacked=True,
    edgecolor="white",
    width=1,
    ylabel="Capacity (MW)",
    xlabel="Investment Period",
    rot=0,
)

c = "Generator" df = pd.concat( { period: n.components[c].get_active_assets(period) * n.components[c].static.p_nom_opt for period in n.investment_periods }, axis=1, ) df.T.plot.bar( stacked=True, edgecolor="white", width=1, ylabel="Capacity (MW)", xlabel="Investment Period", rot=0, )

Out[11]:

text
<Axes: xlabel='Investment Period', ylabel='Capacity (MW)'>

No description has been provided for this image

In [12]:

Copied! diagram

ipynb
df = n.generators_t.p.sum(axis=0).T.div(1e3)
df.T.plot.bar(
    stacked=True,
    edgecolor="white",
    width=1,
    ylabel="Generation (GWh)",
    xlabel="Investment Period",
    rot=0,
)

df = n.generators_t.p.sum(axis=0).T.div(1e3) df.T.plot.bar( stacked=True, edgecolor="white", width=1, ylabel="Generation (GWh)", xlabel="Investment Period", rot=0, )

Out[12]:

text
<Axes: xlabel='Investment Period', ylabel='Generation (GWh)'>

No description has been provided for this image

diagram 2026-11-02

diagram 2021-07-23