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:
| Scenario | Gas Price | Probability |
|---|---|---|
| Low | 40 €/MWh | 40% |
| Medium | 70 €/MWh | 30% |
| High | 100 €/MWh | 30% |
Import Packages
Let's first import the necessary packages.
In [2]:
Copied!
import matplotlib.pyplot as plt
import pandas as pd
import pypsa
from pypsa.costs import annuityimport 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!
# 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!
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 ndef 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!
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.objectivecaps_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
/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`/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')INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/4 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 155.78it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 354.40it/s]INFO:linopy.io: Writing time: 0.05sSet 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-mwu66zmv.lpReading time = 0.03 secondsobj: 26284 rows, 11684 columns, 45363 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`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')INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/4 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 158.01it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 349.38it/s]INFO:linopy.io: Writing time: 0.04sSet 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-37_4cyib.lpReading time = 0.03 secondsobj: 26284 rows, 11684 columns, 45363 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`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')INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/4 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 164.42it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 323.45it/s]INFO:linopy.io: Writing time: 0.04sSet 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-uy721t4z.lpReading time = 0.03 secondsobj: 26284 rows, 11684 columns, 45363 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO: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!
# 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(0, 0.5, 'Total Cost (M€/year)')
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!
n_stoch = build_network(GAS_PRICES[BASE])
n_stoch.set_scenarios(PROB)n_stoch = build_network(GAS_PRICES[BASE]) n_stoch.set_scenarios(PROB)
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!
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!
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.objectiven_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
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'])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.INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/4 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 99.80it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 232.22it/s]INFO:linopy.io: Writing time: 0.06sSet 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-dt6jtu6t.lpReading time = 0.10 secondsobj: 78852 rows, 35044 columns, 136089 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.Total expected cost: 0.969 M€/yearIn [10]:
Copied!
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(0, 0.5, 'Total Cost (M€/year)')
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!
# 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")
Wait-and-See (WS) cost: 0.890 M€/yearIn [12]:
Copied!
# 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")
EVPI (SP - WS): 0.079 M€/yearIn [13]:
Copied!
# 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")
Expected gas price: 67.0 EUR/MWh_thIn [14]:
Copied!
# 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")
Stochastic Prog (SP) cost: 0.969 M€/yearIn [15]:
Copied!
# 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")
INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`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')INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/4 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 4/4 [00:00<00:00, 156.65it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 321.45it/s]INFO:linopy.io: Writing time: 0.04sSet 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-qatnt43c.lpReading time = 0.03 secondsobj: 26284 rows, 11684 columns, 45363 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`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')INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/5 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 5/5 [00:00<00:00, 169.26it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 359.72it/s]INFO:linopy.io: Writing time: 0.04sSet 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-tk1uwjub.lpReading time = 0.03 secondsobj: 26288 rows, 11684 columns, 45367 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`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')Warning: environment still referenced so free is deferred (Continue to use WLS)INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/5 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 5/5 [00:00<00:00, 188.01it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 346.64it/s]INFO:linopy.io: Writing time: 0.04sSet 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-t1lnjcdu.lpReading time = 0.03 secondsobj: 26288 rows, 11684 columns, 45367 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.INFO:pypsa.network.index:Applying weightings to all columns of `snapshot_weightings`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')INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/5 [00:00<?, ?it/s]Writing constraints.: 100%|██████████| 5/5 [00:00<00:00, 185.13it/s]Writing continuous variables.: 0%| | 0/2 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 2/2 [00:00<00:00, 333.08it/s]INFO:linopy.io: Writing time: 0.04sSet 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-wtbhpzmc.lpReading time = 0.03 secondsobj: 26288 rows, 11684 columns, 45367 nonzerosSet parameter LogToConsole to value 0INFO: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: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper were not assigned to the network.Expected Value (EEV) cost: 0.971 M€/yearIn [16]:
Copied!
# 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")
VSS (EEV - SP): 0.002 M€/yearIn [17]:
Copied!
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)")
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!
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(1.5, 0.9698854088266327, 'VSS')
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.
2026-08-05
2025-06-24