Post · 20 min read· pp. 257–270

Defining Asset Operational Limits over User-Defined Time Periods

This example demonstrates how to impose periodic minimum and maximum energy output constraints on a Combined Cycle Gas Turbine (CCGT) generator using PyPSA's custom constraint mechanism. This example focusses on monthly limits but the approach would work for limits set over any user-defined periods, including non-uniform ones (e.g, daily, weekly, every reporting period, etc.).

It uses a 3-hourly resolved variant of the single-node network developed in the single-node capacity expansion example, replacing the load-shedding generator with a combined-cycle gas turbine (CCGT).

In practice, monthly CCGT constraints arise from:

  • contractual minimum-offtake agreements (lower bound),
  • fuel-supply or CO₂-permit limits (upper bound).

Our operational limits will be added via the extra_functionality callback in n.optimize().

In [2]:

Copied! diagram

ipynb
import calendar

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import xarray as xr

import calendar import pandas as pd import plotly.express as px import plotly.graph_objects as go import xarray as xr

First, we will create the definition for our new CCGT generator, and use it in our network in place of load shedding.

We attach the monthly limits to the network as custom time-dependent attributes (p_min_periodic, p_max_periodic), with values only on the first snapshot of each month (all other snapshots are NaN). PyPSA stores any extra keyword arguments passed to n.add() as component attributes, so these custom attributes persist when exporting the network to file / importing the network from file.

If we wanted to apply a different period for our limit, we would update the attribute to have the limit data applied at the first snapshot of each period, e.g.:

text
daily_limit = pd.Series([10, 15, ...], index=pd.to_datetime(["2019-01-01", "2019-01-02", ...]))
# We have to expand the data out to all snapshots to be able to store it as a PyPSA network attribute.
# All snapshots that aren't the first of the day will be filled with NaN.
daily_limit_all_snapshots = daily_limit.reindex(n.snapshots)
n.add(
    "Generator",
    "CCGT",
    ...
    p_max_periodic=daily_limit_all_snapshots,
)

In [3]:

Copied! diagram

ipynb
def get_p_monthly(network: pypsa.Network, output_mw: float) -> pd.Series:
    """Define a monthly output limit for dispatch, set for the first snapshot of each month."""
    sns = network.snapshots
    weights = network.snapshot_weightings["generators"]
    return pd.Series(output_mw * weights, index=sns).resample("MS").sum().reindex(sns)


n = pypsa.examples.model_energy()

ccgt_p_nom = 2000  # MW – fixed installed capacity
min_fraction = 0.15  # lower bound: 15 % of maximum possible monthly output
max_fraction = 0.40  # upper bound: 40 % of maximum possible monthly output
p_min_monthly = get_p_monthly(n, min_fraction * ccgt_p_nom)
p_max_monthly = get_p_monthly(n, max_fraction * ccgt_p_nom)

# Replace load shedding with a fixed-capacity CCGT
n.remove("Generator", "load shedding")

n.add(
    "Generator",
    "CCGT",
    bus="electricity",
    carrier="CCGT",
    p_nom=ccgt_p_nom,
    marginal_cost=60,  # €/MWh
    p_nom_extendable=False,
    p_min_periodic=p_min_monthly,
    p_max_periodic=p_max_monthly,
)
n.add("Carrier", "CCGT")

monthly_bounds = (
    pd.concat([p_min_monthly, p_max_monthly], axis=1, keys=["p_min", "p_max"])
    .groupby(n.snapshots.month.rename("month"))
    .sum()
)
display(monthly_bounds)

def get_p_monthly(network: pypsa.Network, output_mw: float) -> pd.Series: """Define a monthly output limit for dispatch, set for the first snapshot of each month.""" sns = network.snapshots weights = network.snapshot_weightings["generators"] return pd.Series(output_mw * weights, index=sns).resample("MS").sum().reindex(sns) n = pypsa.examples.model_energy() ccgt_p_nom = 2000 # MW – fixed installed capacity min_fraction = 0.15 # lower bound: 15 % of maximum possible monthly output max_fraction = 0.40 # upper bound: 40 % of maximum possible monthly output p_min_monthly = get_p_monthly(n, min_fraction * ccgt_p_nom) p_max_monthly = get_p_monthly(n, max_fraction * ccgt_p_nom)

Replace load shedding with a fixed-capacity CCGT

n.remove("Generator", "load shedding") n.add( "Generator", "CCGT", bus="electricity", carrier="CCGT", p_nom=ccgt_p_nom, marginal_cost=60, # €/MWh p_nom_extendable=False, p_min_periodic=p_min_monthly, p_max_periodic=p_max_monthly, ) n.add("Carrier", "CCGT") monthly_bounds = ( pd.concat([p_min_monthly, p_max_monthly], axis=1, keys=["p_min", "p_max"]) .groupby(n.snapshots.month.rename("month")) .sum() ) display(monthly_bounds)

text
/tmp/ipykernel_8195/1091314057.py:8: 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.examples.model_energy()
text
INFO:pypsa.network.io:Imported network 'Model-Energy' has buses, carriers, generators, links, loads, storage_units, stores
p_minp_max
month
1223200.0595200.0
2201600.0537600.0
3223200.0595200.0
4216000.0576000.0
5223200.0595200.0
6216000.0576000.0
7223200.0595200.0
8223200.0595200.0
9216000.0576000.0
10223200.0595200.0
11216000.0576000.0
12223200.0595200.0

Apply Custom Constraints

The extra_functionality callback receives the network n and the active snapshot index sns. Inside the callback we:

  1. Retrieve the CCGT active-power variable from the Linopy model (n.model).

  2. Sum the variable over all (weighted) snapshots in a period (here, months):

    Em=∑t∈month mwt⋅pCCGT,tE_m = \sum_{t \in \text{month } m} w_t \cdot p_{\text{CCGT},t}

    where wtw_t is the snapshot weighting (1 h for hourly data).

  3. Add two constraints per month:

    Em≥Emmin⁡,Em≤Emmax⁡E_m \geq E_m^{\min}, \quad E_m \leq E_m^{\max}

In [4]:

Copied! diagram

ipynb
def get_grouper(limit_attr: xr.DataArray) -> xr.DataArray:
    """Return a grouper for snapshots in the same period based on the NaN values between each non-NaN value in the limit attribute."""
    return limit_attr.notnull().cumsum("snapshot").rename("limit_period")


def period_ccgt_output_constraints(n: pypsa.Network, sns: pd.Index) -> None:
    """Add lower and upper energy-output constraints for the CCGT dispatch per period.

    Parameters
    ----------
    n : pypsa.Network
    sns : pd.Index
        Active snapshots passed by PyPSA during optimisation.
    """
    m = n.model
    selector = {"name": "CCGT", "snapshot": sns}
    p_ccgt = m.variables["Generator-p"].sel(**selector)
    weights = n.snapshot_weightings["generators"].loc[sns]
    for limit, sign in {"max": "<=", "min": ">="}.items():
        limit_attr = n.components["Generator"].da[f"p_{limit}_periodic"].sel(**selector)
        grouper = get_grouper(limit_attr)
        p_period = (p_ccgt * weights).groupby(grouper).sum()
        p_lim_period = limit_attr.groupby(grouper).sum()
        m.add_constraints(
            lhs=p_period, sign=sign, rhs=p_lim_period, name=f"CCGT-period-{limit}"
        )

def get_grouper(limit_attr: xr.DataArray) -> xr.DataArray: """Return a grouper for snapshots in the same period based on the NaN values between each non-NaN value in the limit attribute.""" return limit_attr.notnull().cumsum("snapshot").rename("limit_period") def period_ccgt_output_constraints(n: pypsa.Network, sns: pd.Index) -> None: """Add lower and upper energy-output constraints for the CCGT dispatch per period. Parameters

n : pypsa.Network sns : pd.Index Active snapshots passed by PyPSA during optimisation. """ m = n.model selector = {"name": "CCGT", "snapshot": sns} p_ccgt = m.variables["Generator-p"].sel(**selector) weights = n.snapshot_weightings["generators"].loc[sns] for limit, sign in {"max": "<=", "min": ">="}.items(): limit_attr = n.components["Generator"].da[f"p_{limit}_periodic"].sel(**selector) grouper = get_grouper(limit_attr) p_period = (p_ccgt * weights).groupby(grouper).sum() p_lim_period = limit_attr.groupby(grouper).sum() m.add_constraints( lhs=p_period, sign=sign, rhs=p_lim_period, name=f"CCGT-period-{limit}" )

Run Optimization

We solve the network twice:

  1. Baseline – no custom constraints, purely cost-optimal dispatch.
  2. Constrained – the extra_functionality callback enforces monthly CCGT bounds.

Both runs use the default HiGHS solver.

In [5]:

Copied! diagram

ipynb
# --- Baseline: no custom constraints ---
n_base = n.copy()
n_base.optimize(include_objective_constant=False)
print("Baseline solved")

--- Baseline: no custom constraints ---

n_base = n.copy() n_base.optimize(include_objective_constant=False) print("Baseline solved")

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/25 [00:00<?, ?it/s]
text
Writing constraints.:  92%|█████████▏| 23/25 [00:00<00:00, 226.62it/s]
text
Writing constraints.: 100%|██████████| 25/25 [00:00<00:00, 221.64it/s]
text
text
Writing continuous variables.:   0%|          | 0/12 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 12/12 [00:00<00:00, 418.10it/s]
text
INFO:linopy.io: Writing time: 0.27s
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-ar5gmrs4.lp
text
Reading time = 0.08 seconds
text
obj: 70086 rows, 32126 columns, 129984 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: 6.83e+09
Solver: gurobi
Runtime: 0.95s
Dual bound: 6.83e+09
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, StorageUnit-ext-p_dispatch-lower, StorageUnit-ext-p_dispatch-upper, StorageUnit-ext-p_store-lower, StorageUnit-ext-p_store-upper, StorageUnit-ext-state_of_charge-lower, StorageUnit-ext-state_of_charge-upper, StorageUnit-energy_balance, Store-energy_balance were not assigned to the network.
text
Baseline solved

In [6]:

Copied! diagram

ipynb
# --- Constrained: with monthly CCGT output limits ---
n_constrained = n.copy()
n_constrained.optimize(
    extra_functionality=period_ccgt_output_constraints,
    include_objective_constant=False,
)
print("Constrained solve completed")

--- Constrained: with monthly CCGT output limits ---

n_constrained = n.copy() n_constrained.optimize( extra_functionality=period_ccgt_output_constraints, include_objective_constant=False, ) print("Constrained solve completed")

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/27 [00:00<?, ?it/s]
text
Writing constraints.:  85%|████████▌ | 23/27 [00:00<00:00, 226.37it/s]
text
Writing constraints.: 100%|██████████| 27/27 [00:00<00:00, 221.87it/s]
text
text
Writing continuous variables.:   0%|          | 0/12 [00:00<?, ?it/s]
text
Writing continuous variables.: 100%|██████████| 12/12 [00:00<00:00, 420.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-bbv5pue4.lp
text
Reading time = 0.08 seconds
text
obj: 70110 rows, 32126 columns, 135824 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 32126 primals, 75950 duals
Objective: 6.94e+09
Solver: gurobi
Runtime: 0.87s
Dual bound: 6.94e+09
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, StorageUnit-ext-p_dispatch-lower, StorageUnit-ext-p_dispatch-upper, StorageUnit-ext-p_store-lower, StorageUnit-ext-p_store-upper, StorageUnit-ext-state_of_charge-lower, StorageUnit-ext-state_of_charge-upper, StorageUnit-energy_balance, Store-energy_balance, CCGT-period-max, CCGT-period-min were not assigned to the network.
text
Constrained solve completed

We can view the constraints that has been built by querying linopy directy:

In [7]:

Copied! diagram

ipynb
display(n_constrained.model.constraints["CCGT-period-min"])
display(n_constrained.model.constraints["CCGT-period-max"])

display(n_constrained.model.constraints["CCGT-period-min"]) display(n_constrained.model.constraints["CCGT-period-max"])

text
Constraint `CCGT-period-min` [limit_period: 12]:
------------------------------------------------
[1]: +3 Generator-p[2019-01-01 00:00:00, CCGT] + 3 Generator-p[2019-01-01 03:00:00, CCGT] + 3 Generator-p[2019-01-01 06:00:00, CCGT] ... +3 Generator-p[2019-01-31 15:00:00, CCGT] + 3 Generator-p[2019-01-31 18:00:00, CCGT] + 3 Generator-p[2019-01-31 21:00:00, CCGT]  ≥ 223200.0
[2]: +3 Generator-p[2019-02-01 00:00:00, CCGT] + 3 Generator-p[2019-02-01 03:00:00, CCGT] + 3 Generator-p[2019-02-01 06:00:00, CCGT] ... +3 Generator-p[2019-02-28 15:00:00, CCGT] + 3 Generator-p[2019-02-28 18:00:00, CCGT] + 3 Generator-p[2019-02-28 21:00:00, CCGT]  ≥ 201600.0
[3]: +3 Generator-p[2019-03-01 00:00:00, CCGT] + 3 Generator-p[2019-03-01 03:00:00, CCGT] + 3 Generator-p[2019-03-01 06:00:00, CCGT] ... +3 Generator-p[2019-03-31 15:00:00, CCGT] + 3 Generator-p[2019-03-31 18:00:00, CCGT] + 3 Generator-p[2019-03-31 21:00:00, CCGT]  ≥ 223200.0
[4]: +3 Generator-p[2019-04-01 00:00:00, CCGT] + 3 Generator-p[2019-04-01 03:00:00, CCGT] + 3 Generator-p[2019-04-01 06:00:00, CCGT] ... +3 Generator-p[2019-04-30 15:00:00, CCGT] + 3 Generator-p[2019-04-30 18:00:00, CCGT] + 3 Generator-p[2019-04-30 21:00:00, CCGT]  ≥ 216000.0
[5]: +3 Generator-p[2019-05-01 00:00:00, CCGT] + 3 Generator-p[2019-05-01 03:00:00, CCGT] + 3 Generator-p[2019-05-01 06:00:00, CCGT] ... +3 Generator-p[2019-05-31 15:00:00, CCGT] + 3 Generator-p[2019-05-31 18:00:00, CCGT] + 3 Generator-p[2019-05-31 21:00:00, CCGT]  ≥ 223200.0
[6]: +3 Generator-p[2019-06-01 00:00:00, CCGT] + 3 Generator-p[2019-06-01 03:00:00, CCGT] + 3 Generator-p[2019-06-01 06:00:00, CCGT] ... +3 Generator-p[2019-06-30 15:00:00, CCGT] + 3 Generator-p[2019-06-30 18:00:00, CCGT] + 3 Generator-p[2019-06-30 21:00:00, CCGT]  ≥ 216000.0
[7]: +3 Generator-p[2019-07-01 00:00:00, CCGT] + 3 Generator-p[2019-07-01 03:00:00, CCGT] + 3 Generator-p[2019-07-01 06:00:00, CCGT] ... +3 Generator-p[2019-07-31 15:00:00, CCGT] + 3 Generator-p[2019-07-31 18:00:00, CCGT] + 3 Generator-p[2019-07-31 21:00:00, CCGT]  ≥ 223200.0
[8]: +3 Generator-p[2019-08-01 00:00:00, CCGT] + 3 Generator-p[2019-08-01 03:00:00, CCGT] + 3 Generator-p[2019-08-01 06:00:00, CCGT] ... +3 Generator-p[2019-08-31 15:00:00, CCGT] + 3 Generator-p[2019-08-31 18:00:00, CCGT] + 3 Generator-p[2019-08-31 21:00:00, CCGT]  ≥ 223200.0
[9]: +3 Generator-p[2019-09-01 00:00:00, CCGT] + 3 Generator-p[2019-09-01 03:00:00, CCGT] + 3 Generator-p[2019-09-01 06:00:00, CCGT] ... +3 Generator-p[2019-09-30 15:00:00, CCGT] + 3 Generator-p[2019-09-30 18:00:00, CCGT] + 3 Generator-p[2019-09-30 21:00:00, CCGT]  ≥ 216000.0
[10]: +3 Generator-p[2019-10-01 00:00:00, CCGT] + 3 Generator-p[2019-10-01 03:00:00, CCGT] + 3 Generator-p[2019-10-01 06:00:00, CCGT] ... +3 Generator-p[2019-10-31 15:00:00, CCGT] + 3 Generator-p[2019-10-31 18:00:00, CCGT] + 3 Generator-p[2019-10-31 21:00:00, CCGT] ≥ 223200.0
[11]: +3 Generator-p[2019-11-01 00:00:00, CCGT] + 3 Generator-p[2019-11-01 03:00:00, CCGT] + 3 Generator-p[2019-11-01 06:00:00, CCGT] ... +3 Generator-p[2019-11-30 15:00:00, CCGT] + 3 Generator-p[2019-11-30 18:00:00, CCGT] + 3 Generator-p[2019-11-30 21:00:00, CCGT] ≥ 216000.0
[12]: +3 Generator-p[2019-12-01 00:00:00, CCGT] + 3 Generator-p[2019-12-01 03:00:00, CCGT] + 3 Generator-p[2019-12-01 06:00:00, CCGT] ... +3 Generator-p[2019-12-31 15:00:00, CCGT] + 3 Generator-p[2019-12-31 18:00:00, CCGT] + 3 Generator-p[2019-12-31 21:00:00, CCGT] ≥ 223200.0
text
Constraint `CCGT-period-max` [limit_period: 12]:
------------------------------------------------
[1]: +3 Generator-p[2019-01-01 00:00:00, CCGT] + 3 Generator-p[2019-01-01 03:00:00, CCGT] + 3 Generator-p[2019-01-01 06:00:00, CCGT] ... +3 Generator-p[2019-01-31 15:00:00, CCGT] + 3 Generator-p[2019-01-31 18:00:00, CCGT] + 3 Generator-p[2019-01-31 21:00:00, CCGT]  ≤ 595200.0
[2]: +3 Generator-p[2019-02-01 00:00:00, CCGT] + 3 Generator-p[2019-02-01 03:00:00, CCGT] + 3 Generator-p[2019-02-01 06:00:00, CCGT] ... +3 Generator-p[2019-02-28 15:00:00, CCGT] + 3 Generator-p[2019-02-28 18:00:00, CCGT] + 3 Generator-p[2019-02-28 21:00:00, CCGT]  ≤ 537600.0
[3]: +3 Generator-p[2019-03-01 00:00:00, CCGT] + 3 Generator-p[2019-03-01 03:00:00, CCGT] + 3 Generator-p[2019-03-01 06:00:00, CCGT] ... +3 Generator-p[2019-03-31 15:00:00, CCGT] + 3 Generator-p[2019-03-31 18:00:00, CCGT] + 3 Generator-p[2019-03-31 21:00:00, CCGT]  ≤ 595200.0
[4]: +3 Generator-p[2019-04-01 00:00:00, CCGT] + 3 Generator-p[2019-04-01 03:00:00, CCGT] + 3 Generator-p[2019-04-01 06:00:00, CCGT] ... +3 Generator-p[2019-04-30 15:00:00, CCGT] + 3 Generator-p[2019-04-30 18:00:00, CCGT] + 3 Generator-p[2019-04-30 21:00:00, CCGT]  ≤ 576000.0
[5]: +3 Generator-p[2019-05-01 00:00:00, CCGT] + 3 Generator-p[2019-05-01 03:00:00, CCGT] + 3 Generator-p[2019-05-01 06:00:00, CCGT] ... +3 Generator-p[2019-05-31 15:00:00, CCGT] + 3 Generator-p[2019-05-31 18:00:00, CCGT] + 3 Generator-p[2019-05-31 21:00:00, CCGT]  ≤ 595200.0
[6]: +3 Generator-p[2019-06-01 00:00:00, CCGT] + 3 Generator-p[2019-06-01 03:00:00, CCGT] + 3 Generator-p[2019-06-01 06:00:00, CCGT] ... +3 Generator-p[2019-06-30 15:00:00, CCGT] + 3 Generator-p[2019-06-30 18:00:00, CCGT] + 3 Generator-p[2019-06-30 21:00:00, CCGT]  ≤ 576000.0
[7]: +3 Generator-p[2019-07-01 00:00:00, CCGT] + 3 Generator-p[2019-07-01 03:00:00, CCGT] + 3 Generator-p[2019-07-01 06:00:00, CCGT] ... +3 Generator-p[2019-07-31 15:00:00, CCGT] + 3 Generator-p[2019-07-31 18:00:00, CCGT] + 3 Generator-p[2019-07-31 21:00:00, CCGT]  ≤ 595200.0
[8]: +3 Generator-p[2019-08-01 00:00:00, CCGT] + 3 Generator-p[2019-08-01 03:00:00, CCGT] + 3 Generator-p[2019-08-01 06:00:00, CCGT] ... +3 Generator-p[2019-08-31 15:00:00, CCGT] + 3 Generator-p[2019-08-31 18:00:00, CCGT] + 3 Generator-p[2019-08-31 21:00:00, CCGT]  ≤ 595200.0
[9]: +3 Generator-p[2019-09-01 00:00:00, CCGT] + 3 Generator-p[2019-09-01 03:00:00, CCGT] + 3 Generator-p[2019-09-01 06:00:00, CCGT] ... +3 Generator-p[2019-09-30 15:00:00, CCGT] + 3 Generator-p[2019-09-30 18:00:00, CCGT] + 3 Generator-p[2019-09-30 21:00:00, CCGT]  ≤ 576000.0
[10]: +3 Generator-p[2019-10-01 00:00:00, CCGT] + 3 Generator-p[2019-10-01 03:00:00, CCGT] + 3 Generator-p[2019-10-01 06:00:00, CCGT] ... +3 Generator-p[2019-10-31 15:00:00, CCGT] + 3 Generator-p[2019-10-31 18:00:00, CCGT] + 3 Generator-p[2019-10-31 21:00:00, CCGT] ≤ 595200.0
[11]: +3 Generator-p[2019-11-01 00:00:00, CCGT] + 3 Generator-p[2019-11-01 03:00:00, CCGT] + 3 Generator-p[2019-11-01 06:00:00, CCGT] ... +3 Generator-p[2019-11-30 15:00:00, CCGT] + 3 Generator-p[2019-11-30 18:00:00, CCGT] + 3 Generator-p[2019-11-30 21:00:00, CCGT] ≤ 576000.0
[12]: +3 Generator-p[2019-12-01 00:00:00, CCGT] + 3 Generator-p[2019-12-01 03:00:00, CCGT] + 3 Generator-p[2019-12-01 06:00:00, CCGT] ... +3 Generator-p[2019-12-31 15:00:00, CCGT] + 3 Generator-p[2019-12-31 18:00:00, CCGT] + 3 Generator-p[2019-12-31 21:00:00, CCGT] ≤ 595200.0

Visualize Results

Monthly CCGT output vs. constraints

The bar chart below shows the monthly CCGT energy output for both the baseline and the constrained run alongside the prescribed lower and upper bounds. In the constrained run the bars should always fall within the shaded region.

In [8]:

Copied! diagram

ipynb
def periodic_energy_balance(
    network: pypsa.Network | pypsa.NetworkCollection, grouper: pd.Series
) -> pd.Series:
    """Return periodic energy output [MWh] for a solved network.

    The `grouper` defines which snapshots belong to the same period, e.g. by month or by season.
    """
    weights = network.snapshot_weightings.generators
    energy_balance = network.statistics.energy_balance(
        groupby_time=False, bus_carrier="electricity"
    ).droplevel(["component", "bus_carrier"])
    energy_balance_period = (energy_balance * weights).T.groupby(grouper).sum()
    return energy_balance_period


def discharge_capacity(network: pypsa.Network | pypsa.NetworkCollection) -> pd.Series:
    """Return discharge capacity [MW] for a solved network."""
    generators = network.generators.p_nom_opt
    storage_units = network.storage_units.p_nom_opt
    capacity = pd.concat([generators, storage_units])
    return capacity


nc = pypsa.NetworkCollection({"Baseline": n_base, "Constrained": n_constrained})
grouper = get_grouper(
    n_constrained.components["Generator"].da["p_min_periodic"].sel(name="CCGT")
).to_series()

def periodic_energy_balance( network: pypsa.Network | pypsa.NetworkCollection, grouper: pd.Series ) -> pd.Series: """Return periodic energy output [MWh] for a solved network. The grouper defines which snapshots belong to the same period, e.g. by month or by season. """ weights = network.snapshot_weightings.generators energy_balance = network.statistics.energy_balance( groupby_time=False, bus_carrier="electricity" ).droplevel(["component", "bus_carrier"]) energy_balance_period = (energy_balance * weights).T.groupby(grouper).sum() return energy_balance_period def discharge_capacity(network: pypsa.Network | pypsa.NetworkCollection) -> pd.Series: """Return discharge capacity [MW] for a solved network.""" generators = network.generators.p_nom_opt storage_units = network.storage_units.p_nom_opt capacity = pd.concat([generators, storage_units]) return capacity nc = pypsa.NetworkCollection({"Baseline": n_base, "Constrained": n_constrained}) grouper = get_grouper( n_constrained.components["Generator"].da["p_min_periodic"].sel(name="CCGT") ).to_series()

In [9]:

Copied! diagram

ipynb
monthly_energy_balance = periodic_energy_balance(nc, grouper).xs(
    "CCGT", level="carrier", axis=1
)

month_labels = [calendar.month_abbr[m] for m in monthly_bounds.index]
df_plot = (
    monthly_energy_balance.stack().to_frame("Monthly CCGT dispatch (MWh)").reset_index()
)
df_plot["Month"] = df_plot["limit_period"].apply(lambda m: calendar.month_abbr[m])
fig = px.bar(
    df_plot,
    x="Month",
    y="Monthly CCGT dispatch (MWh)",
    color="network",
    barmode="group",
)

# Overlay the monthly bounds to verify that CCGT dispatch is within the limits
common_attrs = {
    "x": month_labels,
    "mode": "lines",
    "legendgroup": "bound",
    "line": {"width": 1, "shape": "hvh", "color": "black"},
}
fig.add_trace(go.Scatter(y=monthly_bounds["p_min"], showlegend=False, **common_attrs))
fig.add_trace(
    go.Scatter(
        y=monthly_bounds["p_max"],
        name="Feasible constrained range",
        fill="tonexty",
        fillcolor="rgba(169, 169, 169, 0.3)",
        **common_attrs,
    )
)

monthly_energy_balance = periodic_energy_balance(nc, grouper).xs( "CCGT", level="carrier", axis=1 ) month_labels = [calendar.month_abbr[m] for m in monthly_bounds.index] df_plot = ( monthly_energy_balance.stack().to_frame("Monthly CCGT dispatch (MWh)").reset_index() ) df_plot["Month"] = df_plot["limit_period"].apply(lambda m: calendar.month_abbr[m]) fig = px.bar( df_plot, x="Month", y="Monthly CCGT dispatch (MWh)", color="network", barmode="group", )

Overlay the monthly bounds to verify that CCGT dispatch is within the limits

common_attrs = { "x": month_labels, "mode": "lines", "legendgroup": "bound", "line": {"width": 1, "shape": "hvh", "color": "black"}, } fig.add_trace(go.Scatter(y=monthly_bounds["p_min"], showlegend=False, **common_attrs)) fig.add_trace( go.Scatter( y=monthly_bounds["p_max"], name="Feasible constrained range", fill="tonexty", fillcolor="rgba(169, 169, 169, 0.3)", **common_attrs, ) )

Monthly generation breakdown

Since the segmented network uses non-uniform snapshot durations, we aggregate by computing the weighted energy (p × snapshot_weighting) per technology per month. This gives total-generation [MWh] for each month and shows how the constraints redistribute generation between wind/solar, hydrogen, and the CCGT.

In [10]:

Copied! diagram

ipynb
capacity = discharge_capacity(nc)
df_plot = capacity.to_frame("Capacity (MW)").reset_index()
fig_capacity = px.bar(
    df_plot,
    x="name",
    y="Capacity (MW)",
    color="network",
    barmode="group",
)
fig_capacity.update_layout(
    xaxis_title="Generator / Storage unit", yaxis_title="Installed capacity (MW)"
)

capacity = discharge_capacity(nc) df_plot = capacity.to_frame("Capacity (MW)").reset_index() fig_capacity = px.bar( df_plot, x="name", y="Capacity (MW)", color="network", barmode="group", ) fig_capacity.update_layout( xaxis_title="Generator / Storage unit", yaxis_title="Installed capacity (MW)" )

System cost comparison

The monthly energy bounds force the CCGT away from its cost-optimal dispatch level. We compare the total system operating cost for both runs.

In [11]:

Copied! diagram

ipynb
with pd.option_context("display.float_format", "{:,.0f} M€".format):
    capex = nc.statistics.capex().groupby("network").sum() / 1e6
    opex = nc.statistics.opex().groupby("network").sum() / 1e6
    total = capex + opex
    cost_df = pd.concat([capex, opex, total], axis=1, keys=["Capex", "Opex", "Total"]).T
    cost_df["Cost delta"] = (
        cost_df["Constrained"]
        .subtract(cost_df["Baseline"])
        .div(cost_df["Baseline"])
        .mul(100)
        .round(1)
        .astype(str)
        + " %"
    )
    display(cost_df)

with pd.option_context("display.float_format", "{:,.0f} M€".format): capex = nc.statistics.capex().groupby("network").sum() / 1e6 opex = nc.statistics.opex().groupby("network").sum() / 1e6 total = capex + opex cost_df = pd.concat([capex, opex, total], axis=1, keys=["Capex", "Opex", "Total"]).T cost_df["Cost delta"] = ( cost_df["Constrained"] .subtract(cost_df["Baseline"]) .div(cost_df["Baseline"]) .mul(100) .round(1) .astype(str)

  • " %" ) display(cost_df)
networkBaselineConstrainedCost delta
Capex6,541 M€6,654 M€1.7 %
Opex284 M€286 M€0.6 %
Total6,825 M€6,940 M€1.7 %

diagram 2026-11-05

diagram 2026-03-30