Piecewise costs and constraints
In this example, we demonstrate how to represent non-linear system relationships as piecewise-linear curves in PyPSA. This allows us to describe such relationships as:
- Economies of scale (investment costs per unit capacity reduce as an asset's capacity increases)
- Marginal cost offer curves (marginal cost per unit dispatched energy changes an asset's dispatch increases)
- Part-load efficiencies (efficiency varies when an asset operates below its rated capacity)
Here, we build a model from the single-node capacity expansion example and update the electrolysis component with various piecewise curves. Note that the goal here is not necessarily to showcase a realistic scenario, but rather to demonstrate how it is possible to model piecewise costs and constraints in PyPSA.
In [2]:
Copied!
import matplotlib.pyplot as plt
import numpy as np
import pandas as pdimport matplotlib.pyplot as plt import numpy as np import pandas as pd
In [3]:
Copied!
n = pypsa.examples.model_energy()
# Add a hydrogen load to ensure electrolysis *must* be dispatched in the solution
n.add("Load", "hydrogen-demand", bus="hydrogen", p_set=n.loads_t.p_set["demand"] / 100)
n.components["Link"].static.loc["electrolysis", "marginal_cost"] = 10n = pypsa.examples.model_energy()
Add a hydrogen load to ensure electrolysis *must* be dispatched in the solution
n.add("Load", "hydrogen-demand", bus="hydrogen", p_set=n.loads_t.p_set["demand"] / 100) n.components["Link"].static.loc["electrolysis", "marginal_cost"] = 10
/tmp/ipykernel_8249/3114739314.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.examples.model_energy()INFO:pypsa.network.io:Imported network 'Model-Energy' has buses, carriers, generators, links, loads, storage_units, storesReference case
Our reference case will be a model in which the rated values for our CCGT are used.
In [4]:
Copied!
def update_electrolysis(n: pypsa.Network, **new_attrs) -> pypsa.Network:
n_new = n.copy()
n_new.add(
"Link",
"electrolysis",
**new_attrs,
**n.links.loc["electrolysis"].drop(new_attrs.keys()),
overwrite=True,
)
n_new.sanitize()
return n_newdef update_electrolysis(n: pypsa.Network, **new_attrs) -> pypsa.Network: n_new = n.copy() n_new.add( "Link", "electrolysis", **new_attrs, **n.links.loc["electrolysis"].drop(new_attrs.keys()), overwrite=True, ) n_new.sanitize() return n_new
In [5]:
Copied!
n_ref = update_electrolysis(n)
n_ref.optimize()n_ref = update_electrolysis(n) n_ref.optimize()
INFO:pypsa.consistency:Sanitizing network...INFO:pypsa.consistency:Network sanitization complete./tmp/ipykernel_8249/2283449539.py:2: 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_ref.optimize()INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/25 [00:00<?, ?it/s]Writing constraints.: 92%|█████████▏| 23/25 [00:00<00:00, 228.08it/s]Writing constraints.: 100%|██████████| 25/25 [00:00<00:00, 222.35it/s]Writing continuous variables.: 0%| | 0/12 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 12/12 [00:00<00:00, 412.42it/s]INFO:linopy.io: Writing time: 0.16sSet 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-9y8l06i5.lpReading time = 0.08 secondsobj: 70086 rows, 32126 columns, 129984 nonzerosSet parameter LogToConsole to value 0INFO:linopy.constants: Optimization successful:
Status: ok
Termination condition: optimal
Solution: 32126 primals, 75926 duals
Objective: 8.29e+09
Solver: gurobi
Runtime: 1.43s
Dual bound: 8.29e+09
Solver model: available
Solver message: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Generator-ext-p-lower, Generator-ext-p-upper, Link-ext-p-lower, Link-ext-p-upper, Store-ext-e-lower, Store-ext-e-upper, Store-ext-p-lower, Store-ext-p-upper, Store-ext-p_store-lower, Store-ext-p_store-upper, 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.Out[5]:
('ok', 'optimal')Creating piecewise relationships
Let's assume the following relationships:
The marginal investment cost of our electrolysis facility decreases until a tipping point where additional capacity faces a diseconomy. This could be caused by land purchase costs increasing for additional capacity beyond a certain level. We will describe this with a sigmoid-like curve:
For this example, we will use a scaling factor of 2.4
The electrolysis component in PyPSA represents a collection of real facilities, each with different marginal costs which will be applied in order of merit. We will represent this marginal cost offer curve as:
For this example, let's assume = 5, = 2 €/MWh, = 3€/MW³h
The efficiency of electrolysis degrades at part-load. Let's assume it follows a square root curve bounded by = 70% at full load and = 40% at 0% load:
We can approximate these non-linear relationships with a series of straight lines, or segments, which meet at breakpoints.
Here, we will heuristically select points along each curve to derive these segments.
In [6]:
Copied!
def plot_piecewise_constraints(
x_max,
n_breakpoints,
y_ref,
y_func,
title,
xlabel,
ylabel,
x_min=0,
cumulative: bool = False,
):
x_continuous = np.linspace(x_min, x_max, 500)
x_breakpoints = np.linspace(x_min, x_max, n_breakpoints)
y_breakpoints = y_func(x_breakpoints)
if cumulative:
x_vals = np.repeat(x_breakpoints, 2)[:-1]
y_vals = np.roll(np.repeat(y_breakpoints, 2), -1)[:-1]
else:
x_vals = x_breakpoints
y_vals = y_breakpoints
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x_continuous, y_func(x_continuous), lw=2, label="Non-linear curve")
ax.plot(x_vals, y_vals, "--o", lw=2, label="Piecewise linear")
ax.plot([x_min, x_max], y_ref, "-.o", lw=2, label="Reference linear")
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_title(title)
ax.legend()
plt.tight_layout()
plt.show()def plot_piecewise_constraints( x_max, n_breakpoints, y_ref, y_func, title, xlabel, ylabel, x_min=0, cumulative: bool = False, ): x_continuous = np.linspace(x_min, x_max, 500) x_breakpoints = np.linspace(x_min, x_max, n_breakpoints) y_breakpoints = y_func(x_breakpoints) if cumulative: x_vals = np.repeat(x_breakpoints, 2)[:-1] y_vals = np.roll(np.repeat(y_breakpoints, 2), -1)[:-1] else: x_vals = x_breakpoints y_vals = y_breakpoints fig, ax = plt.subplots(figsize=(6, 4)) ax.plot(x_continuous, y_func(x_continuous), lw=2, label="Non-linear curve") ax.plot(x_vals, y_vals, "--o", lw=2, label="Piecewise linear") ax.plot([x_min, x_max], y_ref, "-.o", lw=2, label="Reference linear") ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_title(title) ax.legend() plt.tight_layout() plt.show()
Investment cost – economy of scale followed by diseconomy of scale
In [7]:
Copied!
P_max_inv = 5000 # MW
C_max_inv = 190000 # €/MW
k = 3
def get_capital_cost_curve(P: np.array):
p = P / P_max_inv - 0.5
return C_max_inv * (p * np.sqrt(1 - k / 4) / np.sqrt(1 - k * p**2) + 0.5)
plot_piecewise_constraints(
P_max_inv,
4,
(C_max_inv, C_max_inv),
get_capital_cost_curve,
"Capital cost piecewise curve approximation",
"Capacity (MW)",
"Marginal capital cost (€/MW)",
cumulative=True,
)P_max_inv = 5000 # MW C_max_inv = 190000 # €/MW k = 3 def get_capital_cost_curve(P: np.array): p = P / P_max_inv - 0.5 return C_max_inv * (p * np.sqrt(1 - k / 4) / np.sqrt(1 - k * p**2) + 0.5) plot_piecewise_constraints( P_max_inv, 4, (C_max_inv, C_max_inv), get_capital_cost_curve, "Capital cost piecewise curve approximation", "Capacity (MW)", "Marginal capital cost (€/MW)", cumulative=True, )

We integrate the capital cost curve when defining the piecewise constraint in PyPSA. This represents the need to pay the costs for each marginal capacity increase at the capital cost of that increment. This means that, compared to a non-linear curve, the piecewise constraint deviates at high dispatch level as the area under each curve differs. This deviation would reduce with more breakpoints.
In [8]:
Copied!
def get_capex_curve(P: np.array):
capital_cost = get_capital_cost_curve(P)
return np.cumsum(
(capital_cost * P) - (capital_cost * pd.Series(P).shift(1).fillna(0).values)
)
plot_piecewise_constraints(
P_max_inv,
4,
(0, C_max_inv * P_max_inv),
get_capex_curve,
"CAPEX curve",
"Capacity (MW)",
"Total capital cost (€)",
)def get_capex_curve(P: np.array): capital_cost = get_capital_cost_curve(P) return np.cumsum( (capital_cost * P) - (capital_cost * pd.Series(P).shift(1).fillna(0).values) ) plot_piecewise_constraints( P_max_inv, 4, (0, C_max_inv * P_max_inv), get_capex_curve, "CAPEX curve", "Capacity (MW)", "Total capital cost (€)", )

Marginal cost offer curve
In [9]:
Copied!
C0_mc = 5 # €/h
alpha_mc = 2 # €/MWh
beta_mc = 3 # €/MW²h
P_max = 5000
def get_marginal_cost_curve(P_frac):
return C0_mc + alpha_mc * P_frac + beta_mc * P_frac**3
ref_mc = C0_mc + alpha_mc + beta_mc
plot_piecewise_constraints(
1,
4,
(ref_mc, ref_mc),
get_marginal_cost_curve,
"Marginal cost offer curve",
"Load rate (Dispatch / Rated dispatch)",
"Cost (€/MWh)",
cumulative=True,
)C0_mc = 5 # €/h alpha_mc = 2 # €/MWh beta_mc = 3 # €/MW²h P_max = 5000 def get_marginal_cost_curve(P_frac): return C0_mc + alpha_mc * P_frac + beta_mc * P_frac**3 ref_mc = C0_mc + alpha_mc + beta_mc plot_piecewise_constraints( 1, 4, (ref_mc, ref_mc), get_marginal_cost_curve, "Marginal cost offer curve", "Load rate (Dispatch / Rated dispatch)", "Cost (€/MWh)", cumulative=True, )

As with capital cost, we consider the integral of the marginal cost curve when defining the piecewise constraint in PyPSA. That is, each segment of the piecewise curve will define different marginal cost rates for increasing dispatch. This means that, compared to a non-linear curve, the piecewise constraint deviates at high dispatch level as the area under each curve is slightly different.
In [10]:
Copied!
def get_opex_curve(P_out, p_max=P_max):
P_frac = P_out / p_max
marginal_cost = get_marginal_cost_curve(P_frac)
return np.cumsum(
(marginal_cost * P_out)
- (marginal_cost * pd.Series(P_out).shift(1).fillna(0).values)
)
plot_piecewise_constraints(
5000,
4,
(0, ref_mc * P_max),
get_opex_curve,
"OPEX curve",
"Dispatch (MWh)",
"Operating cost (€)",
)def get_opex_curve(P_out, p_max=P_max): P_frac = P_out / p_max marginal_cost = get_marginal_cost_curve(P_frac) return np.cumsum( (marginal_cost * P_out)
- (marginal_cost * pd.Series(P_out).shift(1).fillna(0).values) ) plot_piecewise_constraints( 5000, 4, (0, ref_mc * P_max), get_opex_curve, "OPEX curve", "Dispatch (MWh)", "Operating cost (€)", )

Part-load efficiency
In [11]:
Copied!
eta_rated = 0.7 # efficiency at full load
eta_min = 0.4 # efficiency at zero load
P_frac_min = 0 # minimum load fraction (η is finite at zero load)
P_max = 1000
def get_part_load_eff_curve(P_frac):
return (eta_rated - eta_min) * np.sqrt(P_frac) + eta_min
plot_piecewise_constraints(
1,
6,
(eta_rated, eta_rated),
get_part_load_eff_curve,
"Part-load efficiency",
"Load rate (Dispatch / Rated dispatch)",
"Efficiency",
x_min=P_frac_min,
cumulative=False,
)eta_rated = 0.7 # efficiency at full load eta_min = 0.4 # efficiency at zero load P_frac_min = 0 # minimum load fraction (η is finite at zero load) P_max = 1000 def get_part_load_eff_curve(P_frac): return (eta_rated - eta_min) * np.sqrt(P_frac) + eta_min plot_piecewise_constraints( 1, 6, (eta_rated, eta_rated), get_part_load_eff_curve, "Part-load efficiency", "Load rate (Dispatch / Rated dispatch)", "Efficiency", x_min=P_frac_min, cumulative=False, )

We do not consider part-load as a marginal constraint, therefore we do not take the integral of the piecewise curve when applying the constraint:
In [12]:
Copied!
def get_load_in_curve(P_out):
eff = get_part_load_eff_curve(P_out / P_max)
return P_out / eff
plot_piecewise_constraints(
P_max,
6,
(0, P_max / eta_rated),
get_load_in_curve,
"Energy consumption curve",
"Dispatch (MWh)",
"Energy consumption (MWh)",
x_min=P_frac_min,
)def get_load_in_curve(P_out): eff = get_part_load_eff_curve(P_out / P_max) return P_out / eff plot_piecewise_constraints( P_max, 6, (0, P_max / eta_rated), get_load_in_curve, "Energy consumption curve", "Dispatch (MWh)", "Energy consumption (MWh)", x_min=P_frac_min, )

Piecewise attributes for extendable components
Of the above curves, only (dis)economies of scale can be applied to the case where our electrolysis component is extendable.
The other two relate to the load rate of a component (p/p_nom) which is a non-linear relationship of two decision variables when the component is extendable.
Let's see what happens when we add this piecewise constraint:
In [13]:
Copied!
p_nom_breakpoints = np.array([0, 1000, 2000, 3000, 4000])
capital_costs = get_capital_cost_curve(p_nom_breakpoints)
n_piecewise_capex = update_electrolysis(
n,
capital_cost=dict(zip(p_nom_breakpoints, capital_costs)),
)
n_piecewise_capex.optimize(reformulate_sos="auto")p_nom_breakpoints = np.array([0, 1000, 2000, 3000, 4000]) capital_costs = get_capital_cost_curve(p_nom_breakpoints) n_piecewise_capex = update_electrolysis( n, capital_cost=dict(zip(p_nom_breakpoints, capital_costs)), ) n_piecewise_capex.optimize(reformulate_sos="auto")
INFO:pypsa.consistency:Sanitizing network...INFO:pypsa.consistency:Network sanitization complete.INFO:linopy.piecewise:piecewise formulation 'Link-capital_cost_piecewise': auto selected method='lp' (sign='>=', 2 pairs)INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/28 [00:00<?, ?it/s]Writing constraints.: 82%|████████▏ | 23/28 [00:00<00:00, 226.88it/s]Writing constraints.: 100%|██████████| 28/28 [00:00<00:00, 226.98it/s]Writing continuous variables.: 0%| | 0/13 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 13/13 [00:00<00:00, 405.76it/s]INFO:linopy.io: Writing time: 0.17sSet 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-pcls2wy9.lpReading time = 0.09 secondsobj: 70092 rows, 32127 columns, 129994 nonzerosSet parameter LogToConsole to value 0INFO:linopy.constants: Optimization successful:
Status: ok
Termination condition: optimal
Solution: 32127 primals, 75932 duals
Objective: 7.96e+09
Solver: gurobi
Runtime: 2.03s
Dual bound: 7.96e+09
Solver model: available
Solver message: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Generator-ext-p-lower, Generator-ext-p-upper, Link-ext-p-lower, Link-ext-p-upper, Store-ext-e-lower, Store-ext-e-upper, Store-ext-p-lower, Store-ext-p-upper, Store-ext-p_store-lower, Store-ext-p_store-upper, 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.Out[13]:
('ok', 'optimal')We can see the results stored in a new component piecewise data table:
In [14]:
Copied!
display(n_piecewise_capex.c.links.piecewise.capital_cost)display(n_piecewise_capex.c.links.piecewise.capital_cost)
| name | electrolysis | |
|---|---|---|
| attribute | p_nom | capital_cost |
| breakpoint | ||
| 0 | 0.0 | 0.000000 |
| 1 | 1000.0 | 61643.273049 |
| 2 | 2000.0 | 85354.211431 |
| 3 | 3000.0 | 104645.788569 |
| 4 | 4000.0 | 128356.726951 |
We can see that the capital expenditure in electrolysis capacity sits on our piecewise curve:
In [15]:
Copied!
capital_cost_opt = n_piecewise_capex.links.loc[
"electrolysis", "capital_cost_piecewise_opt"
]
p_nom_opt = n_piecewise_capex.links.loc["electrolysis", "p_nom_opt"]
capex_opt = capital_cost_opt * p_nom_opt
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.scatter(p_nom_opt, capex_opt, label="Optimal capital cost")
ax.plot(
p_nom_breakpoints,
get_capex_curve(p_nom_breakpoints),
"--o",
color="red",
label="Piecewise linear capital cost",
)
ax.legend()
ax.set_xlabel("Nominal capacity (MW)")
ax.set_ylabel("CAPEX (€)")
ax.set_title("Electrolysis capital costs (CAPEX)")capital_cost_opt = n_piecewise_capex.links.loc[ "electrolysis", "capital_cost_piecewise_opt" ] p_nom_opt = n_piecewise_capex.links.loc["electrolysis", "p_nom_opt"] capex_opt = capital_cost_opt * p_nom_opt fig, ax = plt.subplots(1, 1, figsize=(6, 4)) ax.scatter(p_nom_opt, capex_opt, label="Optimal capital cost") ax.plot( p_nom_breakpoints, get_capex_curve(p_nom_breakpoints), "--o", color="red", label="Piecewise linear capital cost", ) ax.legend() ax.set_xlabel("Nominal capacity (MW)") ax.set_ylabel("CAPEX (€)") ax.set_title("Electrolysis capital costs (CAPEX)")
Out[15]:
Text(0.5, 1.0, 'Electrolysis capital costs (CAPEX)')
Piecewise attributes for non-extendable components
Let's fix the capacity and apply our marginal cost piecewise constraint.
Unlike capital cost, which is defined as capital expenditure at each p_nom level, marginal cost is defined per unit dispatch, namely p_pu.
This means, our breakpoints exist in the range zero to one.
In [16]:
Copied!
p_pu_breakpoints = np.array([0, 0.25, 0.5, 0.75, 1.0])
marginal_cost = get_marginal_cost_curve(p_pu_breakpoints)
n_piecewise_opex = update_electrolysis(
n,
marginal_cost=dict(zip(p_pu_breakpoints, marginal_cost)),
p_nom_extendable=False,
p_nom=n_ref.links.loc["electrolysis", "p_nom_opt"],
)
n_piecewise_opex.optimize()p_pu_breakpoints = np.array([0, 0.25, 0.5, 0.75, 1.0]) marginal_cost = get_marginal_cost_curve(p_pu_breakpoints) n_piecewise_opex = update_electrolysis( n, marginal_cost=dict(zip(p_pu_breakpoints, marginal_cost)), p_nom_extendable=False, p_nom=n_ref.links.loc["electrolysis", "p_nom_opt"], ) n_piecewise_opex.optimize()
WARNING:pypsa.network.io:Piecewise 'marginal_cost' values price the increment from the previous breakpoint, so the y-value at x=0 spans zero width and will be ignored. To set the y-value for the first segment, set the value on the second breakpoint instead, e.g. {0.0: 0.0, 0.5: 40.0} for a 'marginal_cost' of 40 up to 0.5 'p_pu'. Affected components: ['electrolysis'].INFO:pypsa.consistency:Sanitizing network...INFO:pypsa.consistency:Network sanitization complete.INFO:linopy.piecewise:piecewise formulation 'Link-marginal_cost_piecewise': auto selected method='lp' (sign='>=', 2 pairs)INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io:Writing objective.Writing constraints.: 0%| | 0/30 [00:00<?, ?it/s]Writing constraints.: 83%|████████▎ | 25/30 [00:00<00:00, 233.63it/s]Writing constraints.: 100%|██████████| 30/30 [00:00<00:00, 221.47it/s]Writing continuous variables.: 0%| | 0/13 [00:00<?, ?it/s]Writing continuous variables.: 100%|██████████| 13/13 [00:00<00:00, 415.95it/s]INFO:linopy.io: Writing time: 0.18sSet 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-51bcfp4e.lpReading time = 0.10 secondsobj: 87605 rows, 35045 columns, 156263 nonzerosSet parameter LogToConsole to value 0INFO:linopy.constants: Optimization successful:
Status: ok
Termination condition: optimal
Solution: 35045 primals, 93445 duals
Objective: 7.74e+09
Solver: gurobi
Runtime: 2.21s
Dual bound: 7.74e+09
Solver model: available
Solver message: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Generator-ext-p-lower, Generator-ext-p-upper, Link-fix-p-lower, Link-fix-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, Link-marginal_cost_piecewise_chord, Link-marginal_cost_piecewise_domain_lo, Link-marginal_cost_piecewise_domain_hi were not assigned to the network.Out[16]:
('ok', 'optimal')As with capital cost in our previous example, we can see our marginal cost defined in the piecewise data table.
This time, however, the values are given per unit, i.e., €/MWh.
In the capital cost case, they were given as total cost at each point along the curve (i.e., €).
In [17]:
Copied!
display(n_piecewise_opex.c.links.piecewise.marginal_cost)display(n_piecewise_opex.c.links.piecewise.marginal_cost)
| name | electrolysis | |
|---|---|---|
| attribute | p_pu | marginal_cost |
| breakpoint | ||
| 0 | 0.00 | 5.000000 |
| 1 | 0.25 | 5.546875 |
| 2 | 0.50 | 6.375000 |
| 3 | 0.75 | 7.765625 |
| 4 | 1.00 | 10.000000 |
We can see that the marginal costs of electrolysis follow our piecewise curve:
In [18]:
Copied!
marginal_cost_opt = n_piecewise_opex.links_t.marginal_cost_piecewise_opt["electrolysis"]
p = n_piecewise_opex.links_t.p["electrolysis"]
opex_opt = marginal_cost_opt * p
p_nom_opt = n_piecewise_opex.links.loc["electrolysis", "p_nom"]
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.scatter(p, opex_opt, label="Optimal OPEX")
ax.plot(
p_pu_breakpoints * p_nom_opt,
get_opex_curve(p_pu_breakpoints * p_nom_opt, p_nom_opt),
"--o",
color="red",
label="Piecewise linear OPEX",
)
ax.legend()
ax.set_xlabel("Dispatch (MWh)")
ax.set_ylabel("OPEX (€)")
ax.set_title("Per-snapshot electrolysis operating costs (OPEX)")marginal_cost_opt = n_piecewise_opex.links_t.marginal_cost_piecewise_opt["electrolysis"] p = n_piecewise_opex.links_t.p["electrolysis"] opex_opt = marginal_cost_opt * p p_nom_opt = n_piecewise_opex.links.loc["electrolysis", "p_nom"] fig, ax = plt.subplots(1, 1, figsize=(6, 4)) ax.scatter(p, opex_opt, label="Optimal OPEX") ax.plot( p_pu_breakpoints * p_nom_opt, get_opex_curve(p_pu_breakpoints * p_nom_opt, p_nom_opt), "--o", color="red", label="Piecewise linear OPEX", ) ax.legend() ax.set_xlabel("Dispatch (MWh)") ax.set_ylabel("OPEX (€)") ax.set_title("Per-snapshot electrolysis operating costs (OPEX)")
Out[18]:
Text(0.5, 1.0, 'Per-snapshot electrolysis operating costs (OPEX)')
Now let's fix the capacity and apply our part-load efficiency piecewise constraint.
As with marginal cost, it requires the capacity to be fixed and for the breakpoints to be defined per unit, i.e., p_pu.
Part-load efficiency curves often make the problem much harder to solve, especially compared to piecewise costs. Therefore, we will only solve the first 200 snapshots of our problem for this example.
In [19]:
Copied!
p_pu_breakpoints = np.array([0, 0.25, 0.5, 0.75, 1.0])
efficiencies = get_part_load_eff_curve(p_pu_breakpoints)
n_piecewise_efficiency = update_electrolysis(
n,
efficiency=dict(zip(p_pu_breakpoints, efficiencies)),
p_nom_extendable=False,
p_nom=n_ref.links.loc["electrolysis", "p_nom_opt"],
)
n_piecewise_efficiency.optimize(reformulate_sos=True, snapshots=n.snapshots[:200])p_pu_breakpoints = np.array([0, 0.25, 0.5, 0.75, 1.0]) efficiencies = get_part_load_eff_curve(p_pu_breakpoints) n_piecewise_efficiency = update_electrolysis( n, efficiency=dict(zip(p_pu_breakpoints, efficiencies)), p_nom_extendable=False, p_nom=n_ref.links.loc["electrolysis", "p_nom_opt"], ) n_piecewise_efficiency.optimize(reformulate_sos=True, snapshots=n.snapshots[:200])
WARNING:pypsa.network.io:A non-zero y value at x=0 for piecewise 'efficiency' will be ignored when the piecewise constraint is defined since y values are denormalised using x values. To approximate 'efficiency' as non-zero at 'p_pu'=0, consider setting it at a very small x value instead, e.g. {0.0: 0.0, 0.001: 10, 0.5: 40.0}. Affected components: ['electrolysis'].INFO:pypsa.consistency:Sanitizing network...INFO:pypsa.consistency:Network sanitization complete.INFO:linopy.piecewise:piecewise formulation 'Link-p1_piecewise': auto selected method='incremental' (sign='=', 2 pairs)INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io: Writing time: 0.15sSet 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-b0tpksyf.lpReading time = 0.01 secondsobj: 7205 rows, 4005 columns, 14666 nonzerosSet parameter LogToConsole to value 0WARNING:linopy.solvers:Dual values of MILP couldn't be parsedINFO:linopy.constants: Optimization successful:
Status: ok
Termination condition: optimal
Solution: 4005 primals, 0 duals
Objective: 5.51e+09
Solver: gurobi
Runtime: 0.23s
MIP gap: 9.49e-05
Dual bound: 5.51e+09
Solver model: available
Solver message: 2INFO:pypsa.optimization.optimize:No shadow prices were assigned to the network.Out[19]:
('ok', 'optimal')We can see that the electrolysis efficiency follow our piecewise curve:
In [20]:
Copied!
p1_opt = -1 * n_piecewise_efficiency.links_t.p1["electrolysis"]
p = n_piecewise_efficiency.links_t.p["electrolysis"]
p_nom_opt = n_piecewise_efficiency.links.loc["electrolysis", "p_nom"]
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.scatter(p, p1_opt, label="Optimal operation")
ax.plot(
p_pu_breakpoints * p_nom_opt,
efficiencies * p_nom_opt * p_pu_breakpoints,
"--o",
color="red",
label="Piecewise linear operation",
)
ax.legend()
ax.set_xlabel("Electricity input (MWh)")
ax.set_ylabel("Hydrogen output (MWh)")
ax.set_title("Per-snapshot electrolysis operating efficiency")p1_opt = -1 * n_piecewise_efficiency.links_t.p1["electrolysis"] p = n_piecewise_efficiency.links_t.p["electrolysis"] p_nom_opt = n_piecewise_efficiency.links.loc["electrolysis", "p_nom"] fig, ax = plt.subplots(1, 1, figsize=(6, 4)) ax.scatter(p, p1_opt, label="Optimal operation") ax.plot( p_pu_breakpoints * p_nom_opt, efficiencies * p_nom_opt * p_pu_breakpoints, "--o", color="red", label="Piecewise linear operation", ) ax.legend() ax.set_xlabel("Electricity input (MWh)") ax.set_ylabel("Hydrogen output (MWh)") ax.set_title("Per-snapshot electrolysis operating efficiency")
Out[20]:
Text(0.5, 1.0, 'Per-snapshot electrolysis operating efficiency')
2026-08-05
2026-08-04