Post · 23 min read· pp. 462–484

Stochastic Optimization

This example demonstrates principles of stochastic optimization for energy system planning under uncertainty and their implementation in PyPSA. See User Guide - Stochastic Optimization. We will consider a stylized capacity expansion model with three scenarios with low, medium, and high gas prices. The network will have a single-bus with a constant load and solar, wind, gas and lignite as extendable generators and the following gas price scenarios:

ScenarioGas PriceProbability
Low40 €/MWh40%
Medium70 €/MWh30%
High100 €/MWh30%

Import Packages

Let's first import the necessary packages.

In [2]:

Copied! diagram

ipynb
import matplotlib.pyplot as plt
import pandas as pd

import pypsa
from pypsa.costs import annuity

import matplotlib.pyplot as plt import pandas as pd import pypsa from pypsa.costs import annuity

Prepare Input Data

Then, we set a few general parameters, load capacity factor time series and techno-economic data such as investment costs and conversion efficiencies.

In [3]:

Copied! diagram

ipynb
# Scenario definitions - Gas price uncertainty
SCENARIOS = ["low", "med", "high"]
GAS_PRICES = {"low": 40, "med": 70, "high": 100}  # EUR/MWh_th
PROB = {"low": 0.4, "med": 0.3, "high": 0.3}  # Scenario probabilities
BASE = "low"  # Base scenario for network construction

# System parameters
FREQ = "3h"  # Time resolution
LOAD_MW = 1  # Constant load (MW)

# Time series data URL
TS_URL = (
    "https://tubcloud.tu-berlin.de/s/pKttFadrbTKSJKF/download/time-series-lecture-2.csv"
)

# Load and process time series data
ts = pd.read_csv(TS_URL, index_col=0, parse_dates=True)
ts = ts.resample(FREQ).asfreq()  # Resample to 3-hour resolution


# Technology data: investment costs, efficiencies, marginal costs
TECH = {
    "solar": {"profile": "solar", "inv": 1e6, "m_cost": 0.01},
    "wind": {"profile": "onwind", "inv": 2e6, "m_cost": 0.02},
    "gas": {"inv": 7e5, "eff": 0.6},
    "lignite": {"inv": 1.3e6, "eff": 0.4, "m_cost": 130},
}

# Financial parameters
FOM, DR, LIFE = 3.0, 0.03, 25  # Fixed O&M (%), discount rate, lifetime (years)

# Calculate annualized capital costs
for cfg in TECH.values():
    cfg["fixed_cost"] = (annuity(DR, LIFE) + FOM / 100) * cfg["inv"]


COLOR_MAP = {
    "solar": "gold",
    "wind": "skyblue",
    "gas": "brown",
    "lignite": "black",
}

Scenario definitions - Gas price uncertainty

SCENARIOS = ["low", "med", "high"] GAS_PRICES = {"low": 40, "med": 70, "high": 100} # EUR/MWh_th PROB = {"low": 0.4, "med": 0.3, "high": 0.3} # Scenario probabilities BASE = "low" # Base scenario for network construction

System parameters

FREQ = "3h" # Time resolution LOAD_MW = 1 # Constant load (MW)

Time series data URL

TS_URL = ( "https://tubcloud.tu-berlin.de/s/pKttFadrbTKSJKF/download/time-series-lecture-2.csv" )

Load and process time series data

ts = pd.read_csv(TS_URL, index_col=0, parse_dates=True) ts = ts.resample(FREQ).asfreq() # Resample to 3-hour resolution

Technology data: investment costs, efficiencies, marginal costs

TECH = { "solar": {"profile": "solar", "inv": 1e6, "m_cost": 0.01}, "wind": {"profile": "onwind", "inv": 2e6, "m_cost": 0.02}, "gas": {"inv": 7e5, "eff": 0.6}, "lignite": {"inv": 1.3e6, "eff": 0.4, "m_cost": 130}, }

Financial parameters

FOM, DR, LIFE = 3.0, 0.03, 25 # Fixed O&M (%), discount rate, lifetime (years)

Calculate annualized capital costs

for cfg in TECH.values(): cfg["fixed_cost"] = (annuity(DR, LIFE) + FOM / 100) * cfg["inv"] COLOR_MAP = { "solar": "gold", "wind": "skyblue", "gas": "brown", "lignite": "black", }

Create PyPSA Network

Next, we build the PyPSA network from the provided input data. We wrap it in a function for easy reuse for different scenarios.

In [4]:

Copied! diagram

ipynb
def build_network(gas_price: float) -> pypsa.Network:
    n = pypsa.Network()
    n.set_snapshots(ts.index)
    n.snapshot_weightings = pd.Series(int(FREQ[:-1]), index=ts.index)  # 3-hour weights

    # Add bus and load
    n.add("Bus", "DE")
    n.add("Load", "DE_load", bus="DE", p_set=LOAD_MW)

    # Add renewable generators (variable renewable energy)
    for tech in ["solar", "wind"]:
        cfg = TECH[tech]
        n.add(
            "Generator",
            tech,
            bus="DE",
            p_nom_extendable=True,
            p_max_pu=ts[cfg["profile"]],  # Renewable availability profile
            capital_cost=cfg["fixed_cost"],
            marginal_cost=cfg["m_cost"],
        )

    # Add conventional generators (dispatchable)
    for tech in ["gas", "lignite"]:
        cfg = TECH[tech]
        # Gas marginal cost depends on gas price and efficiency
        mc = (gas_price / cfg.get("eff")) if tech == "gas" else cfg["m_cost"]
        n.add(
            "Generator",
            tech,
            bus="DE",
            p_nom_extendable=True,
            efficiency=cfg.get("eff"),
            capital_cost=cfg["fixed_cost"],
            marginal_cost=mc,
        )
    return n

def build_network(gas_price: float) -> pypsa.Network: n = pypsa.Network() n.set_snapshots(ts.index) n.snapshot_weightings = pd.Series(int(FREQ[:-1]), index=ts.index) # 3-hour weights

Add bus and load

n.add("Bus", "DE") n.add("Load", "DE_load", bus="DE", p_set=LOAD_MW)

Add renewable generators (variable renewable energy)

for tech in ["solar", "wind"]: cfg = TECH[tech] n.add( "Generator", tech, bus="DE", p_nom_extendable=True, p_max_pu=ts[cfg["profile"]], # Renewable availability profile capital_cost=cfg["fixed_cost"], marginal_cost=cfg["m_cost"], )

Add conventional generators (dispatchable)

for tech in ["gas", "lignite"]: cfg = TECH[tech]

Gas marginal cost depends on gas price and efficiency

mc = (gas_price / cfg.get("eff")) if tech == "gas" else cfg["m_cost"] n.add( "Generator", tech, bus="DE", p_nom_extendable=True, efficiency=cfg.get("eff"), capital_cost=cfg["fixed_cost"], marginal_cost=mc, ) return n

Deterministic Optimization

Initially, let's solve separate deterministic optimization problems for each gas price scenario. This represents the approach where we assume perfect foresight on the uncertain parameter. That means we solve the problem for each scenario independently.

In [5]:

Copied! diagram

ipynb
caps_det = pd.DataFrame(index=SCENARIOS, columns=TECH.keys())
objs_det = pd.Series(index=SCENARIOS)

for sc in SCENARIOS:
    n = build_network(GAS_PRICES[sc])
    n.optimize()
    caps_det.loc[sc] = n.generators.p_nom_opt
    objs_det.loc[sc] = n.objective

caps_det = pd.DataFrame(index=SCENARIOS, columns=TECH.keys()) objs_det = pd.Series(index=SCENARIOS) for sc in SCENARIOS: n = build_network(GAS_PRICES[sc]) n.optimize() caps_det.loc[sc] = n.generators.p_nom_opt objs_det.loc[sc] = n.objective

text
/tmp/ipykernel_8847/3998719704.py:2: 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()
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`
text
/tmp/ipykernel_8847/3673675481.py:6: 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()
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['DE'], dtype='object', name='name')
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/4 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 155.78it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 354.40it/s]
text
INFO:linopy.io: Writing time: 0.05s
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-mwu66zmv.lp
text
Reading time = 0.03 seconds
text
obj: 26284 rows, 11684 columns, 45363 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 11684 primals, 26284 duals
Objective: 6.45e+05
Solver: gurobi
Runtime: 0.05s
Dual bound: 6.45e+05
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.
text
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['DE'], dtype='object', name='name')
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/4 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 158.01it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 349.38it/s]
text
INFO:linopy.io: Writing time: 0.04s
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-37_4cyib.lp
text
Reading time = 0.03 seconds
text
obj: 26284 rows, 11684 columns, 45363 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 11684 primals, 26284 duals
Objective: 9.96e+05
Solver: gurobi
Runtime: 0.15s
Dual bound: 9.96e+05
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.
text
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['DE'], dtype='object', name='name')
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/4 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 164.42it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 323.45it/s]
text
INFO:linopy.io: Writing time: 0.04s
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-uy721t4z.lp
text
Reading time = 0.03 seconds
text
obj: 26284 rows, 11684 columns, 45363 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 11684 primals, 26284 duals
Objective: 1.11e+06
Solver: gurobi
Runtime: 0.18s
Dual bound: 1.11e+06
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.

In [6]:

Copied! diagram

ipynb
# Visualize deterministic results
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))

colors = [COLOR_MAP.get(c, "gray") for c in caps_det.columns]
caps_det.plot(kind="bar", stacked=True, ax=ax1, color=colors)
ax1.set_title("Deterministic Capacity Mix by Scenario")
ax1.set_ylabel("Capacity (MW)")
ax1.legend(loc="upper left")

(objs_det / 1e6).plot(kind="bar", ax=ax2, color="steelblue")
ax2.set_title("Deterministic Total Costs by Scenario")
ax2.set_ylabel("Total Cost (M€/year)")

Visualize deterministic results

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5)) colors = [COLOR_MAP.get(c, "gray") for c in caps_det.columns] caps_det.plot(kind="bar", stacked=True, ax=ax1, color=colors) ax1.set_title("Deterministic Capacity Mix by Scenario") ax1.set_ylabel("Capacity (MW)") ax1.legend(loc="upper left") (objs_det / 1e6).plot(kind="bar", ax=ax2, color="steelblue") ax2.set_title("Deterministic Total Costs by Scenario") ax2.set_ylabel("Total Cost (M€/year)")

Out[6]:

text
Text(0, 0.5, 'Total Cost (M€/year)')

No description has been provided for this image

We observe that higher gas prices lead to more renewable capacity expansion and less gas capacity. As gas prices increase, total system costs rise.

Stochastic Optimization

The key to stochastic optimization in PyPSA is the n.set_scenarios() method. This method transforms a regular PyPSA network into a stochastic network by adding scenario dimensions to all component data which allows specifying scenario-specific parameters. Once scenarios are set, PyPSA treats investment decisions as first-stage variables that must be the same across all scenarios, while dispatch decisions become second-stage variables that can differ by scenario.

We start by building a deterministic network for our (arbitrarily selected) base scenario. Subsequently, we add our scenarios to the network.

In [7]:

Copied! diagram

ipynb
n_stoch = build_network(GAS_PRICES[BASE])
n_stoch.set_scenarios(PROB)

n_stoch = build_network(GAS_PRICES[BASE]) n_stoch.set_scenarios(PROB)

text
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`

After that, we can set the scenario-specific parameters, i.e. the varying gas prices by scenario.

In [8]:

Copied! diagram

ipynb
for sc in SCENARIOS:
    n_stoch.generators.loc[(sc, "gas"), "marginal_cost"] = (
        GAS_PRICES[sc] / n_stoch.generators.loc[(sc, "gas"), "efficiency"]
    )

for sc in SCENARIOS: n_stoch.generators.loc[(sc, "gas"), "marginal_cost"] = ( GAS_PRICES[sc] / n_stoch.generators.loc[(sc, "gas"), "efficiency"] )

Now, we can solve the stochastic optimisation model:

In [9]:

Copied! diagram

ipynb
n_stoch.optimize()

print(f"Total expected cost: {n_stoch.objective / 1e6:.3f} M€/year")

caps_api = n_stoch.generators.p_nom_opt.xs(BASE, level="scenario")
obj_api = n_stoch.objective

n_stoch.optimize() print(f"Total expected cost: {n_stoch.objective / 1e6:.3f} M€/year") caps_api = n_stoch.generators.p_nom_opt.xs(BASE, level="scenario") obj_api = n_stoch.objective

text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
MultiIndex([( 'low', 'DE'),
            ( 'med', 'DE'),
            ('high', 'DE')],
           names=['scenario', 'name'])
text
WARNING:linopy.expressions:Constant RHS contains dimensions {'scenario'} not present in the expression, which might lead to inefficiencies. Consider collapsing the dimensions by taking min/max.
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/4 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 99.80it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 232.22it/s]
text
INFO:linopy.io: Writing time: 0.06s
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-dt6jtu6t.lp
text
Reading time = 0.10 seconds
text
obj: 78852 rows, 35044 columns, 136089 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 35044 primals, 78852 duals
Objective: 9.69e+05
Solver: gurobi
Runtime: 0.60s
Dual bound: 9.69e+05
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.
text
Total expected cost: 0.969 M€/year

In [10]:

Copied! diagram

ipynb
caps_comparison = caps_det.copy()
caps_comparison.loc["Stochastic"] = caps_api

objs_comparison = objs_det.copy()
objs_comparison.loc["Stochastic"] = obj_api

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))

colors = [COLOR_MAP.get(c, "gray") for c in caps_comparison.columns]
caps_comparison.plot(kind="bar", stacked=True, ax=ax1, color=colors)
ax1.set_title("Capacity Mix: Deterministic vs. Stochastic")
ax1.set_ylabel("Capacity (MW)")
ax1.legend(loc="upper left")

(objs_comparison / 1e6).plot(kind="bar", ax=ax2, color="steelblue")
ax2.set_title("Total Cost: Deterministic vs. Stochastic")
ax2.set_ylabel("Total Cost (M€/year)")

caps_comparison = caps_det.copy() caps_comparison.loc["Stochastic"] = caps_api objs_comparison = objs_det.copy() objs_comparison.loc["Stochastic"] = obj_api fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5)) colors = [COLOR_MAP.get(c, "gray") for c in caps_comparison.columns] caps_comparison.plot(kind="bar", stacked=True, ax=ax1, color=colors) ax1.set_title("Capacity Mix: Deterministic vs. Stochastic") ax1.set_ylabel("Capacity (MW)") ax1.legend(loc="upper left") (objs_comparison / 1e6).plot(kind="bar", ax=ax2, color="steelblue") ax2.set_title("Total Cost: Deterministic vs. Stochastic") ax2.set_ylabel("Total Cost (M€/year)")

Out[10]:

text
Text(0, 0.5, 'Total Cost (M€/year)')

No description has been provided for this image

Value of Information Metrics

We can also now calculate the Value of Information (VoI) metrics, which include the Expected Value of Perfect Information (EVPI) and the Value of Stochastic Solution (VSS). These metrics help us understand the benefits of incorporating uncertainty into our optimization model.

In [11]:

Copied! diagram

ipynb
# Wait-and-See (perfect information) expected cost
ws_cost = sum(objs_det[sc] * PROB[sc] for sc in SCENARIOS)
print(f"Wait-and-See (WS) cost: {ws_cost / 1e6:.3f} M€/year")

Wait-and-See (perfect information) expected cost

ws_cost = sum(objs_det[sc] * PROB[sc] for sc in SCENARIOS) print(f"Wait-and-See (WS) cost: {ws_cost / 1e6:.3f} M€/year")

text
Wait-and-See (WS) cost: 0.890 M€/year

In [12]:

Copied! diagram

ipynb
# Expected Value of Perfect Information
evpi = obj_api - ws_cost
print(f"EVPI (SP - WS): {evpi / 1e6:.3f} M€/year")

Expected Value of Perfect Information

evpi = obj_api - ws_cost print(f"EVPI (SP - WS): {evpi / 1e6:.3f} M€/year")

text
EVPI (SP - WS): 0.079 M€/year

In [13]:

Copied! diagram

ipynb
# Expected gas price
expected_gas_price = sum(GAS_PRICES[sc] * PROB[sc] for sc in SCENARIOS)
print(f"Expected gas price: {expected_gas_price:.1f} EUR/MWh_th")

Expected gas price

expected_gas_price = sum(GAS_PRICES[sc] * PROB[sc] for sc in SCENARIOS) print(f"Expected gas price: {expected_gas_price:.1f} EUR/MWh_th")

text
Expected gas price: 67.0 EUR/MWh_th

In [14]:

Copied! diagram

ipynb
# Report stochastic programming (SP) cost
print(f"Stochastic Prog (SP) cost: {obj_api / 1e6:.3f} M€/year")

Report stochastic programming (SP) cost

print(f"Stochastic Prog (SP) cost: {obj_api / 1e6:.3f} M€/year")

text
Stochastic Prog (SP) cost: 0.969 M€/year

In [15]:

Copied! diagram

ipynb
# Solve deterministic problem with expected gas price (EEV solution)
n_eev = build_network(expected_gas_price)
n_eev.optimize()
eev_capacities = n_eev.generators.p_nom_opt

# Evaluate EEV capacities under each scenario
eev_costs = []
for sc in SCENARIOS:
    n_eval = build_network(GAS_PRICES[sc])
    for tech in TECH.keys():
        n_eval.generators.loc[tech, "p_nom_max"] = eev_capacities[tech]
        n_eval.generators.loc[tech, "p_nom_min"] = eev_capacities[tech]
    n_eval.optimize()
    eev_costs.append(n_eval.objective)

eev_expected_cost = sum(eev_costs[i] * PROB[sc] for i, sc in enumerate(SCENARIOS))
print(f"Expected Value (EEV) cost: {eev_expected_cost / 1e6:.3f} M€/year")

Solve deterministic problem with expected gas price (EEV solution)

n_eev = build_network(expected_gas_price) n_eev.optimize() eev_capacities = n_eev.generators.p_nom_opt

Evaluate EEV capacities under each scenario

eev_costs = [] for sc in SCENARIOS: n_eval = build_network(GAS_PRICES[sc]) for tech in TECH.keys(): n_eval.generators.loc[tech, "p_nom_max"] = eev_capacities[tech] n_eval.generators.loc[tech, "p_nom_min"] = eev_capacities[tech] n_eval.optimize() eev_costs.append(n_eval.objective) eev_expected_cost = sum(eev_costs[i] * PROB[sc] for i, sc in enumerate(SCENARIOS)) print(f"Expected Value (EEV) cost: {eev_expected_cost / 1e6:.3f} M€/year")

text
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['DE'], dtype='object', name='name')
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/4 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 156.65it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 321.45it/s]
text
INFO:linopy.io: Writing time: 0.04s
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-qatnt43c.lp
text
Reading time = 0.03 seconds
text
obj: 26284 rows, 11684 columns, 45363 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 11684 primals, 26284 duals
Objective: 9.71e+05
Solver: gurobi
Runtime: 0.17s
Dual bound: 9.71e+05
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.
text
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['DE'], dtype='object', name='name')
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/5 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 5/5 [00:00<00:00, 169.26it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 359.72it/s]
text
INFO:linopy.io: Writing time: 0.04s
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-tk1uwjub.lp
text
Reading time = 0.03 seconds
text
obj: 26288 rows, 11684 columns, 45367 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 11684 primals, 26288 duals
Objective: 7.37e+05
Solver: gurobi
Runtime: 0.02s
Dual bound: 7.37e+05
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.
text
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['DE'], dtype='object', name='name')
text
Warning: environment still referenced so free is deferred (Continue to use WLS)
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/5 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 5/5 [00:00<00:00, 188.01it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 346.64it/s]
text
INFO:linopy.io: Writing time: 0.04s
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-t1lnjcdu.lp
text
Reading time = 0.03 seconds
text
obj: 26288 rows, 11684 columns, 45367 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 11684 primals, 26288 duals
Objective: 9.97e+05
Solver: gurobi
Runtime: 0.01s
Dual bound: 9.97e+05
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.
text
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['DE'], dtype='object', name='name')
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/5 [00:00<?, ?it/s]
text
Writing constraints.: 100%|██████████| 5/5 [00:00<00:00, 185.13it/s]
text
text
Writing continuous variables.:   0%|          | 0/2 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 333.08it/s]
text
INFO:linopy.io: Writing time: 0.04s
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-wtbhpzmc.lp
text
Reading time = 0.03 seconds
text
obj: 26288 rows, 11684 columns, 45367 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 11684 primals, 26288 duals
Objective: 1.26e+06
Solver: gurobi
Runtime: 0.02s
Dual bound: 1.26e+06
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.
text
Expected Value (EEV) cost: 0.971 M€/year

In [16]:

Copied! diagram

ipynb
# Value of Stochastic Solution
vss = eev_expected_cost - obj_api
print(f"VSS (EEV - SP): {vss / 1e6:.3f} M€/year")

Value of Stochastic Solution

vss = eev_expected_cost - obj_api print(f"VSS (EEV - SP): {vss / 1e6:.3f} M€/year")

text
VSS (EEV - SP): 0.002 M€/year

In [17]:

Copied! diagram

ipynb
print("\nTheoretical Ordering Check:")
print(f"  WS ≤ SP: {ws_cost <= obj_api} ({ws_cost:.0f} ≤ {obj_api:.0f})")
print(
    f"  SP ≤ EEV: {obj_api <= eev_expected_cost} ({obj_api:.0f} ≤ {eev_expected_cost:.0f})"
)
print(f"  EVPI ≥ 0: {evpi >= 0} ({evpi:.0f} ≥ 0)")
print(f"  VSS ≥ 0: {vss >= 0} ({vss:.0f} ≥ 0)")

print("\nTheoretical Ordering Check:") print(f" WS ≤ SP: {ws_cost <= obj_api} ({ws_cost:.0f} ≤ {obj_api:.0f})") print( f" SP ≤ EEV: {obj_api <= eev_expected_cost} ({obj_api:.0f} ≤ {eev_expected_cost:.0f})" ) print(f" EVPI ≥ 0: {evpi >= 0} ({evpi:.0f} ≥ 0)") print(f" VSS ≥ 0: {vss >= 0} ({vss:.0f} ≥ 0)")

text
Theoretical Ordering Check:
  WS ≤ SP: True (889596 ≤ 968918)
  SP ≤ EEV: True (968918 ≤ 970853)
  EVPI ≥ 0: True (79322 ≥ 0)
  VSS ≥ 0: True (1935 ≥ 0)

In [18]:

Copied! diagram

ipynb
costs_voi = pd.Series(
    {
        "Wait-and-See\n(Perfect Info)": ws_cost,
        "Stochastic\nProgramming": obj_api,
        "Expected Value\n(Ignore Uncertainty)": eev_expected_cost,
    }
)


fig, ax1 = plt.subplots(figsize=(7, 5))

# Cost comparison
(costs_voi / 1e6).plot(kind="bar", ax=ax1, color=["green", "blue", "red"], alpha=0.7)
ax1.set_title("Value of Information: Cost Comparison", fontsize=14, fontweight="bold")
ax1.set_ylabel("Total Cost (M€/year)")
ax1.tick_params(axis="x", rotation=45)
ax1.grid(True, alpha=0.3)

# Add EVPI and VSS arrows
ax1.annotate(
    "",
    xy=(0, ws_cost / 1e6),
    xytext=(1, obj_api / 1e6),
    arrowprops={"arrowstyle": "<->", "color": "purple", "lw": 2},
)
ax1.text(
    0.5,
    (ws_cost + obj_api) / (2 * 1e6),
    "EVPI",
    color="purple",
    fontweight="bold",
    fontsize=10,
    ha="center",
)

ax1.annotate(
    "",
    xy=(1, obj_api / 1e6),
    xytext=(2, eev_expected_cost / 1e6),
    arrowprops={"arrowstyle": "<->", "color": "orange", "lw": 2},
)
ax1.text(
    1.5,
    (eev_expected_cost + obj_api) / (2 * 1e6),
    "VSS",
    color="orange",
    fontweight="bold",
    fontsize=10,
    ha="center",
)

costs_voi = pd.Series( { "Wait-and-See\n(Perfect Info)": ws_cost, "Stochastic\nProgramming": obj_api, "Expected Value\n(Ignore Uncertainty)": eev_expected_cost, } ) fig, ax1 = plt.subplots(figsize=(7, 5))

Cost comparison

(costs_voi / 1e6).plot(kind="bar", ax=ax1, color=["green", "blue", "red"], alpha=0.7) ax1.set_title("Value of Information: Cost Comparison", fontsize=14, fontweight="bold") ax1.set_ylabel("Total Cost (M€/year)") ax1.tick_params(axis="x", rotation=45) ax1.grid(True, alpha=0.3)

Add EVPI and VSS arrows

ax1.annotate( "", xy=(0, ws_cost / 1e6), xytext=(1, obj_api / 1e6), arrowprops={"arrowstyle": "<->", "color": "purple", "lw": 2}, ) ax1.text( 0.5, (ws_cost + obj_api) / (2 * 1e6), "EVPI", color="purple", fontweight="bold", fontsize=10, ha="center", ) ax1.annotate( "", xy=(1, obj_api / 1e6), xytext=(2, eev_expected_cost / 1e6), arrowprops={"arrowstyle": "<->", "color": "orange", "lw": 2}, ) ax1.text( 1.5, (eev_expected_cost + obj_api) / (2 * 1e6), "VSS", color="orange", fontweight="bold", fontsize=10, ha="center", )

Out[18]:

text
Text(1.5, 0.9698854088266327, 'VSS')

No description has been provided for this image

References

[1] Birge, J. R., & Louveaux, F. (2011). Introduction to Stochastic Programming.

[2] Birge, J. R. (1982). The value of the stochastic solution in stochastic linear programs with fixed recourse. Mathematical Programming, 24(1), 314-325.

diagram 2026-08-05

diagram 2025-06-24