Post · 24 min read· pp. 434–451

Imperfect Competition

This example demonstrates how to model oligopolistic behaviour in energy markets using PyPSA. The notebook provides some theoretical background and a quick neat PyPSA implementation.

Spoiler: we implemented Cournot-Nash equilibrium without KKT conditions, complementarity solvers, big-M constraints, or any structural changes to cost-minimization problem instance created by PyPSA. Instead, we use a trick known as the "fictitious objective" in the economics/OR literature, perhaps underappreciated in energy system modelling stream.

Background: why bother?

We can think of plentiful examples of oligopolistic markets in energy context, where handful of large producers can exercise market power and drive up prices: natural gas supply, gas turbines manufacturing, material supply chains, etc.

The standard approach to modelling imperfect competition games is via Karush-Kuhn-Tucker (KKT) conditions, formulating Mixed Complementarity Problems (MCPs) and solving them with specialised solvers (mainly PATH). An amazing resource for learning about this is Complementarity Modeling in Energy Markets by Steven Gabriel and co-authors.

MCP feature complementarity constraints that yield non-convexities, but a Big-M method can make them tractable for MIP solvers. Thus we can implement imperfect competition models with complementarity constraints in linopy, for example this quick linopy example covers perfect competition, Cournot-Nash oligopoly, asymmetric information, Stackelberg, and conjectural variations games solved as mixed-integer linear problems based on KKT conditions.

However, this approach is impractical for PyPSA implementation. PyPSA acts as an optimisation wrapper around a network (model) instance — it automatically builds a cost-minimisation problem (LP, MIP, or QP) from the user-defined components and their attributes. Casting an MCP would require automatic derivation of first-order conditions and mapping of dual variables for each component, which would be tricky (if possible at all?) to generalise across all of PyPSA's functionality. It turns out there is another route in the economics/OR literature from 1990s.

The "fictitious objective"

The Cournot equilibrium among NN players can be characterised as the solution to a single optimisation problem. Margaret Slade's 1994 paper calls it a "fictitious-objective function" that reproduces equilibrium game results. The paper shows that for the homogeneous Cournot game, linear demand is sufficient for the existence of such a fictitious objective.

Ben Hobbs also explored this topic in 2001 paper by studying properties of MCP and LCP (Linear Complementarity Problem) formulations. The paper concludes: "The key assumption that permits their [KKT-based equilibrium] formulation as LCPs is that each producer naively assumes that its output will not affect transmission prices" - so another condition for the existence of a fictitious objective is that players treat transmission prices as fixed (the player's perceived derivative of the transmission shadow price with respect to its own output is zero), so congestion enters every player's problem as a linear term.

Let's work through the math, then see it in action in PyPSA.

Setup

Consider a market with NN generators indexed by i=1,…,Ni = 1, \ldots, N, each choosing dispatch qi≥0q_i \geq 0 [MW]. Total supply is Q=∑i=1NqiQ = \sum_{i=1}^{N} q_i.

The market price PP is given by the inverse demand function, linear in total supply QQ:

P(Q)=a−b⋅Q,a>0,  b>0P(Q) = a - b \cdot Q, \qquad a > 0, \; b > 0

where aa [EUR/MWh] is the maximum willingness to pay and bb [EUR/MWh per MW] is the demand slope. In the code example below: a=30a = 30, b=4b = 4.

Generator cost functions are convex and producer-specific:

Ci(qi),Ci′(qi)>0,Ci′′(qi)≥0C_i(q_i), \qquad C_i'(q_i) > 0, \quad C_i''(q_i) \geq 0

In the code example, both gas producers use Ci(qi)=qi+0.5⋅qi2C_i(q_i) = q_i + 0.5 \cdot q_i^2, set via marginal_cost=1 and marginal_cost_quadratic=0.5 for simplicity matter. However, the results below hold for any convex cost functions (i.e. no symmetry is required) and any number of generators.

Perfect competition (cost optimisation problem)

In standard energy system optimisation (e.g. PyPSA's n.optimize()), the model dispatches generators to minimise total system cost (equivalently, maximise social welfare). Each generator is a price-taker: it bids its marginal cost and the market clears. The generator's implicit problem is:

max⁡qi  P⋅qi−Ci(qi)\max_{q_i} \; P \cdot q_i - C_i(q_i)

First-Order Condition (FOC):

P=Ci′(qi)(1)P = C_i'(q_i) \tag{1}

Each generator produces up to the point where the market price equals its marginal cost. This is often referred to as the merit-order dispatch (by energy folks), or as a result implied by KKT condition and complementarity slackness (by math folks). The market price (shadow price of the bus power balance constraint) clears the market:

P∗=a−b∑i=1Nqi∗P^* = a - b \sum_{i=1}^{N} q_i^*

This competitive equilibrium is also the solution to the social welfare maximisation problem:

max⁡{qi}  ∫0QP(s) ds⏟gross consumer surplus−∑i=1NCi(qi)(W)\max_{\{q_i\}} \; \underbrace{\int_0^Q P(s) \, ds}_{\text{gross consumer surplus}} - \sum_{i=1}^{N} C_i(q_i) \tag{W}

For linear demand, this becomes:

max⁡{qi}  a⋅Q−b2⋅Q2−∑i=1NCi(qi)\max_{\{q_i\}} \; a \cdot Q - \frac{b}{2} \cdot Q^2 - \sum_{i=1}^{N} C_i(q_i)

Differentiating (W)(W) with respect to qiq_i recovers exactly the competitive FOC (1)(1):

∂W∂qi=a−b⋅Q−Ci′(qi)=P(Q)−Ci′(qi)=0\frac{\partial W}{\partial q_i} = a - b \cdot Q - C_i'(q_i) = P(Q) - C_i'(q_i) = 0

This is the First Welfare Theorem: least-cost dispatch produces the competitive equilibrium. This is "Problem A" in the code below, solved by PyPSA's n.optimize() without any modifications.

Cournot competition (strategic generators)

The Cournot conjecture

Under Cournot competition, each generator recognises that its own dispatch qiq_i affects the market price. Generator ii solves:

max⁡qi  P(Q)⋅qi−Ci(qi)\max_{q_i} \; P(Q) \cdot q_i - C_i(q_i)

where Q=qi+Q−iQ = q_i + Q_{-i} and Q−i=∑j≠iqjQ_{-i} = \sum_{j \neq i} q_j is the total output of all rivals. The Cournot assumption is that each generator takes rivals' output Q−iQ_{-i} as fixed when choosing qiq_i, so ∂Q∂qi=1\frac{\partial Q}{\partial q_i} = 1.

Here, FOC becomes:

∂∂qi[P(Q)⋅qi−Ci(qi)]=P(Q)+P′(Q)⋅qi−Ci′(qi)=0\frac{\partial}{\partial q_i} \big[ P(Q) \cdot q_i - C_i(q_i) \big] = P(Q) + P'(Q) \cdot q_i - C_i'(q_i) = 0

For linear demand, P′(Q)=−bP'(Q) = -b, so:

P(Q)−b⋅qi=Ci′(qi)(2)P(Q) - b \cdot q_i = C_i'(q_i) \tag{2}

Comparing with the competitive FOC (1)(1):

P(Q)⏟price-taking⟶P(Q)−b⋅qi⏟Cournot\underbrace{P(Q)}_{\text{price-taking}} \quad \longrightarrow \quad \underbrace{P(Q) - b \cdot q_i}_{\text{Cournot}}

The term b⋅qib \cdot q_i is the Cournot markup: the reduction in marginal revenue below price, caused by the price-depressing effect of the generator's own output. A larger generator (higher qiq_i) or a steeper demand curve (higher bb) produces a bigger markup — and more incentive to withhold output.

Generalisation via conjectural variations (CV)

The Cournot model is a special case of conjectural variations. Define generator ii's CV parameter cvicv_i as:

cvi=1+∂Q−i∂qicv_i = 1 + \frac{\partial Q_{-i}}{\partial q_i}

This captures the generator's belief about how total market output responds to its own dispatch change. When cvi=0cv_i = 0, the generator is a price-taker — it believes its output has no effect on the price, recovering the standard competitive dispatch. For 0<cvi<10 < cv_i < 1, the generator has partial strategic awareness. At cvi=1cv_i = 1, we get the classic Cournot-Nash assumption — rivals hold output fixed.

The generalised FOC becomes:

P(Q)−b⋅cvi⋅qi=Ci′(qi)(3)P(Q) - b \cdot cv_i \cdot q_i = C_i'(q_i) \tag{3}

When cvi=0cv_i = 0, this reduces to the competitive FOC (1)(1). When cvi=1cv_i = 1, it is the standard Cournot FOC (2)(2). The linopy example linked above implements this as well, showing how varying cvicv_i from 0 to 1 traces a continuum of equilibria between perfect competition and Cournot.

From FOC to fictitious objective function

Derivation

The competitive FOC is:

P(Q)−Ci′(qi)=0P(Q) - C_i'(q_i) = 0

The Cournot FOC is:

P(Q)−b⋅cvi⋅qi−Ci′(qi)=0P(Q) - b \cdot cv_i \cdot q_i - C_i'(q_i) = 0

The gap between them is the term b⋅cvi⋅qib \cdot cv_i \cdot q_i. We need a function Mi(qi)M_i(q_i) to subtract from the welfare objective such that:

∂Mi∂qi=b⋅cvi⋅qi\frac{\partial M_i}{\partial q_i} = b \cdot cv_i \cdot q_i

Integrating:

Mi(qi)=b⋅cvi2⋅qi2(4)\boxed{M_i(q_i) = \frac{b \cdot cv_i}{2} \cdot q_i^2} \tag{4}

This term can be called the Cournot markup -- a quadratic penalty on each strategic generator's dispatch.

The modified optimisation problem

Adding the markup to the welfare objective:

max⁡{qi}  a⋅Q−b2⋅Q2−∑i=1NCi(qi)⏟standard least-cost dispatch−∑i=1Nb⋅cvi2⋅qi2⏟Cournot markup(W’)\max_{\{q_i\}} \; \underbrace{a \cdot Q - \frac{b}{2} \cdot Q^2 - \sum_{i=1}^{N} C_i(q_i)}_{\text{standard least-cost dispatch}} - \underbrace{\sum_{i=1}^{N} \frac{b \cdot cv_i}{2} \cdot q_i^2}_{\text{Cournot markup}} \tag{W'}

So if we differentiate (W′)(W') with respect to qiq_i:

∂W′∂qi=a−b⋅Q⏟=P(Q)−Ci′(qi)−b⋅cvi⋅qi=0\frac{\partial W'}{\partial q_i} = \underbrace{a - b \cdot Q}_{= P(Q)} - C_i'(q_i) - b \cdot cv_i \cdot q_i = 0

which is exactly the Cournot FOC (3)(3).

This is "Problem B" in the code below, where the markup is appended to the PyPSA model's objective after create_model().

Equivalent minimisation form (cost perspective)

Negating, the cost-minimisation form is:

min⁡{qi}  ∑i=1NCi(qi)+∑i=1Nb⋅cvi2⋅qi2−a⋅Q+b2⋅Q2\min_{\{q_i\}} \; \sum_{i=1}^{N} C_i(q_i) + \sum_{i=1}^{N} \frac{b \cdot cv_i}{2} \cdot q_i^2 - a \cdot Q + \frac{b}{2} \cdot Q^2

The markup acts as an additional quadratic cost on each strategic generator. It raises the effective marginal cost from the true production cost to a "strategic" cost:

MCieff(qi)=Ci′(qi)⏟true MC+b⋅cvi⋅qi⏟strategic withholdingMC_i^{\text{eff}}(q_i) = \underbrace{C_i'(q_i)}_{\text{true MC}} + \underbrace{b \cdot cv_i \cdot q_i}_{\text{strategic withholding}}

In the code example, with Ci′(q)=1+qC_i'(q) = 1 + q, b=4b = 4, cv=1cv = 1:

MCieff(qi)=(1+qi)+4⋅qi=1+5⋅qiMC_i^{\text{eff}}(q_i) = (1 + q_i) + 4 \cdot q_i = 1 + 5 \cdot q_i

The effective marginal cost curve is five times steeper, causing the generator to produce less and the market price to rise.


PyPSA example: two gas producers, one electricity market

Now let's see this in action. We build a two-bus network where oligopolistic gas producers drive up electricity costs.

In [2]:

Copied! diagram

ipynb
import pandas as pd

import pandas as pd

In [3]:

Copied! diagram

ipynb
# Cost parameters
DEMAND_INTERCEPT = 30  # a in P(d) = a - b*d  [EUR/MWh]
DEMAND_SLOPE = 4  # b in P(d) = a - b*d  [EUR/MWh per MW]
LINEAR_COST = 1  # linear cost coefficient  [EUR/MWh]
QUADRATIC_COST = 0.5  # quadratic cost coefficient  [EUR/MWh per MW]

# Capacities and demands
SOLAR_CAPACITY = 3.0  # [MW] installed solar capacity
SOLAR_CF = [0.8, 0.5, 0.1]  # capacity factors per snapshot
GAS_PLANT_CAPACITY = 8.0  # [MW] gas backup plant capacity
GAS_PRODUCER_CAPACITY = 5.0  # [MW] each gas producer's capacity
DEMAND_MAX = 10.0  # [MW] maximum demand quantity

Cost parameters

DEMAND_INTERCEPT = 30 # a in P(d) = a - b*d [EUR/MWh] DEMAND_SLOPE = 4 # b in P(d) = a - b*d [EUR/MWh per MW] LINEAR_COST = 1 # linear cost coefficient [EUR/MWh] QUADRATIC_COST = 0.5 # quadratic cost coefficient [EUR/MWh per MW]

Capacities and demands

SOLAR_CAPACITY = 3.0 # [MW] installed solar capacity SOLAR_CF = [0.8, 0.5, 0.1] # capacity factors per snapshot GAS_PLANT_CAPACITY = 8.0 # [MW] gas backup plant capacity GAS_PRODUCER_CAPACITY = 5.0 # [MW] each gas producer's capacity DEMAND_MAX = 10.0 # [MW] maximum demand quantity

In [4]:

Copied! diagram

ipynb
def create_network():
    """Create the two-bus electricity + gas network.

    The network has 3 snapshots with decreasing solar output,
    creating increasing residual demand for gas backup.
    """
    n = pypsa.Network()
    n.set_snapshots(range(3))

    n.add("Bus", "electricity")
    n.add("Bus", "gas")

    # --- Electricity market ---

    # Solar: zero-cost renewable with time-varying capacity factor
    n.add(
        "Generator",
        "solar",
        bus="electricity",
        p_nom=SOLAR_CAPACITY,
        marginal_cost=0,
        p_max_pu=SOLAR_CF,
    )

    # Elastic demand: inverse demand curve P(d) = 30 - 4*d
    # Modelled as a sign=-1 generator ("demand bid"):
    #   Objective contribution: (-30)*d + 2*d^2
    #   FOC: -30 + 4*d = -lambda  (lambda = shadow price on bus)
    #   Hence: lambda = 30 - 4*d = P(d)
    n.add(
        "Generator",
        "elastic_demand",
        bus="electricity",
        sign=-1,
        p_nom=DEMAND_MAX,
        marginal_cost=-DEMAND_INTERCEPT,
        marginal_cost_quadratic=DEMAND_SLOPE / 2,
    )

    # --- Gas market ---

    # Two gas producers with identical convex cost C(q) = q + 0.5*q^2
    for i in [1, 2]:
        n.add(
            "Generator",
            f"gas_producer_{i}",
            bus="gas",
            p_nom=GAS_PRODUCER_CAPACITY,
            marginal_cost=LINEAR_COST,
            marginal_cost_quadratic=QUADRATIC_COST,
        )

    # --- Gas-to-electricity link (gas backup plant) ---
    # Converts gas to electricity 1:1 for simplicity.
    # The gas bus shadow price becomes the fuel cost of gas-fired power.
    n.add(
        "Link",
        "gas_plant",
        bus0="gas",
        bus1="electricity",
        p_nom=GAS_PLANT_CAPACITY,
        marginal_cost=0,
        efficiency=1.0,
    )

    return n

def create_network(): """Create the two-bus electricity + gas network. The network has 3 snapshots with decreasing solar output, creating increasing residual demand for gas backup. """ n = pypsa.Network() n.set_snapshots(range(3)) n.add("Bus", "electricity") n.add("Bus", "gas")

--- Electricity market ---

Solar: zero-cost renewable with time-varying capacity factor

n.add( "Generator", "solar", bus="electricity", p_nom=SOLAR_CAPACITY, marginal_cost=0, p_max_pu=SOLAR_CF, )

Elastic demand: inverse demand curve P(d) = 30 - 4*d

Modelled as a sign=-1 generator ("demand bid"):

Objective contribution: (-30)*d + 2*d^2

FOC: -30 + 4*d = -lambda (lambda = shadow price on bus)

Hence: lambda = 30 - 4*d = P(d)

n.add( "Generator", "elastic_demand", bus="electricity", sign=-1, p_nom=DEMAND_MAX, marginal_cost=-DEMAND_INTERCEPT, marginal_cost_quadratic=DEMAND_SLOPE / 2, )

--- Gas market ---

Two gas producers with identical convex cost C(q) = q + 0.5*q^2

for i in [1, 2]: n.add( "Generator", f"gas_producer_{i}", bus="gas", p_nom=GAS_PRODUCER_CAPACITY, marginal_cost=LINEAR_COST, marginal_cost_quadratic=QUADRATIC_COST, )

Converts gas to electricity 1:1 for simplicity.

The gas bus shadow price becomes the fuel cost of gas-fired power.

n.add( "Link", "gas_plant", bus0="gas", bus1="electricity", p_nom=GAS_PLANT_CAPACITY, marginal_cost=0, efficiency=1.0, ) return n

In [5]:

Copied! diagram

ipynb
# Create the network
n = create_network()

Create the network

n = create_network()

text
/tmp/ipykernel_3888/573161955.py:7: 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()

Problem A — Perfect competition (cv=0cv = 0)

Note that under convexity & price-taking assumptions, cost minimisation yields the competitive equilibrium (and thus a social welfare maximisation).

In [6]:

Copied! diagram

ipynb
n_a = create_network()
m_a = n_a.optimize.create_model()

# investigate the model structure
print(m_a)

n_a = create_network() m_a = n_a.optimize.create_model()

investigate the model structure

print(m_a)

text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['electricity', 'gas'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following links have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['gas_plant'], dtype='object', name='name')
text
/tmp/ipykernel_3888/1751098940.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.
  m_a = n_a.optimize.create_model()
text
Linopy QP model
===============

Variables:
----------
 * Generator-p (snapshot, name)
 * Link-p (snapshot, name)

Expressions:
------------
<empty>

Constraints:
------------
 * Generator-fix-p-lower (snapshot, name)
 * Generator-fix-p-upper (snapshot, name)
 * Link-fix-p-lower (snapshot, name)
 * Link-fix-p-upper (snapshot, name)
 * Bus-nodal_balance (snapshot, name)

Status:
-------
initialized

In [7]:

Copied! diagram

ipynb
# Problem A is the PyPSA unmodified cost min model
status_a, cond_a = n_a.optimize.solve_model(solver_name="highs", output_flag=False)

print(f"\n{'=' * 60}")
print("  Problem A: Perfect Competition (cv = 0)")
print(f"{'=' * 60}")
print(f"  Status: {status_a} | {cond_a}")
print(f"  Objective: {n_a.objective:.2f}")

Problem A is the PyPSA unmodified cost min model

status_a, cond_a = n_a.optimize.solve_model(solver_name="highs", output_flag=False) print(f"\n{'=' * 60}") print(" Problem A: Perfect Competition (cv = 0)") print(f"{'=' * 60}") print(f" Status: {status_a} | {cond_a}") print(f" Objective: {n_a.objective:.2f}")

text
INFO:linopy.model: Solve problem using Highs solver
text
INFO:linopy.model:Solver options:
 - output_flag: False
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.04s
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 15 primals, 36 duals
Objective: -2.96e+02
Solver: highs
Runtime: 0.00s
MIP gap: inf
Dual bound: 0.00e+00
Solver model: available
Solver message: Optimal
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 were not assigned to the network.
text
============================================================
  Problem A: Perfect Competition (cv = 0)
============================================================
  Status: ok | optimal
  Objective: -296.27

Problem B — Cournot-Nash competition (cv=1cv = 1)

Each gas producer ii internalises its impact on the market price. From the Cournot FOC:

−P+b⋅cv⋅qi+MC(qi)=0⇒MCeff=(1+qi)+4⋅qi=1+5⋅qi-P + b \cdot cv \cdot q_i + MC(q_i) = 0 \quad \Rightarrow \quad MC^{\text{eff}} = (1 + q_i) + 4 \cdot q_i = 1 + 5 \cdot q_i

To obtain this FOC from a minimisation problem, we add the markup term (b⋅cv/2)⋅qi2(b \cdot cv / 2) \cdot q_i^2 to each producer's objective in the linopy model (here: PyPSA objective function).

In [8]:

Copied! diagram

ipynb
n_b = create_network()
m_b = n_b.optimize.create_model()

# Access gas producer dispatch variables from the linopy model
q1 = m_b["Generator-p"].sel(name="gas_producer_1")
q2 = m_b["Generator-p"].sel(name="gas_producer_2")

# Cournot game parameters
cv = 1  # conjectural variation: 1 = Cournot (best-response)
b = DEMAND_SLOPE  # inverse demand slope = 4

# Cournot markup: (b*cv/2) * q_i^2  for each producer, each snapshot
# This effectively raises each producer's marginal cost from (1+q) to (1+5q)
cournot_markup = (b * cv / 2) * (q1 * q1 + q2 * q2)

# Append markup to the PyPSA model's objective
m_b.objective = m_b.objective.expression + cournot_markup.sum()

# Solve
status_b, cond_b = n_b.optimize.solve_model(solver_name="highs", output_flag=False)

print(f"\n{'=' * 60}")
print("  Problem B: Cournot-Nash Competition (cv = 1)")
print(f"{'=' * 60}")
print(f"  Status: {status_b} | {cond_b}")
print(f"  Objective: {n_b.objective:.2f}")

n_b = create_network() m_b = n_b.optimize.create_model()

Access gas producer dispatch variables from the linopy model

q1 = m_b["Generator-p"].sel(name="gas_producer_1") q2 = m_b["Generator-p"].sel(name="gas_producer_2")

Cournot game parameters

cv = 1 # conjectural variation: 1 = Cournot (best-response) b = DEMAND_SLOPE # inverse demand slope = 4

Cournot markup: (b*cv/2) * q_i^2 for each producer, each snapshot

This effectively raises each producer's marginal cost from (1+q) to (1+5q)

cournot_markup = (b * cv / 2) * (q1 * q1 + q2 * q2)

Append markup to the PyPSA model's objective

m_b.objective = m_b.objective.expression + cournot_markup.sum()

Solve

status_b, cond_b = n_b.optimize.solve_model(solver_name="highs", output_flag=False) print(f"\n{'=' * 60}") print(" Problem B: Cournot-Nash Competition (cv = 1)") print(f"{'=' * 60}") print(f" Status: {status_b} | {cond_b}") print(f" Objective: {n_b.objective:.2f}")

text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['electricity', 'gas'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following links have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['gas_plant'], dtype='object', name='name')
text
/tmp/ipykernel_3888/124132865.py:14: LinopySemanticsWarning: Auxiliary coordinate 'name' was conflicting across operands and silently dropped by legacy (xarray's default). Under v1 this raises ValueError.
  Values:    left='gas_producer_1', right='gas_producer_2'
  Resolve:   `.drop_vars('name')`
             `.assign_coords(name=...)` to relabel one side
             or `.isel(..., drop=True)` if a scalar isel introduced it.
  Opt in:    linopy.options['semantics'] = 'v1'
  Silence:   warnings.filterwarnings('ignore', category=LinopySemanticsWarning)
  cournot_markup = (b * cv / 2) * (q1 * q1 + q2 * q2)
INFO:linopy.model: Solve problem using Highs solver
text
INFO:linopy.model:Solver options:
 - output_flag: False
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.03s
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 15 primals, 36 duals
Objective: -2.39e+02
Solver: highs
Runtime: 0.00s
MIP gap: inf
Dual bound: 0.00e+00
Solver model: available
Solver message: Optimal
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 were not assigned to the network.
text
============================================================
  Problem B: Cournot-Nash Competition (cv = 1)
============================================================
  Status: ok | optimal
  Objective: -238.89

Economic analysis & welfare decomposition

Now the interesting part — how does market power affect welfare? We decompose the consumer surplus loss into a revenue transfer to producers and deadweight welfare loss.

First, let's collect results:

In [9]:

Copied! diagram

ipynb
def production_cost(q):
    """True production cost: C(q) = q + 0.5*q^2"""
    return LINEAR_COST * q + QUADRATIC_COST * q**2


def analyse_economics(n, label):
    """Compute economic metrics for a solved network."""
    q1 = n.generators_t.p["gas_producer_1"].values
    q2 = n.generators_t.p["gas_producer_2"].values
    p_gas = n.buses_t.marginal_price["gas"].values
    p_elec = n.buses_t.marginal_price["electricity"].values
    demand = n.generators_t.p["elastic_demand"].values

    # Production costs
    cost1 = production_cost(q1)
    cost2 = production_cost(q2)

    # Revenue = price * quantity
    rev1 = p_gas * q1
    rev2 = p_gas * q2

    # Profit = revenue - cost
    profit1 = rev1 - cost1
    profit2 = rev2 - cost2

    # Consumer expenditure (what electricity consumers pay)
    consumer_exp = p_elec * demand

    # Consumer surplus: integral under demand curve minus expenditure
    # integral_0^d P(x)dx = a*d - (b/2)*d^2
    consumer_surplus = (
        DEMAND_INTERCEPT * demand - (DEMAND_SLOPE / 2) * demand**2 - consumer_exp
    )

    return {
        "label": label,
        "q1": q1,
        "q2": q2,
        "demand": demand,
        "p_gas": p_gas,
        "p_elec": p_elec,
        "cost1": cost1,
        "cost2": cost2,
        "profit1": profit1,
        "profit2": profit2,
        "total_producer_profit": (profit1 + profit2).sum(),
        "total_production_cost": (cost1 + cost2).sum(),
        "total_consumer_expenditure": consumer_exp.sum(),
        "total_consumer_surplus": consumer_surplus.sum(),
    }


econ_a = analyse_economics(n_a, "A: Competitive")
econ_b = analyse_economics(n_b, "B: Cournot")

print(f"{'=' * 70}")
print("  ECONOMIC ANALYSIS (Totals)")
print(f"{'=' * 70}")

for econ in [econ_a, econ_b]:
    print(f"\n  --- {econ['label']} ---")
    print(f"    Total gas production cost:    {econ['total_production_cost']:.2f}")
    print(f"    Total producer profit:        {econ['total_producer_profit']:.2f}")
    print(f"    Total consumer expenditure:   {econ['total_consumer_expenditure']:.2f}")
    print(f"    Total consumer surplus:       {econ['total_consumer_surplus']:.2f}")

def production_cost(q): """True production cost: C(q) = q + 0.5*q^2""" return LINEAR_COST * q + QUADRATIC_COST * q**2 def analyse_economics(n, label): """Compute economic metrics for a solved network.""" q1 = n.generators_t.p["gas_producer_1"].values q2 = n.generators_t.p["gas_producer_2"].values p_gas = n.buses_t.marginal_price["gas"].values p_elec = n.buses_t.marginal_price["electricity"].values demand = n.generators_t.p["elastic_demand"].values

Production costs

cost1 = production_cost(q1) cost2 = production_cost(q2)

Revenue = price * quantity

rev1 = p_gas * q1 rev2 = p_gas * q2

Profit = revenue - cost

profit1 = rev1 - cost1 profit2 = rev2 - cost2

Consumer expenditure (what electricity consumers pay)

consumer_exp = p_elec * demand

Consumer surplus: integral under demand curve minus expenditure

integral_0^d P(x)dx = a*d - (b/2)*d^2

consumer_surplus = ( DEMAND_INTERCEPT * demand - (DEMAND_SLOPE / 2) * demand**2 - consumer_exp ) return { "label": label, "q1": q1, "q2": q2, "demand": demand, "p_gas": p_gas, "p_elec": p_elec, "cost1": cost1, "cost2": cost2, "profit1": profit1, "profit2": profit2, "total_producer_profit": (profit1 + profit2).sum(), "total_production_cost": (cost1 + cost2).sum(), "total_consumer_expenditure": consumer_exp.sum(), "total_consumer_surplus": consumer_surplus.sum(), } econ_a = analyse_economics(n_a, "A: Competitive") econ_b = analyse_economics(n_b, "B: Cournot") print(f"{'=' * 70}") print(" ECONOMIC ANALYSIS (Totals)") print(f"{'=' * 70}") for econ in [econ_a, econ_b]: print(f"\n --- {econ['label']} ---") print(f" Total gas production cost: {econ['total_production_cost']:.2f}") print(f" Total producer profit: {econ['total_producer_profit']:.2f}") print(f" Total consumer expenditure: {econ['total_consumer_expenditure']:.2f}") print(f" Total consumer surplus: {econ['total_consumer_surplus']:.2f}")

text
======================================================================
  ECONOMIC ANALYSIS (Totals)
======================================================================

  --- A: Competitive ---
    Total gas production cost:    36.32
    Total producer profit:        20.72
    Total consumer expenditure:   71.17
    Total consumer surplus:       261.41

  --- B: Cournot ---
    Total gas production cost:    20.73
    Total producer profit:        89.37
    Total consumer expenditure:   148.69
    Total consumer surplus:       150.66

In [10]:

Copied! diagram

ipynb
# --- Decomposition of welfare loss ---

# Welfare = Consumer surplus + Producer surplus (profit)
welfare_a = econ_a["total_consumer_surplus"] + econ_a["total_producer_profit"]
welfare_b = econ_b["total_consumer_surplus"] + econ_b["total_producer_profit"]

welfare_loss = welfare_a - welfare_b  # positive = welfare decreased
revenue_increase = econ_b["total_producer_profit"] - econ_a["total_producer_profit"]
consumer_loss = econ_a["total_consumer_surplus"] - econ_b["total_consumer_surplus"]
deadweight_loss = welfare_loss

# Cost increase to electricity system = consumer expenditure increase
cost_increase = (
    econ_b["total_consumer_expenditure"] - econ_a["total_consumer_expenditure"]
)

print(f"\n  Competitive total welfare:      {welfare_a:.2f}")
print(f"  Cournot total welfare:          {welfare_b:.2f}")
print(f"  Welfare loss (DWL):             {deadweight_loss:.2f}")

print(f"\n  Producer profit (competitive):  {econ_a['total_producer_profit']:.2f}")
print(f"  Producer profit (Cournot):      {econ_b['total_producer_profit']:.2f}")
print(f"  Oligopolist revenue increase:   {revenue_increase:.2f}")

print(f"\n  Consumer surplus (competitive): {econ_a['total_consumer_surplus']:.2f}")
print(f"  Consumer surplus (Cournot):     {econ_b['total_consumer_surplus']:.2f}")
print(f"  Consumer surplus loss:          {consumer_loss:.2f}")

print(f"\n  Consumer expenditure increase:  {cost_increase:.2f}")

print("\n  Decomposition of consumer surplus loss:")
print(f"    = Revenue transfer to producers: {revenue_increase:.2f}")
print(f"    + Deadweight loss:               {deadweight_loss:.2f}")
print(f"    = Total consumer loss:           {revenue_increase + deadweight_loss:.2f}")
print(f"    (actual consumer loss:           {consumer_loss:.2f})")

--- Decomposition of welfare loss ---

Welfare = Consumer surplus + Producer surplus (profit)

welfare_a = econ_a["total_consumer_surplus"] + econ_a["total_producer_profit"] welfare_b = econ_b["total_consumer_surplus"] + econ_b["total_producer_profit"] welfare_loss = welfare_a - welfare_b # positive = welfare decreased revenue_increase = econ_b["total_producer_profit"] - econ_a["total_producer_profit"] consumer_loss = econ_a["total_consumer_surplus"] - econ_b["total_consumer_surplus"] deadweight_loss = welfare_loss

Cost increase to electricity system = consumer expenditure increase

cost_increase = ( econ_b["total_consumer_expenditure"] - econ_a["total_consumer_expenditure"] ) print(f"\n Competitive total welfare: {welfare_a:.2f}") print(f" Cournot total welfare: {welfare_b:.2f}") print(f" Welfare loss (DWL): {deadweight_loss:.2f}") print(f"\n Producer profit (competitive): {econ_a['total_producer_profit']:.2f}") print(f" Producer profit (Cournot): {econ_b['total_producer_profit']:.2f}") print(f" Oligopolist revenue increase: {revenue_increase:.2f}") print(f"\n Consumer surplus (competitive): {econ_a['total_consumer_surplus']:.2f}") print(f" Consumer surplus (Cournot): {econ_b['total_consumer_surplus']:.2f}") print(f" Consumer surplus loss: {consumer_loss:.2f}") print(f"\n Consumer expenditure increase: {cost_increase:.2f}") print("\n Decomposition of consumer surplus loss:") print(f" = Revenue transfer to producers: {revenue_increase:.2f}") print(f" + Deadweight loss: {deadweight_loss:.2f}") print(f" = Total consumer loss: {revenue_increase + deadweight_loss:.2f}") print(f" (actual consumer loss: {consumer_loss:.2f})")

text
  Competitive total welfare:      282.13
  Cournot total welfare:          240.03
  Welfare loss (DWL):             42.10

  Producer profit (competitive):  20.72
  Producer profit (Cournot):      89.37
  Oligopolist revenue increase:   68.65

  Consumer surplus (competitive): 261.41
  Consumer surplus (Cournot):     150.66
  Consumer surplus loss:          110.76

  Consumer expenditure increase:  77.52

  Decomposition of consumer surplus loss:
    = Revenue transfer to producers: 68.65
    + Deadweight loss:               42.10
    = Total consumer loss:           110.76
    (actual consumer loss:           110.76)

In [11]:

Copied! diagram

ipynb
# --- Side-by-side summary table ---

summary = pd.DataFrame(
    {
        "A: Competitive": {
            "Gas price (avg)": econ_a["p_gas"].mean(),
            "Elec price (avg)": econ_a["p_elec"].mean(),
            "Gas output (total)": (econ_a["q1"] + econ_a["q2"]).sum(),
            "Demand (total)": econ_a["demand"].sum(),
            "Production cost": econ_a["total_production_cost"],
            "Consumer expenditure": econ_a["total_consumer_expenditure"],
            "Producer profit": econ_a["total_producer_profit"],
            "Consumer surplus": econ_a["total_consumer_surplus"],
            "Total welfare": welfare_a,
        },
        "B: Cournot": {
            "Gas price (avg)": econ_b["p_gas"].mean(),
            "Elec price (avg)": econ_b["p_elec"].mean(),
            "Gas output (total)": (econ_b["q1"] + econ_b["q2"]).sum(),
            "Demand (total)": econ_b["demand"].sum(),
            "Production cost": econ_b["total_production_cost"],
            "Consumer expenditure": econ_b["total_consumer_expenditure"],
            "Producer profit": econ_b["total_producer_profit"],
            "Consumer surplus": econ_b["total_consumer_surplus"],
            "Total welfare": welfare_b,
        },
    }
)
summary["Delta (B-A)"] = summary["B: Cournot"] - summary["A: Competitive"]
summary.style.format("{:.2f}")

--- Side-by-side summary table ---

summary = pd.DataFrame( { "A: Competitive": { "Gas price (avg)": econ_a["p_gas"].mean(), "Elec price (avg)": econ_a["p_elec"].mean(), "Gas output (total)": (econ_a["q1"] + econ_a["q2"]).sum(), "Demand (total)": econ_a["demand"].sum(), "Production cost": econ_a["total_production_cost"], "Consumer expenditure": econ_a["total_consumer_expenditure"], "Producer profit": econ_a["total_producer_profit"], "Consumer surplus": econ_a["total_consumer_surplus"], "Total welfare": welfare_a, }, "B: Cournot": { "Gas price (avg)": econ_b["p_gas"].mean(), "Elec price (avg)": econ_b["p_elec"].mean(), "Gas output (total)": (econ_b["q1"] + econ_b["q2"]).sum(), "Demand (total)": econ_b["demand"].sum(), "Production cost": econ_b["total_production_cost"], "Consumer expenditure": econ_b["total_consumer_expenditure"], "Producer profit": econ_b["total_producer_profit"], "Consumer surplus": econ_b["total_consumer_surplus"], "Total welfare": welfare_b, }, } ) summary["Delta (B-A)"] = summary["B: Cournot"] - summary["A: Competitive"] summary.style.format("{:.2f}")

Out[11]:

A: CompetitiveB: CournotDelta (B-A)
Gas price (avg)3.6010.006.40
Elec price (avg)3.6010.006.40
Gas output (total)15.6010.80-4.80
Demand (total)19.8015.00-4.80
Production cost36.3220.73-15.59
Consumer expenditure71.17148.6977.52
Producer profit20.7289.3768.65
Consumer surplus261.41150.66-110.76
Total welfare282.13240.03-42.10

A note on calibrating demand parameters

In energy system models, demand is often modelled as an inelastic load (in PyPSA: Load component with p_set). NB

If demand is perfectly inelastic (b→∞b \to \infty, Q=QˉQ = \bar{Q} for all prices), the Cournot markup b⋅cvi⋅qi→∞b \cdot cv_i \cdot q_i \to \infty. This is economically correct: without any demand response, a generator at margin can charge any price. NB this phenomenon is a reason for various modelling artifacts around price formation that is illustrated in this paper.

The fictitious objective approach to modelling imperfect competition relies on the markup term, which depends on the demand slope bb. Recall that Slade's 1994 paper proves the existence of a fictitious objective for linear demand.

In practice, demand has some finite price elasticity ε<0\varepsilon < 0. The point elasticity of linear demand at an observed operating point (Qˉ,Pˉ)(\bar{Q}, \bar{P}) is:

ε=−1b⋅PˉQˉ\varepsilon = -\frac{1}{b} \cdot \frac{\bar{P}}{\bar{Q}}

Solving for bb and aa:

b=PˉQˉ⋅∣ε∣(5)b = \frac{\bar{P}}{\bar{Q} \cdot |\varepsilon|} \tag{5}

a=Pˉ(1+1∣ε∣)(6)a = \bar{P} \left(1 + \frac{1}{|\varepsilon|}\right) \tag{6}

These are used as marginal_cost = -a and marginal_cost_quadratic = b / 2 on an elastic demand generator (with sign=-1), replacing the fixed Load.

Example. At Pˉ=50\bar{P} = 50 EUR/MWh, Qˉ=5\bar{Q} = 5 MW, ε=−0.1\varepsilon = -0.1:

b=505×0.1=100,a=50×(1+10)=550b = \frac{50}{5 \times 0.1} = 100, \qquad a = 50 \times (1 + 10) = 550

PS There are various functional forms for demand elasticity, which is also illustrated in the Price formation without fuel costs (..) paper.

diagram 2026-10-08

diagram 2026-02-27