Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Formulating the Optimal Power Flow Problem Using Pyomo, Gurobipy, and AMPL

The optimal power flow (OPF) problem is vital to the stable and cost-effective operation of the electrical grid. See here for a full derivation and formulation using the bus injection model, and here for the approach we’ll be taking to incorporate generator offers in the electricity market.

Like any other optimization problem, OPF must be formulated in a standard format in order to interface with an optimization algorithm (a solver). This allows the decision variables, the constraints, the objective, etc. to be supplied to the solver, and the final solution to be extracted. Optimization modeling interfaces like Pyomo, Gurobipy, and AMPL are designed to make this easy, speaking the same language—sets, parameters, variables, and so on—that’s common when formulating optimization problems.

Pyomo and Gurobipy are implemented as Python libraries—meaning that, although they have some overhead, the formulation and solving of optimization problems can easily be integrated into larger programs. AMPL is a leaner language with more convenient syntax tailor-made for formulating optimization problems, but is more cumbersome to use with programming languages like Python. Gurobi, the developer of Gurobipy, provides similar libraries for other programming languages.

Pyomo and AMPL are solver-agnostic; they can be used with a variety of free and commercial solvers. Gurobipy, on the other hand, is exclusively for use with Gurobi’s proprietary solver.

Pyomo

from math import pi

import pyomo.environ as pyo

model = pyo.AbstractModel()


# Sets


model.load_bus_index = pyo.Set()
model.generator_bus_index = pyo.Set()
model.slack_bus_index = pyo.Set()
model.bus_index = (
    model.load_bus_index | model.generator_bus_index | model.slack_bus_index
)
model.nonzero_pq_pair_index = pyo.Set(
    doc="Index of all nonzero (price, quantity) pairs, concatenated from all generator offers"
)


# Parameters


model.pq_pair_to_bus = pyo.Param(
    model.nonzero_pq_pair_index,
    within=(model.generator_bus_index | model.slack_bus_index),
    doc="Map from a (price, quantity) pair to a generator or slack bus",
)
model.prices = pyo.Param(
    model.nonzero_pq_pair_index,
    doc="Flat list of nonzero prices per MWh concatenated from all generators' (price, quantity) pairs",
)
model.quantity_steps = pyo.Param(
    model.nonzero_pq_pair_index,
    within=pyo.PositiveReals,
    doc="Flat list of quantity steps concatenated from all generators' (price, quantity) pairs",
)

model.conductances = pyo.Param(
    model.bus_index,
    model.bus_index,
    within=pyo.Reals,
    doc="Real component of the admittance matrix",
)
model.susceptances = pyo.Param(
    model.bus_index,
    model.bus_index,
    within=pyo.Reals,
    doc="Imaginary component of the admittance matrix",
)

model.load_real_powers = pyo.Param(model.load_bus_index, within=pyo.Reals)
model.load_reactive_powers = pyo.Param(model.load_bus_index, within=pyo.Reals)

model.fixed_voltage_magnitudes = pyo.Param(
    model.generator_bus_index | model.slack_bus_index
)

model.min_voltage_magnitudes = pyo.Param(model.bus_index)
model.max_voltage_magnitudes = pyo.Param(model.bus_index)

model.max_apparent_powers = pyo.Param(
    model.bus_index, model.bus_index, within=pyo.NonNegativeReals
)

# Variables


def real_power_bounds(m: pyo.Model, pq_pair_i: int):
    return (0, m.quantity_steps[pq_pair_i])


model.generator_real_powers = pyo.Var(
    model.nonzero_pq_pair_index,
    within=pyo.NonNegativeReals,
    bounds=real_power_bounds,
    doc="Real power dispatch for each generator (price, quantity) pair",
)

model.reactive_powers = pyo.Var(model.bus_index, within=pyo.Reals)


def voltage_magnitude_bounds(m: pyo.Model, bus_i: int):
    return (m.min_voltage_magnitudes[bus_i], m.max_voltage_magnitudes[bus_i])


model.voltage_magnitudes = pyo.Var(model.bus_index, bounds=voltage_magnitude_bounds)
model.voltage_angles = pyo.Var(model.bus_index, within=pyo.Reals, bounds=(-pi, pi))


# Objective: Minimize system cost


model.cost = pyo.Objective(
    expr=pyo.sum_product(model.prices, model.generator_real_powers)
)


# Constraints

## Power Flow Equations (Bus Injection Model)


def real_power_flow_rule(m: pyo.Model, bus_i: int):
    injections = [
        m.generator_real_powers[pq_pair_i]
        for pq_pair_i in m.nonzero_pq_pair_index
        if m.pq_pair_to_bus[pq_pair_i] == bus_i
    ]
    if bus_i in m.load_bus_index:
        injections.append(m.load_real_powers[bus_i])
    withdrawals = [
        m.voltage_magnitudes[bus_i]
        * m.voltage_magnitudes[bus_k]
        * (
            m.conductances[bus_i, bus_k]
            * pyo.cos(m.voltage_angles[bus_i] - m.voltage_angles[bus_k])
            + m.susceptances[bus_i, bus_k]
            * pyo.sin(m.voltage_angles[bus_i] - m.voltage_angles[bus_k])
        )
        for bus_k in m.bus_index
    ]
    return sum(injections) == sum(withdrawals)


def reactive_power_flow_rule(m: pyo.Model, bus_i: int):
    injection = m.reactive_powers[bus_i]
    withdrawals = [
        m.voltage_magnitudes[bus_i]
        * m.voltage_magnitudes[bus_k]
        * (
            m.conductances[bus_i, bus_k]
            * pyo.sin(m.voltage_angles[bus_i] - m.voltage_angles[bus_k])
            - m.susceptances[bus_i, bus_k]
            * pyo.cos(m.voltage_angles[bus_i] - m.voltage_angles[bus_k])
        )
        for bus_k in m.bus_index
    ]
    return injection == sum(withdrawals)


model.real_power_flow_constraint = pyo.Constraint(
    model.bus_index, rule=real_power_flow_rule
)
model.reactive_power_flow_constraint = pyo.Constraint(
    model.bus_index, rule=reactive_power_flow_rule
)


## Branch Loading Constraint


def branch_loading_rule(m: pyo.Model, bus_i: int, bus_k: int):
    apparent_power = (
        m.voltage_magnitudes[bus_i]
        * pyo.sqrt(
            (
                m.voltage_magnitudes[bus_i] * pyo.cos(m.voltage_angles[bus_i])
                - m.voltage_magnitudes[bus_k] * pyo.cos(m.voltage_angles[bus_k])
            )
            ** 2
            + (
                m.voltage_magnitudes[bus_i] * pyo.sin(m.voltage_angles[bus_i])
                - m.voltage_magnitudes[bus_k] * pyo.sin(m.voltage_angles[bus_k])
            )
            ** 2
        )
        * pyo.sqrt(
            m.conductances[bus_i, bus_k] ** 2 + m.susceptances[bus_i, bus_k] ** 2
        )
    )
    return apparent_power <= m.max_apparent_powers[bus_i, bus_k]


model.branch_loading_constraint = pyo.Constraint(
    model.bus_index, model.bus_index, rule=branch_loading_rule
)


## Bus Type Constraints


def load_bus_reactive_power_rule(m: pyo.Model, bus_i: int):
    return m.reactive_powers[bus_i] == m.load_reactive_powers[bus_i]


def fixed_voltage_magnitude_rule(m: pyo.Model, bus_i: int):
    return m.voltage_magnitudes[bus_i] == m.fixed_voltage_magnitudes[bus_i]


def slack_bus_voltage_angle_rule(m: pyo.Model, bus_i: int):
    return m.voltage_angles[bus_i] == 0


model.load_bus_reactive_power_constraint = pyo.Constraint(
    model.load_bus_index, rule=load_bus_reactive_power_rule
)
model.fixed_voltage_magnitude_constraint = pyo.Constraint(
    model.generator_bus_index | model.slack_bus_index, rule=fixed_voltage_magnitude_rule
)
model.slack_bus_voltage_angle_constraint = pyo.Constraint(
    model.slack_bus_index, rule=slack_bus_voltage_angle_rule
)

Resources: Mathematical Modeling · Pyomo | See also: Pyomo Network

Gurobipy

from math import inf, pi

import gurobipy as gp
from gurobipy import nlfunc

model = gp.Model("opf")

# Sets

type LoadBusIdx = int
type GeneratorBusIdx = int
type SlackBusIdx = int
type BusIdx = LoadBusIdx | GeneratorBusIdx | SlackBusIdx

load_bus_index: set[LoadBusIdx] = set()
generator_bus_index: set[GeneratorBusIdx] = set()
slack_bus_index: set[SlackBusIdx] = set()
bus_index: set[BusIdx] = load_bus_index | generator_bus_index | slack_bus_index

type PqPairIdx = int

nonzero_pq_pair_index = set[PqPairIdx]()

# Parameters

# Map from a (price, quantity) pair to a generator or slack bus:
pq_pair_to_bus: dict[PqPairIdx, BusIdx] = {}
# Flat list of nonzero prices per MWh concatenated from all generators'
# (price, quantity) pairs:
prices: dict[PqPairIdx, float] = {}
# Flat list of quantity steps concatenated from all generators' (price, quantity pairs):
quantity_steps: dict[PqPairIdx, float] = {}

# Real component of the admittance matrix:
conductances: dict[BusIdx, dict[BusIdx, float]] = {}
# Imaginary component of the admittance matrix:
susceptances: dict[BusIdx, dict[BusIdx, float]] = {}

load_real_powers: dict[LoadBusIdx, float] = {}
load_reactive_powers: dict[LoadBusIdx, float] = {}

fixed_voltage_magnitudes: dict[GeneratorBusIdx | SlackBusIdx, float] = {}

min_voltage_magnitudes: dict[BusIdx, float] = {}
max_voltage_magnitudes: dict[BusIdx, float] = {}

max_apparent_powers: dict[BusIdx, dict[BusIdx, float]] = {}

# Variables

generator_real_powers = model.addVars(nonzero_pq_pair_index, lb=0, ub=quantity_steps)
reactive_powers = model.addVars(bus_index, lb=-inf, ub=inf)
voltage_magnitudes = model.addVars(
    bus_index, lb=min_voltage_magnitudes, ub=max_voltage_magnitudes
)
voltage_angles = model.addVars(bus_index, lb=-pi, ub=pi)

# Objective: Minimize system cost

model.setObjective(
    gp.quicksum(
        prices[pq_pair_i] * generator_real_powers[pq_pair_i]
        for pq_pair_i in nonzero_pq_pair_index
    )
)

# Constraints

## Power Flow Equations (Bus Injection Model)

real_power_withdrawals = model.addVars(bus_index, lb=-inf, ub=inf)
model.addConstrs(
    gp.quicksum(
        generator_real_powers[pq_pair_i]
        for pq_pair_i in nonzero_pq_pair_index
        if pq_pair_to_bus[pq_pair_i] == bus_i
    )
    + (load_real_powers[bus_i])
    == real_power_withdrawals[bus_i]
    for bus_i in bus_index
)
model.addConstrs(
    real_power_withdrawals[bus_i]
    == gp.quicksum(
        voltage_magnitudes[bus_i]
        * voltage_magnitudes[bus_k]
        * (
            conductances[bus_i][bus_k]
            * nlfunc.cos(voltage_angles[bus_i] - voltage_angles[bus_k])
            + susceptances[bus_i][bus_k]
            * nlfunc.sin(voltage_angles[bus_i] - voltage_angles[bus_k])
        )
        for bus_k in bus_index
    )
    for bus_i in bus_index
)

model.addConstrs(
    reactive_powers[bus_i]
    == gp.quicksum(
        voltage_magnitudes[bus_i]
        * voltage_magnitudes[bus_k]
        * (
            conductances[bus_i][bus_k]
            * nlfunc.sin(voltage_angles[bus_i] - voltage_angles[bus_k])
            - susceptances[bus_i][bus_k]
            * nlfunc.cos(voltage_angles[bus_i] - voltage_angles[bus_k])
        )
        for bus_k in bus_index
    )
    for bus_i in bus_index
)

## Branch Loading Constraint

model.addConstrs(
    voltage_magnitudes[bus_i]
    * nlfunc.sqrt(
        nlfunc.square(
            voltage_magnitudes[bus_i] * nlfunc.cos(voltage_angles[bus_i])
            - voltage_magnitudes[bus_k] * nlfunc.cos(voltage_angles[bus_k])
        )
        + nlfunc.square(
            voltage_magnitudes[bus_i] * nlfunc.sin(voltage_angles[bus_i])
            - voltage_magnitudes[bus_k] * nlfunc.sin(voltage_angles[bus_k])
        )
    )
    * nlfunc.sqrt(
        nlfunc.square(conductances[bus_i][bus_k])
        + nlfunc.square(susceptances[bus_i][bus_k])
    )
    <= max_apparent_powers[bus_i, bus_k]
    for bus_k in bus_index
    for bus_i in bus_index
)

## Bus Type Constraints

model.addConstrs(
    reactive_powers[bus_i] == load_reactive_powers[bus_i] for bus_i in load_bus_index
)
model.addConstrs(
    voltage_magnitudes[bus_i] == fixed_voltage_magnitudes[bus_i]
    for bus_i in generator_bus_index | slack_bus_index
)
model.addConstrs(voltage_angles[bus_i] == 0 for bus_i in slack_bus_index)

Resources: Gurobi’s example of unit commitment

AMPL

# Sets

set LOAD_BUS_INDEX;
set GENERATOR_BUS_INDEX;
set SLACK_BUS_INDEX;
set BUS_INDEX = LOAD_BUS_INDEX union GENERATOR_BUS_INDEX union SLACK_BUS_INDEX;
# Index of all nonzero (price, quantity) pairs, concatenated from all generator offers:
set NONZERO_PQ_PAIR_INDEX;

# Parameters

param pi := acos(-1);

# Map from a (price, quantity) pair to a generator or slack bus:
param pq_pair_to_bus {pq_pair_i in NONZERO_PQ_PAIR_INDEX}
    in (GENERATOR_BUS_INDEX union SLACK_BUS_INDEX);
# Flat list of nonzero prices per MWh concatenated from all generators'
# (price, quantity) pairs:
param prices {NONZERO_PQ_PAIR_INDEX};
# Flat list of quantity steps concatenated from all generators' (price, quantity pairs):
param quantity_steps {NONZERO_PQ_PAIR_INDEX} > 0;

# Real component of the admittance matrix:
param conductances {BUS_INDEX, BUS_INDEX};
# Imaginary component of the admittance matrix:
param susceptances {BUS_INDEX, BUS_INDEX};

param load_real_powers {LOAD_BUS_INDEX};
param load_reactive_powers {LOAD_BUS_INDEX};

param fixed_voltage_magnitudes {GENERATOR_BUS_INDEX union SLACK_BUS_INDEX};

param min_voltage_magnitudes {BUS_INDEX};
param max_voltage_magnitudes {BUS_INDEX};

param max_apparent_powers {BUS_INDEX, BUS_INDEX} >= 0;

# Variables

# Real power dispatch for each generator (price, quantity) pair:
var GeneratorRealPowers {pq_pair_i in NONZERO_PQ_PAIR_INDEX}
    >= 0, <= quantity_steps[pq_pair_i];

var ReactivePowers {BUS_INDEX};

var VoltageMagnitudes {bus_i in BUS_INDEX}
    >= min_voltage_magnitudes[bus_i], <= max_voltage_magnitudes[bus_i];

var VoltageAngles {BUS_INDEX} >= -pi, <= pi;

# Objective: Minimize system cost

minimize Cost:
    sum {pq_pair_i in NONZERO_PQ_PAIR_INDEX} prices[pq_pair_i] * GeneratorRealPowers[pq_pair_i];

# Constraints

## Power Flow Equations (Bus Injection Model)

subject to RealPowerFlowConstraint {bus_i in BUS_INDEX}:
    sum {pq_pair_i in NONZERO_PQ_PAIR_INDEX: pq_pair_to_bus[pq_pair_i] == bus_i}
        GeneratorRealPowers[pq_pair_i]
    + (if bus_i in LOAD_BUS_INDEX then load_real_powers[bus_i] else 0)
    == sum {bus_k in BUS_INDEX} (
        VoltageMagnitudes[bus_i]
        * VoltageMagnitudes[bus_k]
        * (
            conductances[bus_i, bus_k]
            * cos(VoltageAngles[bus_i] - VoltageAngles[bus_k])
            + susceptances[bus_i, bus_k]
            * sin(VoltageAngles[bus_i] - VoltageAngles[bus_k])
        )
    );

subject to ReactivePowerFlowConstraint {bus_i in BUS_INDEX}:
    ReactivePowers[bus_i] == sum {bus_k in BUS_INDEX} (
        VoltageMagnitudes[bus_i]
        * VoltageMagnitudes[bus_k]
        * (
            conductances[bus_i, bus_k]
            * sin(VoltageAngles[bus_i] - VoltageAngles[bus_k])
            - susceptances[bus_i, bus_k]
            * cos(VoltageAngles[bus_i] - VoltageAngles[bus_k])
        )
    );

## Branch Loading Constraint

subject to BranchLoadingConstraint {bus_i in BUS_INDEX, bus_k in BUS_INDEX}:
    VoltageMagnitudes[bus_i] * sqrt(
        (
            VoltageMagnitudes[bus_i] * cos(VoltageAngles[bus_i])
            - VoltageMagnitudes[bus_k] * cos(VoltageAngles[bus_k])
        )^2
        + (
            VoltageMagnitudes[bus_i] * sin(VoltageAngles[bus_i])
            - VoltageMagnitudes[bus_k] * sin(VoltageAngles[bus_k])
        )^2
    ) * sqrt(
        conductances[bus_i, bus_k]^2 + susceptances[bus_i, bus_k]^2
    ) <= max_apparent_powers[bus_i, bus_k];

# Bus Type Constraints

subject to LoadBusReactivePowerConstraint {bus_i in LOAD_BUS_INDEX}:
    ReactivePowers[bus_i] == load_reactive_powers[bus_i];

subject to FixedVoltageMagnitudeConstraint {bus_i in GENERATOR_BUS_INDEX union SLACK_BUS_INDEX}:
    VoltageMagnitudes[bus_i] == fixed_voltage_magnitudes[bus_i];

subject to SlackBusVoltageAngleConstraint {bus_i in SLACK_BUS_INDEX}:
    VoltageAngles[bus_i] == 0;

Resources: AMPL introduction | AMPL expressions | AMPL’s example of unit commitment | AMPL’s example of stochastic optimization for economic dispatch

Appendix: Deriving the branch loading constraint

The branch loading constraint specifies that the apparent power flowing into any branch (denoted ikik) from either attached bus (denoted ii) cannot exceed the branch’s rated maximum:

∣Sik∣≤Sik  ⁣max|S_{ik}| \leq S_{ik}^{\:\! \text{max}}

This needs to be expressed in terms of the decision variables for the voltage magnitudes (∣Vi∣|V_i|, ∣Vk∣|V_k|) and voltage angles (δi\delta_i, δk\delta_k). The complex power SikS_{ik} is given by:

Sik=V ⁣i(V ⁣i1 ∣aik∣2(yikSh2+yik)−Vk1aik∗yik)S_{ik} = V_{\! i} \left( V_{\! i} \frac{1}{\, |a_{ik}|^2} \left( \frac{y_{ik}^\text{Sh}}{2} + y_{ik} \right) - V_k \frac{1}{a_{ik}^*} y_{ik} \right)

For simplicity at the expense of accuracy, we assume aik=1a_{ik} = 1 (no off-nominal turns ratios) and yikSh=0y_{ik}^\text{Sh} = 0 (no shunt admittances):

Sik=V ⁣i (V ⁣i−Vk)∗ yik∗S_{ik} = V_{\! i} \, (V_{\! i} - V_k)^* \, y_{ik}^*

Furthermore, because Y ⁣ik=−yikY_{\! ik} = - y_{ik} when aik=1a_{ik} = 1, where YY is the bus admittance matrix, we can rewrite SikS_{ik} as:

Sik=−V ⁣i (V ⁣i−Vk)∗ Y ⁣ik∗S_{ik} = - V_{\! i} \, (V_{\! i} - V_k)^* \, Y_{\! ik}^*

This allows us to use only the bus admittance matrix, not the separate branch-from-bus and branch-to-bus admittance matrices. Finally, the apparent power is as follows, where GG and BB are the real and imaginary parts of the bus admittance matrix.

∣Sik∣=∣V ⁣i∣ ∣V ⁣i−Vk∣ ∣Y ⁣ik∣=∣V ⁣i∣(∣V ⁣i∣cos⁡δi−∣Vk∣cos⁡δk)2+(∣V ⁣i∣sin⁡δi−∣Vk∣sin⁡δk)2Gik2+Bik2\begin{aligned} |S_{ik}| & = |V_{\! i}| \, |V_{\! i} - V_k| \, |Y_{\! ik}| \\ & = |V_{\! i}| \sqrt{(|V_{\! i}| \cos \delta_i - |V_k| \cos \delta_k)^2 + (|V_{\! i}| \sin \delta_i - |V_k| \sin \delta_k)^2} \sqrt{G_{ik}^2 + B_{ik}^2} \end{aligned}