Post · 31 min read· pp. 224–248

Flow-Based Market Coupling

Flow-based market coupling (FBMC) is how much of Europe allocates cross-border capacities of electricity trade. This notebook builds it up from scratch on a small three-zone system in PyPSA, in three parts:

  1. The domain - what the flow-based feasible region is and what it represents.
  2. Market clearing - letting PyPSA optimise the market clearing with a flow-based domain.
  3. External borders - ways to handle borders that lie outside the flow-based region.

The core idea

A market is split into zones (also called hubs or bidding zones). Each zone has a net position NPzNP_z: its total generation minus its load, i.e. its net export (positive) or import (negative), in MW. Net positions cause flows on the grid, and some combinations would overload a critical element. FBMC keeps the flow on each critical element within its remaining margin by a set of linear inequalities:

∑zPTDFc,z NPz≤RAMcfor every constraint c,∑zNPz=0.\sum_{z} \mathrm{PTDF}_{c,z}\, NP_z \le \mathrm{RAM}_c \quad\text{for every constraint } c, \qquad\qquad \sum_{z} NP_z = 0.

  • CNEC (Critical Network Element + Contingency) - a monitored grid element, in one flow direction, under one assumed outage. One CNEC = one constraint cc = one row.
  • Zonal PTDF (Power Transfer Distribution Factor) - how strongly zone zz's export loads CNEC cc. A value of 0.10.1 means 10% of the export flows over that element; a negative value means the export relieves it.
  • RAM (Remaining Available Margin) - the MW of headroom left on the CNEC for the market to use.
  • The second equation is energy conservation: exports and imports must net to zero.

Together these inequalities carve out the flow-based domain: the set of net-position combinations the grid can physically support. Throughout, we take the domain (PTDF + RAM) as a given input. Deriving it from a grid model is a separate task.

In [2]:

Copied! diagram

ipynb
import linopy
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.spatial import HalfspaceIntersection

import pypsa

import linopy import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.spatial import HalfspaceIntersection import pypsa

Part 1 - The flow-based domain

Three zones A, B, C sit at the corners of a triangle joined by three lines AB, BC, AC of equal reactance. Each line is monitored in both directions, so the domain has six CNECs. With three zones and ∑zNPz=0\sum_z NP_z = 0, only two net positions are free - the domain is a 2-D polygon we can draw.

The PTDFs are the textbook DC-flow values for an equal-reactance triangle with C as the reference zone (its column is zero). A unit export from A, withdrawn at C, splits 2/3 over the direct line AC and 1/3 over the detour AB+BC.

In [3]:

Copied! diagram

ipynb
zones = ["A", "B", "C"]
lines = {
    "AB": {"A": 1 / 3, "B": -1 / 3, "C": 0.0, "RAM": 1000.0},
    "BC": {"A": 1 / 3, "B": 2 / 3, "C": 0.0, "RAM": 1500.0},
    "AC": {"A": 2 / 3, "B": 1 / 3, "C": 0.0, "RAM": 2000.0},
}
pos = pd.DataFrame(lines).T
neg = pos.copy()
neg[zones] *= -1  # reverse direction: flip PTDF signs
domain = pd.concat(
    [pos.rename(lambda s: f"{s} (+)"), neg.rename(lambda s: f"{s} (-)")]
).sort_index()
domain.index.name = "cnec"
domain

zones = ["A", "B", "C"] lines = { "AB": {"A": 1 / 3, "B": -1 / 3, "C": 0.0, "RAM": 1000.0}, "BC": {"A": 1 / 3, "B": 2 / 3, "C": 0.0, "RAM": 1500.0}, "AC": {"A": 2 / 3, "B": 1 / 3, "C": 0.0, "RAM": 2000.0}, } pos = pd.DataFrame(lines).T neg = pos.copy() neg[zones] *= -1 # reverse direction: flip PTDF signs domain = pd.concat( [pos.rename(lambda s: f"{s} (+)"), neg.rename(lambda s: f"{s} (-)")] ).sort_index() domain.index.name = "cnec" domain

Out[3]:

ABCRAM
cnec
AB (+)0.333333-0.3333330.01000.0
AB (-)-0.3333330.333333-0.01000.0
AC (+)0.6666670.3333330.02000.0
AC (-)-0.666667-0.333333-0.02000.0
BC (+)0.3333330.6666670.01500.0
BC (-)-0.333333-0.666667-0.01500.0

Reading one row. AC (+) has PTDFA=0.67\mathrm{PTDF}_A = 0.67, PTDFB=0.33\mathrm{PTDF}_B = 0.33, RAM=2000\mathrm{RAM} = 2000, i.e. 0.67 NPA+0.33 NPB≤20000.67\,NP_A + 0.33\,NP_B \le 2000. If A exports 3000 MW with B balanced, the loading is 0.67×3000=20000.67 \times 3000 = 2000, exactly the limit. A is then pinned by line AC, unable to export more even while other lines still have room. That coupling between zones is what FBMC captures and a single number per border cannot.

Drawing the domain

Substituting NPC=−(NPA+NPB)NP_C = -(NP_A + NP_B) leaves (NPA,NPB)(NP_A, NP_B) as the two free axes; each CNEC becomes a straight edge and the feasible region is their intersection. The reduction is general: the effective coefficient on a free zone zz is PTDFc,z−PTDFc,ref\mathrm{PTDF}_{c,z} - \mathrm{PTDF}_{c,\mathrm{ref}}, where ref\mathrm{ref} is the chosen reference zone. The picture does not depend on which zone that is.

In [4]:

Copied! diagram

ipynb
ref = "C"
free = [z for z in zones if z != ref]
a_ub = domain[free].values - domain[[ref]].values  # half-plane coefficients
b_ub = domain["RAM"].values
hs = HalfspaceIntersection(np.column_stack([a_ub, -b_ub]), np.zeros(len(free)))
v = hs.intersections
poly = v[np.argsort(np.arctan2(v[:, 1] - v[:, 1].mean(), v[:, 0] - v[:, 0].mean()))]


def draw_domain(ax: plt.Axes) -> None:
    """Draw the feasible polygon, its CNEC reference lines and edge labels."""
    span = np.abs(poly).max() * 1.4
    t = np.array([-span, span])
    for a1, a2, rhs in zip(a_ub[:, 0], a_ub[:, 1], b_ub, strict=True):
        xy = (t, (rhs - a1 * t) / a2) if abs(a2) > abs(a1) else ((rhs - a2 * t) / a1, t)
        ax.plot(*xy, color="0.75", lw=0.8, zorder=0)
    ax.fill(poly[:, 0], poly[:, 1], color="#440154", alpha=0.12)
    ring = np.vstack([poly, poly[0]])
    ax.plot(ring[:, 0], ring[:, 1], color="#440154", lw=1.5)
    for p, q in zip(poly, ring[1:], strict=True):
        mid = (p + q) / 2
        ax.annotate(
            domain.index[np.argmin(b_ub - a_ub @ mid)],
            mid,
            textcoords="offset points",
            xytext=(4, 4),
            fontsize=8,
            color="#440154",
        )
    ax.axhline(0, linestyle="--", color="k", lw=0.6)
    ax.axvline(0, linestyle="--", color="k", lw=0.6)
    ax.set(
        xlim=(-span, span),
        ylim=(-span, span),
        aspect="equal",
        xlabel=f"NP_{free[0]}  (MW, export +)",
        ylabel=f"NP_{free[1]}  (MW, export +)",
    )


def check(np_free: tuple[float, float]) -> pd.DataFrame:
    """Return loadings, margins and active (binding) CNECs for a net position."""
    netpos = pd.Series(dict(zip(free, np_free, strict=True)))
    netpos[ref] = -netpos.sum()
    load = domain[zones] @ netpos
    out = pd.DataFrame(
        {
            "loading": load.round(1),
            "RAM": domain["RAM"],
            "margin": (domain["RAM"] - load).round(1),
        }
    )
    out["active"] = out["margin"].abs() < 1e-6
    return out

ref = "C" free = [z for z in zones if z != ref] a_ub = domain[free].values - domain[[ref]].values # half-plane coefficients b_ub = domain["RAM"].values hs = HalfspaceIntersection(np.column_stack([a_ub, -b_ub]), np.zeros(len(free))) v = hs.intersections poly = v[np.argsort(np.arctan2(v[:, 1] - v[:, 1].mean(), v[:, 0] - v[:, 0].mean()))] def draw_domain(ax: plt.Axes) -> None: """Draw the feasible polygon, its CNEC reference lines and edge labels.""" span = np.abs(poly).max() * 1.4 t = np.array([-span, span]) for a1, a2, rhs in zip(a_ub[:, 0], a_ub[:, 1], b_ub, strict=True): xy = (t, (rhs - a1 * t) / a2) if abs(a2) > abs(a1) else ((rhs - a2 * t) / a1, t) ax.plot(*xy, color="0.75", lw=0.8, zorder=0) ax.fill(poly[:, 0], poly[:, 1], color="#440154", alpha=0.12) ring = np.vstack([poly, poly[0]]) ax.plot(ring[:, 0], ring[:, 1], color="#440154", lw=1.5) for p, q in zip(poly, ring[1:], strict=True): mid = (p + q) / 2 ax.annotate( domain.index[np.argmin(b_ub - a_ub @ mid)], mid, textcoords="offset points", xytext=(4, 4), fontsize=8, color="#440154", ) ax.axhline(0, linestyle="--", color="k", lw=0.6) ax.axvline(0, linestyle="--", color="k", lw=0.6) ax.set( xlim=(-span, span), ylim=(-span, span), aspect="equal", xlabel=f"NP_{free[0]} (MW, export +)", ylabel=f"NP_{free[1]} (MW, export +)", ) def check(np_free: tuple[float, float]) -> pd.DataFrame: """Return loadings, margins and active (binding) CNECs for a net position.""" netpos = pd.Series(dict(zip(free, np_free, strict=True))) netpos[ref] = -netpos.sum() load = domain[zones] @ netpos out = pd.DataFrame( { "loading": load.round(1), "RAM": domain["RAM"], "margin": (domain["RAM"] - load).round(1), } ) out["active"] = out["margin"].abs() < 1e-6 return out

Three example net positions are marked below:

  • Case 1 NP = (+1000, -500, -500) - well inside the domain; every CNEC keeps spare margin.
  • Case 2 NP = (+1500, -1500, 0) - a straight transfer from A to B landing on an edge (one binding CNEC).
  • Case 3 NP = (+3000, 0, -3000) - A exporting to C, landing at a corner (two binding CNECs).

In [5]:

Copied! diagram

ipynb
case1, case2, case3 = (1000, -500), (1500, -1500), (3000, 0)

fig, ax = plt.subplots(figsize=(5.5, 5.5), layout="constrained")
draw_domain(ax)
for pt, name in [(case1, "Case 1"), (case2, "Case 2"), (case3, "Case 3")]:
    ax.scatter(*pt, color="C3", zorder=3)
    ax.annotate(
        name, pt, textcoords="offset points", xytext=(6, -12), fontsize=9, color="C3"
    )

case1, case2, case3 = (1000, -500), (1500, -1500), (3000, 0) fig, ax = plt.subplots(figsize=(5.5, 5.5), layout="constrained") draw_domain(ax) for pt, name in [(case1, "Case 1"), (case2, "Case 2"), (case3, "Case 3")]: ax.scatter(*pt, color="C3", zorder=3) ax.annotate( name, pt, textcoords="offset points", xytext=(6, -12), fontsize=9, color="C3" )

No description has been provided for this image

The shaded hexagon holds every combination of net positions that keeps all CNECs within their RAM; each grey line is one CNEC and the six touching the hexagon are its edges. The region is not a box: A's room to export depends on what B does.

Case 1 is strictly interior and no CNEC is active, so the market could move in any direction from here:

In [6]:

Copied! diagram

ipynb
check(case1)

check(case1)

Out[6]:

loadingRAMmarginactive
cnec
AB (+)500.01000.0500.0False
AB (-)-500.01000.01500.0False
AC (+)500.02000.01500.0False
AC (-)-500.02000.02500.0False
BC (+)0.01500.01500.0False
BC (-)0.01500.01500.0False

Case 2 loads the direct line AB hardest, so AB (+) is the single binding CNEC (zero margin):

In [7]:

Copied! diagram

ipynb
check(case2)

check(case2)

Out[7]:

loadingRAMmarginactive
cnec
AB (+)1000.01000.00.0True
AB (-)-1000.01000.02000.0False
AC (+)500.02000.01500.0False
AC (-)-500.02000.02500.0False
BC (+)-500.01500.02000.0False
BC (-)500.01500.01000.0False

Case 3 binds AB (+) and AC (+) at once and the two constraints pin the outcome:

In [8]:

Copied! diagram

ipynb
check(case3)

check(case3)

Out[8]:

loadingRAMmarginactive
cnec
AB (+)1000.01000.00.0True
AB (-)-1000.01000.02000.0False
AC (+)2000.02000.00.0True
AC (-)-2000.02000.04000.0False
BC (+)1000.01500.0500.0False
BC (-)-1000.01500.02500.0False

Part 2 - Clearing the market

So far we probed various net positions by hand. Now we give each zone generators and load and let PyPSA optimize the net position that meets demand at least cost while staying inside the domain. This is market clearing.

Representing FBMC in PyPSA

A zone's net position is simply its generation minus its load. We need a device that lets each zone be individually imbalanced while the system balances overall, and that exposes each NPzNP_z as a variable to constrain. We use an auxiliary pool bus:

  • one bus per zone (A, B, C) carrying that zone's generators and load;
  • one extra auxiliary bus pool as a modelling device;
  • one link zone -> pool per zone, where its flow denotes that zone's net position;
  • the pool's own energy balance then forces ∑zNPz=0\sum_z NP_z = 0 automatically;
  • the flow-based domain is one custom constraint on those link flows.

No physical lines or links between zones must be added: the grid physics lives entirely in the PTDF/RAM domain. For the example, we choose costs to create tension: zone A is cheap (10 EUR/MWh) and wants to export; B is expensive (80) with the largest load; C is in between (50).

We add the custom constraint by taking the linopy model from n.optimize.create_model(), adding the flow-based constraints, and solving with n.optimize.solve_model(). PyPSA also ships the domain as a built-in global constraint type, and the appendix clears the same market with it.

In [9]:

Copied! diagram

ipynb
loads = pd.Series({"A": 500.0, "B": 1500.0, "C": 1000.0})  # MW
cost = pd.Series({"A": 10.0, "B": 80.0, "C": 50.0})  # EUR/MWh


def add_fb_domain(m: linopy.Model, zones: list[str], ram: pd.Series) -> None:
    """Add PTDF . NP <= RAM to model m over the given domain columns."""
    netpos = m["Link-p"].sel(name=zones)
    m.add_constraints(netpos @ domain[zones] <= ram, name="fb_domain")


n = pypsa.Network()
n.add("Bus", [*zones, "pool"])
n.add("Load", zones, bus=zones, p_set=loads)
n.add("Generator", zones, bus=zones, p_nom=4000, marginal_cost=cost)
n.add("Link", zones, bus0=zones, bus1="pool", p_nom=10000, p_min_pu=-1)  # flow = NP_z
n.sanitize()

m = n.optimize.create_model()
add_fb_domain(m, zones, domain["RAM"])
n.optimize.solve_model(log_to_console=False)

loads = pd.Series({"A": 500.0, "B": 1500.0, "C": 1000.0}) # MW cost = pd.Series({"A": 10.0, "B": 80.0, "C": 50.0}) # EUR/MWh def add_fb_domain(m: linopy.Model, zones: list[str], ram: pd.Series) -> None: """Add PTDF . NP <= RAM to model m over the given domain columns.""" netpos = m["Link-p"].sel(name=zones) m.add_constraints(netpos @ domain[zones] <= ram, name="fb_domain") n = pypsa.Network() n.add("Bus", [*zones, "pool"]) n.add("Load", zones, bus=zones, p_set=loads) n.add("Generator", zones, bus=zones, p_nom=4000, marginal_cost=cost) n.add("Link", zones, bus0=zones, bus1="pool", p_nom=10000, p_min_pu=-1) # flow = NP_z n.sanitize() m = n.optimize.create_model() add_fb_domain(m, zones, domain["RAM"]) n.optimize.solve_model(log_to_console=False)

text
/tmp/ipykernel_3402/3663471481.py:11: 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.consistency:Sanitizing network...
text
INFO:pypsa.components._types.carriers:Adding 1 missing carriers: ['AC']
text
INFO:pypsa.components._types.carriers:Assigned colors to 1 carriers using 'tab10' palette.
text
INFO:pypsa.consistency:Network sanitization complete.
text
/tmp/ipykernel_3402/3663471481.py:18: 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.
  m = n.optimize.create_model()
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
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-7ex6t0yx.lp
text
Reading time = 0.00 seconds
text
obj: 22 rows, 6 columns, 33 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 6 primals, 22 duals
Objective: 6.50e+04
Solver: gurobi
Runtime: 0.00s
Dual bound: 6.50e+04
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, Link-fix-p-lower, Link-fix-p-upper, fb_domain were not assigned to the network.

Out[9]:

text
('ok', 'optimal')

Net positions and generation

The link flows are the net positions; generation shows who supplies whom.

In [10]:

Copied! diagram

ipynb
pd.DataFrame(
    {
        "net position": n.links_t.p0.iloc[0],
        "generation": n.generators_t.p.iloc[0],
        "load": pd.Series(loads),
    }
).round(1)

pd.DataFrame( { "net position": n.links_t.p0.iloc[0], "generation": n.generators_t.p.iloc[0], "load": pd.Series(loads), } ).round(1)

Out[10]:

net positiongenerationload
A2000.02500.0500.0
B-1000.0500.01500.0
C-1000.00.01000.0

A exports 2000 MW; B and C import 1000 MW each. But A does not serve everyone and B still runs its expensive 500 MW. A CNEC capped A's export.

From net positions to physical flows

The net position is a commercial quantity. Its physical consequence is the flow it puts on the grid: Fc=∑zPTDFc,z NPzF_c = \sum_z \mathrm{PTDF}_{c,z}\, NP_z, exactly the left-hand side of each domain inequality. In this toy model, every CNEC is a line between two regions, so these loadings are the actual MW flowing between the regions. Collapsing each line's two directions into one signed flow yields:

In [11]:

Copied! diagram

ipynb
netpos = n.links_t.p0.iloc[0]
flows = pd.DataFrame(
    {
        "physical flow": (pos[zones] @ netpos).round(1),  # signed MW on each line
        "Fmax": pos["RAM"],
    }
)
flows

netpos = n.links_t.p0.iloc[0] flows = pd.DataFrame( { "physical flow": (pos[zones] @ netpos).round(1), # signed MW on each line "Fmax": pos["RAM"], } ) flows

Out[11]:

physical flowFmax
AB1000.01000.0
BC0.01500.0
AC1000.02000.0

Line AB carries 1000 MW (its limit) while AC carries 1000 MW of its 2000 MW and BC carries nothing. The single line AB decides the whole outcome; on the domain picture the result lands exactly on the AB (+) edge:

In [12]:

Copied! diagram

ipynb
fig, ax = plt.subplots(figsize=(5, 5), layout="constrained")
draw_domain(ax)
ax.scatter(netpos["A"], netpos["B"], color="C3", zorder=3, s=40)
ax.annotate(
    "optimum",
    (netpos["A"], netpos["B"]),
    textcoords="offset points",
    xytext=(8, -4),
    fontsize=9,
    color="C3",
);

fig, ax = plt.subplots(figsize=(5, 5), layout="constrained") draw_domain(ax) ax.scatter(netpos["A"], netpos["B"], color="C3", zorder=3, s=40) ax.annotate( "optimum", (netpos["A"], netpos["B"]), textcoords="offset points", xytext=(8, -4), fontsize=9, color="C3", );

No description has been provided for this image

Prices and shadow prices

Two sets of dual variables are interesting to review:

  • zonal prices πz\pi_z - the dual of each zone's energy balance (EUR/MWh);
  • CNEC shadow prices μc\mu_c - the dual of each domain inequality, which describes the welfare gained per extra MW of RAM on that CNEC. A binding CNEC is also called an active constraint. linopy reports the dual of a ≤\le constraint as ≤0\le 0, so ∣μc∣|\mu_c| is that welfare value in EUR/MW.

In [13]:

Copied! diagram

ipynb
prices = n.buses_t.marginal_price.iloc[0].round(2)
prices.to_frame("price (EUR/MWh)")

prices = n.buses_t.marginal_price.iloc[0].round(2) prices.to_frame("price (EUR/MWh)")

Out[13]:

price (EUR/MWh)
name
A10.0
B80.0
C45.0
pool45.0

In [14]:

Copied! diagram

ipynb
shadow = n.model.constraints["fb_domain"].dual.sel(snapshot="now").to_pandas().round(2)
shadow[shadow != 0].to_frame("shadow price (EUR/MW)")

shadow = n.model.constraints["fb_domain"].dual.sel(snapshot="now").to_pandas().round(2) shadow[shadow != 0].to_frame("shadow price (EUR/MW)")

Out[14]:

shadow price (EUR/MW)
cnec
AB (+)-105.0

One binding CNEC (AB (+), ∣μ∣=105|\mu| = 105) splits the three zones into three prices: cheap A stays at 10, blocked B pays its own 80, C settles at 45.

The base price. The pool bus has no generation or load, so its price λ\lambda is the multiplier on the balance ∑zNPz=0\sum_z NP_z = 0: the copper-plate reference price that every zone would pay if no CNEC bound. Congestion then spreads the zonal prices around λ\lambda. That means zone zz sits at λ\lambda plus its PTDF-weighted shadow prices:

πz=λ+∑cμc PTDFc,z.\pi_z = \lambda + \sum_c \mu_c\, \mathrm{PTDF}_{c,z}.

We can do a plausibility check that must reproduce the solver's zonal prices:

In [15]:

Copied! diagram

ipynb
lam = prices["pool"]
mu = n.model.constraints["fb_domain"].dual.sel(snapshot="now").to_pandas()
pd.DataFrame(
    {"solver": prices[zones], "identity": (lam + domain[zones].T @ mu).round(2)}
)

lam = prices["pool"] mu = n.model.constraints["fb_domain"].dual.sel(snapshot="now").to_pandas() pd.DataFrame( {"solver": prices[zones], "identity": (lam + domain[zones].T @ mu).round(2)} )

Out[15]:

solveridentity
A10.010.0
B80.080.0
C45.045.0

They match. The spread between A and B is then (\sum_c \mu_c (\mathrm{PTDF}{c,A} - \mathrm{PTDF}{c,B}) = (-105),(\tfrac13 - (-\tfrac13)) = -70): B is 70 EUR/MWh higher than A, entirely attributable to the AB (+) constraint. This is how a grid limit becomes a price signal.

Part 3 - External borders

Real markets have borders to zones outside the flow-based region via HVDC links and neighbouring AC systems. Their exchanges still load the domain's CNECs, and there are two ways to handle them.

Standard Hybrid Coupling (SHC) - the external exchange is a fixed forecast. The flow it induces on the CNECs is reserved out of RAM before the market optimization runs, through the FuafF_{uaf} term of the RAM formula. The market cannot change it as it is treated as a static capacity reservation.

Advanced Hybrid Coupling (AHC) - the border becomes a virtual hub and receives its own PTDF column in the domain and a net position optimised by the market, against the RAM before that reservation. The reserved capacity moves from FuafF_{uaf} back into usable RAM.

The RAM formula

The margin published for each CNEC is built up from the physical line limit as

RAM=Fmax−FRM−Fuaf−F0−FLTN+AMR−IVA,\mathrm{RAM} = F_{max} - \mathrm{FRM} - F_{uaf} - F_{0} - F_{LTN} + \mathrm{AMR} - \mathrm{IVA},

where FmaxF_{max} is the maximum physical flow; FRM\mathrm{FRM} (flow reliability margin) a safety buffer (e.g. 10%); FuafF_{uaf} the flow from exchanges with non-flow-based borders (the forecast handled here); F0F_{0} the internal flow at all-zero net positions; FLTNF_{LTN} long-term nominations (low relevance); AMR\mathrm{AMR} an added minimum RAM (regulatory virtual capacity, e.g. 70% of FmaxF_{max}); and IVA\mathrm{IVA} a TSO validation reduction. Only FuafF_{uaf} concerns us; the others we fold into a single physical margin we take as RAM.

We add one external market X: a cheap import (20 EUR/MWh) arriving via an HVDC that lands at node B, so its PTDF column equals B's. To compare the two methods on equal footing we start from that physical margin RAM and, for SHC, subtract Fuaf=PTDFc,X NPXforecastF_{uaf} = \mathrm{PTDF}_{c,X}\, NP_X^{\mathrm{forecast}} ourselves. Under SHC the forecast is assumed to be a conservative 300 MW.

In [16]:

Copied! diagram

ipynb
domain["X"] = domain["B"]  # X lands at B -> same PTDF column
cost_x, forecast = 20.0, 300.0  # X price (EUR/MWh), SHC forecast export (MW)


def solve(mode: str) -> pypsa.Network:
    """Clear the market with the external border treated as SHC or AHC."""
    ext = [*zones, "X"]
    cols = ext if mode == "ahc" else zones  # domain columns
    ram = domain["RAM"] - (domain["X"] * forecast if mode == "shc" else 0.0)

    n = pypsa.Network()
    n.add("Bus", [*ext, "pool"])
    n.add("Load", zones, bus=zones, p_set=loads)
    n.add(
        "Generator",
        ext,
        bus=ext,
        p_nom=6000,
        marginal_cost=[cost.get(z, cost_x) for z in ext],
    )
    n.add("Link", ext, bus0=ext, bus1="pool", p_nom=10000, p_min_pu=-1)
    if mode == "shc":  # freeze X at the forecast
        n.links.loc["X", "p_set"] = forecast
    n.sanitize()

    m = n.optimize.create_model()
    add_fb_domain(m, cols, ram)
    n.optimize.solve_model(log_to_console=False)
    return n

domain["X"] = domain["B"] # X lands at B -> same PTDF column cost_x, forecast = 20.0, 300.0 # X price (EUR/MWh), SHC forecast export (MW) def solve(mode: str) -> pypsa.Network: """Clear the market with the external border treated as SHC or AHC.""" ext = [*zones, "X"] cols = ext if mode == "ahc" else zones # domain columns ram = domain["RAM"] - (domain["X"] * forecast if mode == "shc" else 0.0) n = pypsa.Network() n.add("Bus", [*ext, "pool"]) n.add("Load", zones, bus=zones, p_set=loads) n.add( "Generator", ext, bus=ext, p_nom=6000, marginal_cost=[cost.get(z, cost_x) for z in ext], ) n.add("Link", ext, bus0=ext, bus1="pool", p_nom=10000, p_min_pu=-1) if mode == "shc": # freeze X at the forecast n.links.loc["X", "p_set"] = forecast n.sanitize() m = n.optimize.create_model() add_fb_domain(m, cols, ram) n.optimize.solve_model(log_to_console=False) return n

The whole SHC/AHC difference sits in two lines of solve: SHC subtracts FuafF_{uaf} from RAM and freezes X's link; AHC keeps X's column in the domain and lets its link optimise. Clear both and compare.

In [17]:

Copied! diagram

ipynb
def summarise(n: pypsa.Network) -> pd.Series:
    netpos = n.links_t.p0.iloc[0]
    price = n.buses_t.marginal_price.iloc[0]
    dual = n.model.constraints["fb_domain"].dual.sel(snapshot="now").to_pandas()
    return pd.Series(
        {
            **{f"NP {z}": netpos[z] for z in [*zones, "X"]},
            **{f"price {z}": price[z] for z in [*zones, "X"]},
            "shadow AB(+)": -dual.get("AB (+)", 0.0),
            "total cost": n.objective,
        }
    )


nets = {mode: solve(mode) for mode in ["shc", "ahc"]}
compare = pd.DataFrame(
    {mode.upper(): summarise(nn) for mode, nn in nets.items()}
).round(1)
compare

def summarise(n: pypsa.Network) -> pd.Series: netpos = n.links_t.p0.iloc[0] price = n.buses_t.marginal_price.iloc[0] dual = n.model.constraints["fb_domain"].dual.sel(snapshot="now").to_pandas() return pd.Series( { **{f"NP {z}": netpos[z] for z in [*zones, "X"]}, **{f"price {z}": price[z] for z in [*zones, "X"]}, "shadow AB(+)": -dual.get("AB (+)", 0.0), "total cost": n.objective, } ) nets = {mode: solve(mode) for mode in ["shc", "ahc"]} compare = pd.DataFrame( {mode.upper(): summarise(nn) for mode, nn in nets.items()} ).round(1) compare

text
INFO:pypsa.consistency:Sanitizing network...
text
INFO:pypsa.components._types.carriers:Adding 1 missing carriers: ['AC']
text
INFO:pypsa.components._types.carriers:Assigned colors to 1 carriers using 'tab10' palette.
text
INFO:pypsa.consistency:Network sanitization complete.
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.03s
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-159m1bam.lp
text
Reading time = 0.00 seconds
text
obj: 28 rows, 8 columns, 41 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 8 primals, 31 duals
Objective: 4.70e+04
Solver: gurobi
Runtime: 0.00s
Dual bound: 4.70e+04
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, Link-fix-p-lower, Link-fix-p-upper, Link-p_set, fb_domain were not assigned to the network.
text
INFO:pypsa.consistency:Sanitizing network...
text
INFO:pypsa.components._types.carriers:Adding 1 missing carriers: ['AC']
text
INFO:pypsa.components._types.carriers:Assigned colors to 1 carriers using 'tab10' palette.
text
INFO:pypsa.consistency:Network sanitization complete.
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.03s
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-ax7jujk1.lp
text
Reading time = 0.00 seconds
text
obj: 27 rows, 8 columns, 46 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 8 primals, 27 duals
Objective: 3.50e+04
Solver: gurobi
Runtime: 0.00s
Dual bound: 3.50e+04
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, Link-fix-p-lower, Link-fix-p-upper, fb_domain were not assigned to the network.

Out[17]:

SHCAHC
NP A2000.02000.0
NP B-1300.0-1500.0
NP C-1000.0-1000.0
NP X300.0500.0
price A10.010.0
price B80.020.0
price C45.015.0
price X20.020.0
shadow AB(+)105.015.0
total cost47000.035000.0

Reading the columns:

  • X net position: frozen at 300 MW under SHC; the market pulls it to 500 MW under AHC.
  • Congestion: AB (+) binds in both, but its shadow price collapses from 105 €/MW to 15 €/MW. The extra cheap import relieves the very border that limited trade.
  • Prices: under SHC blocked zone B pays its own 80 €/MWh; under AHC the import reaches it and B falls to 20 €/MWh, compressing the spread.
  • Welfare: total cost drops from 47000 € to 35000 €, a 12000 € gain from 200 MW of cheap X displacing expensive B generation.

In [18]:

Copied! diagram

ipynb
ent = [*zones, "X"]
x = np.arange(len(ent))
fig, ax = plt.subplots(figsize=(6, 4), layout="constrained")
for i, (mode, col) in enumerate(
    zip(["SHC", "AHC"], ["#5ec962", "#3b528b"], strict=True)
):
    bars = ax.bar(
        x + (i - 0.5) * 0.4,
        compare.loc[[f"price {z}" for z in ent], mode],
        width=0.4,
        label=mode,
        color=col,
    )
    ax.bar_label(bars, fmt="%.0f", fontsize=8, padding=2)
ax.set_xticks(x, ent)
ax.set(
    xlabel="zone",
    ylabel="price (EUR/MWh)",
)
ax.legend(frameon=False);

ent = [*zones, "X"] x = np.arange(len(ent)) fig, ax = plt.subplots(figsize=(6, 4), layout="constrained") for i, (mode, col) in enumerate( zip(["SHC", "AHC"], ["#5ec962", "#3b528b"], strict=True) ): bars = ax.bar( x + (i - 0.5) * 0.4, compare.loc[[f"price {z}" for z in ent], mode], width=0.4, label=mode, color=col, ) ax.bar_label(bars, fmt="%.0f", fontsize=8, padding=2) ax.set_xticks(x, ent) ax.set( xlabel="zone", ylabel="price (EUR/MWh)", ) ax.legend(frameon=False);

No description has been provided for this image

Appendix: FBMC with the built-in flow_based global constraint

The pool bus and the zone -> pool links are a modelling device, not part of the market. Their only jobs are to give each zone an import/export outlet and to enforce sum(NP) = 0. PyPSA stores a flow-based domain natively as GlobalConstraint rows with type="flow_based", one per CNEC, with the zonal PTDF in columns ptdf_<zone> and the margin in ram. n.c.global_constraints.add_flow_based(zonal_ptdf, ram) writes them from a CNEC x zone frame.

n.optimize() then gives each zone bus a net-position variable inside its nodal balance,

genz−loadz−NPz=0,\text{gen}_z - \text{load}_z - NP_z = 0 ,

so the zonal prices still come from its dual, enforces sum(NP) = 0 and puts the domain PTDF . NP <= RAM on the net positions. No auxiliary components and no linopy code needed.

In [19]:

Copied! diagram

ipynb
na = pypsa.Network()
na.add("Bus", zones)
na.add("Load", zones, bus=zones, p_set=loads)
na.add("Generator", zones, bus=zones, p_nom=4000, marginal_cost=cost)
na.sanitize()
na.c.global_constraints.add_flow_based(domain[zones], domain["RAM"])
na.optimize()

pd.DataFrame(
    {
        "net position (MW)": na.buses_t.net_position.iloc[0][zones].round(0),
        "price (EUR/MWh)": na.buses_t.marginal_price.iloc[0][zones].round(1),
    }
)

na = pypsa.Network() na.add("Bus", zones) na.add("Load", zones, bus=zones, p_set=loads) na.add("Generator", zones, bus=zones, p_nom=4000, marginal_cost=cost) na.sanitize() na.c.global_constraints.add_flow_based(domain[zones], domain["RAM"]) na.optimize() pd.DataFrame( { "net position (MW)": na.buses_t.net_position.iloc[0][zones].round(0), "price (EUR/MWh)": na.buses_t.marginal_price.iloc[0][zones].round(1), } )

text
INFO:pypsa.consistency:Sanitizing network...
text
INFO:pypsa.components._types.carriers:Adding 1 missing carriers: ['AC']
text
INFO:pypsa.components._types.carriers:Assigned colors to 1 carriers using 'tab10' palette.
text
INFO:pypsa.consistency:Network sanitization complete.
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.02s
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-kpq64d2p.lp
text
Reading time = 0.00 seconds
text
obj: 16 rows, 6 columns, 27 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 6 primals, 16 duals
Objective: 6.50e+04
Solver: gurobi
Runtime: 0.00s
Dual bound: 6.50e+04
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, FlowBased-balance were not assigned to the network.

Out[19]:

net position (MW)price (EUR/MWh)
name
A2000.010.0
B-1000.080.0
C-1000.045.0

In [20]:

Copied! diagram

ipynb
mu = na.global_constraints_t.mu_ram.iloc[0]
display(mu[mu != 0].round(1).to_frame("shadow price (EUR/MW)"))
na.c.global_constraints.zonal_ptdf.round(3)

mu = na.global_constraints_t.mu_ram.iloc[0] display(mu[mu != 0].round(1).to_frame("shadow price (EUR/MW)")) na.c.global_constraints.zonal_ptdf.round(3)

shadow price (EUR/MW)
name
AB (+)-105.0

Out[20]:

busABC
name
AB (+)0.333-0.3330.0
AB (-)-0.3330.333-0.0
AC (+)0.6670.3330.0
AC (-)-0.667-0.333-0.0
BC (+)0.3330.6670.0
BC (-)-0.333-0.667-0.0

Identical to the pool clearing of Part 2 with NP = (2000, -1000, -1000), prices A=10, B=80, C=45 and AB (+) binding at -105 EUR/MW. The duals of the domain land in n.global_constraints_t.mu_ram, and the rows persist with the network like any global constraint (netCDF, CSV, n.copy()).

Part 3 modelled the external zone X as a hub with its own net position. With the built-in domain, X is simply a bus outside the zones joined to B by a Link, and the domain gets one column per corridor link: the CNEC sensitivity to the link flow with the zone net positions held fixed, h - PTDF_B for a corridor landing in B with hub sensitivity h. Here X lands at B, so h = PTDF_B and the column is zero: the import is already fully explained by B's net position, which now includes it. (Using the raw h instead would double count.) See Flow-Based Market Coupling in the user guide for the convention.

In [21]:

Copied! diagram

ipynb
ext = [*zones, "X"]
nb = pypsa.Network()
nb.add("Bus", ext)
nb.add("Load", zones, bus=zones, p_set=loads)
nb.add(
    "Generator",
    ext,
    bus=ext,
    p_nom=6000,
    marginal_cost=[cost.get(z, cost_x) for z in ext],
)
nb.add("Link", "X-B", bus0="X", bus1="B", p_nom=10000, p_min_pu=-1)  # AHC border into B
nb.sanitize()
domain_ahc = domain[zones].assign(
    **{"X-B": domain["X"] - domain["B"]}
)  # h - PTDF_B = 0
nb.c.global_constraints.add_flow_based(domain_ahc, domain["RAM"])
nb.optimize()

print(
    "import X -> B:",
    nb.links_t.p0.iloc[0]["X-B"].round(1),
    "MW; total cost:",
    round(nb.objective),
)
pd.DataFrame(
    {
        "generation - load (MW)": nb.buses_t.net_position.iloc[0][zones],
        "net position incl. corridor (MW)": nb.buses_t.p.iloc[0][zones],
        "price (EUR/MWh)": nb.buses_t.marginal_price.iloc[0][zones],
    }
).round(1)

ext = [*zones, "X"] nb = pypsa.Network() nb.add("Bus", ext) nb.add("Load", zones, bus=zones, p_set=loads) nb.add( "Generator", ext, bus=ext, p_nom=6000, marginal_cost=[cost.get(z, cost_x) for z in ext], ) nb.add("Link", "X-B", bus0="X", bus1="B", p_nom=10000, p_min_pu=-1) # AHC border into B nb.sanitize() domain_ahc = domain[zones].assign( **{"X-B": domain["X"] - domain["B"]} ) # h - PTDF_B = 0 nb.c.global_constraints.add_flow_based(domain_ahc, domain["RAM"]) nb.optimize() print( "import X -> B:", nb.links_t.p0.iloc[0]["X-B"].round(1), "MW; total cost:", round(nb.objective), ) pd.DataFrame( { "generation - load (MW)": nb.buses_t.net_position.iloc[0][zones], "net position incl. corridor (MW)": nb.buses_t.p.iloc[0][zones], "price (EUR/MWh)": nb.buses_t.marginal_price.iloc[0][zones], } ).round(1)

text
INFO:pypsa.consistency:Sanitizing network...
text
INFO:pypsa.components._types.carriers:Adding 1 missing carriers: ['AC']
text
INFO:pypsa.components._types.carriers:Assigned colors to 1 carriers using 'tab10' palette.
text
INFO:pypsa.consistency:Network sanitization complete.
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.03s
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-f13aweln.lp
text
Reading time = 0.00 seconds
text
obj: 21 rows, 8 columns, 34 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 8 primals, 21 duals
Objective: 3.50e+04
Solver: gurobi
Runtime: 0.00s
Dual bound: 3.50e+04
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, Link-fix-p-lower, Link-fix-p-upper, FlowBased-balance were not assigned to the network.
text
import X -> B: 500.0 MW; total cost: 35000

Out[21]:

generation - load (MW)net position incl. corridor (MW)price (EUR/MWh)
name
A2000.02000.010.0
B-1500.0-1000.020.0
C-1000.0-1000.015.0

Same market as the AHC column of Part 3: X exports 500 MW, B's price falls to 20 EUR/MWh and the cost to 35000 EUR. The two net-position readings differ only for B, by the 500 MW it imports: n.buses_t.net_position is generation minus load (the virtual-hub convention of published domains), n.buses_t.p the net position the domain constrains. Both zone sums close: the first against X, the second to zero.

diagram 2026-11-04

diagram 2026-09-21