Optimal Power Flow
Adapted from: Section 4 of [MW21] and the
pop_opf_real model of TSSOS's example/modelopf.jl.
[MW21] Magron, Victor and Wang, Jie. TSSOS: a Julia library to exploit sparsity for large-scale polynomial optimization. arXiv preprint arXiv:2103.00915 (2021).
The Alternating Current Optimal Power Flow (AC-OPF) problem looks for the cheapest way to operate a power network subject to the physical laws governing the flow of electricity. In rectangular coordinates each bus voltage has real and imaginary parts. Branch powers are quadratic in those coordinates. PowerModels keeps the branch powers as variables, which lets us send its quadratically constrained quadratic program (QCQP) directly to an SOS solver.
We then build the pop_opf_real formulation used by TSSOS on the same PGLib instance. We compare the dense first-order bounds before exploring how correlative and term sparsity change the Gram blocks and the bound.
using SumOfSquaresLoading the instance
We load a small instance of the PGLib benchmark library with PGLib.jl; it returns the network data already parsed by PowerModels.
import PowerModels
import PGLib
PowerModels.silence()
data = PGLib.pglib("pglib_opf_case14_ieee")Dict{String, Any} with 13 entries:
"baseMVA" => 100.0
"storage" => Dict{String, Any}()
"name" => "pglib_opf_case14_ieee"
"switch" => Dict{String, Any}()
"bus" => Dict{String, Any}("11"=>Dict{String, Any}("base_kv"=>1.0,…
"shunt" => Dict{String, Any}("1"=>Dict{String, Any}("source_id"=>Any…
"source_type" => "matpower"
"per_unit" => true
"dcline" => Dict{String, Any}()
"gen" => Dict{String, Any}("3"=>Dict{String, Any}("gen_bus"=>3, "g…
"load" => Dict{String, Any}("11"=>Dict{String, Any}("qd"=>0.05, "lo…
"source_version" => "2"
"branch" => Dict{String, Any}("20"=>Dict{String, Any}("rate_b"=>0.76,…Giving the PowerModels QCQP directly to SumOfSquares
PowerModels' default AC formulation uses polar voltages, so its branch equations contain sines and cosines. Choose rectangular voltages with ACRPowerModel to get a QCQP for this instance. We build one JuMP model and solve it twice. First, Ipopt finds a feasible operating point. Its cost AC is an upper bound on the minimum cost.
import Ipopt
qcqp = PowerModels.instantiate_model(
data,
PowerModels.ACRPowerModel,
PowerModels.build_opf,
).model
set_optimizer(
qcqp,
optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0),
)
optimize!(qcqp)
AC = objective_value(qcqp)2178.0804123199423Switch the optimizer on that same model to compute a first-order SOS lower bound. Query objective_bound for the relaxation value.
import SCS
sdp_solver = optimizer_with_attributes(
SCS.Optimizer,
"eps_abs" => 1e-9,
"eps_rel" => 1e-9,
"verbose" => 0,
)
set_optimizer(qcqp, () -> SumOfSquares.Optimizer(sdp_solver))
optimize!(qcqp)
qcqp_bound = objective_bound(qcqp)2178.08040254788PowerModels keeps active and reactive power at both ends of every branch. On case14 that adds 80 flow variables to the 38 voltage and generator variables, giving a dense first-order Gram block of size 119. PowerModels enforces the apparent-power limit directly as p² + q² ≤ rate_a². The TSSOS formulation below substitutes the branch flows into the bus balances. Substitution would make the apparent-power constraint quartic, so TSSOS uses the weaker quadratic current limit |I|² ≤ rate_a² / vmin², which follows from |S| = |V| |I|. It also encodes generator intervals as quadratic inequalities. These choices affect the first-order SDP and its sparsity.
Building the polynomial optimization problem
The function below is a port of pop_opf_real from TSSOS' modelopf.jl. It returns the objective f to be minimized, the vectors ineqs (the ≥ 0 constraints) and eqs (the = 0 constraints), together with the variables x. Each generator contributes the active/reactive powers x[2nbus+i]/x[2nbus+ng+i] while bus i contributes the rectangular voltage coordinates x[i] = e_i and x[i+nbus] = f_i.
using DynamicPolynomials
bfind(v, x) = findfirst(isequal(x), v)
fl_sum(itr) = mapreduce(identity, +, itr, init = 0.0)fl_sum (generic function with 1 method)Each constraint is provided as a support/coefficient pair, exactly as in TSSOS, where a support entry is a list of variable indices (repetition encodes powers). We normalize every constraint by its largest coefficient; since this is a positive scaling it leaves the feasible set (and hence the relaxation) unchanged but improves the conditioning.
function mkpoly(x, supp, coe)
return sum(
coe[t] * prod(j -> x[j], supp[t]; init = one(eltype(coe))) for
t in eachindex(coe)
)
end
normalize_poly(p) = p / maximum(abs, coefficients(p))
function build_opf_pop(data; AngleCons = true, LineLimit = "relax")
PowerModels.standardize_cost_terms!(data, order = 2)
ref = PowerModels.build_ref(data)[:it][PowerModels.pm_it_sym][:nw][0]
nbus = length(ref[:bus])
ng = length(ref[:gen])
n = 2 * nbus + 2 * ng
@polyvar x[1:n]
gens = sort!(collect(keys(ref[:gen])))
bus = sort!(collect(keys(ref[:bus])))
# Objective: the sum of the (quadratic) generation costs.
coe = Float64[sum(gen["cost"][3] for (_, gen) in ref[:gen])]
supp = Vector{Int}[Int[]]
for i in 1:ng
gen = ref[:gen][gens[i]]
push!(coe, gen["cost"][2], gen["cost"][1])
push!(supp, [2nbus + i], [2nbus + i, 2nbus + i])
end
f = mkpoly(x, supp, coe)
ineqs = typeof(f)[]
eqs = typeof(f)[]
# Voltage magnitude: vmin² ≤ eᵢ² + fᵢ² ≤ vmax².
for i in 1:nbus
push!(ineqs, mkpoly(x, Vector{Int}[[], [i, i], [i+nbus, i+nbus]],
[-ref[:bus][bus[i]]["vmin"]^2, 1, 1]))
push!(ineqs, mkpoly(x, Vector{Int}[[], [i, i], [i+nbus, i+nbus]],
[ref[:bus][bus[i]]["vmax"]^2, -1, -1]))
end
# Angle differences and (relaxed) thermal limits, one pair per branch.
for (_, branch) in ref[:branch]
g, b = PowerModels.calc_branch_y(branch)
tr, ti = PowerModels.calc_branch_t(branch)
g_fr = branch["g_fr"]; b_fr = branch["b_fr"]
g_to = branch["g_to"]; b_to = branch["b_to"]
tm = branch["tap"]
vr = bfind(bus, branch["f_bus"])
vt = bfind(bus, branch["t_bus"])
srt = sort([vr, vt])
if AngleCons
p1 = mkpoly(x, Vector{Int}[srt, srt .+ nbus, [vt, vr+nbus], [vr, vt+nbus]],
[tan(branch["angmax"]), tan(branch["angmax"]), -1, 1])
p2 = mkpoly(x, Vector{Int}[[vt, vr+nbus], [vr, vt+nbus], srt, srt .+ nbus],
[1, -1, -tan(branch["angmin"]), -tan(branch["angmin"])])
push!(ineqs, normalize_poly(p1), normalize_poly(p2))
end
if LineLimit == "relax"
ab1 = (g+g_fr)^2 + (b+b_fr)^2
cd1 = (-g*tr+b*ti)^2 + (b*tr+g*ti)^2
acbd1 = (g+g_fr)*(-g*tr+b*ti) - (b+b_fr)*(b*tr+g*ti)
bcad1 = -(b+b_fr)*(-g*tr+b*ti) - (g+g_fr)*(b*tr+g*ti)
ab2 = (g+g_to)^2*tm^4 + (b+b_to)^2*tm^4
cd2 = (g*tr+b*ti)^2 + (-b*tr+g*ti)^2
acbd2 = -(g+g_to)*tm^2*(g*tr+b*ti) + (b+b_to)*tm^2*(-b*tr+g*ti)
bcad2 = (b+b_to)*tm^2*(g*tr+b*ti) + (g+g_to)*tm^2*(-b*tr+g*ti)
mvr = ref[:bus][bus[vr]]["vmin"]^2
mvt = ref[:bus][bus[vt]]["vmin"]^2
p1 = mkpoly(x, Vector{Int}[[], [vr, vr], [vr+nbus, vr+nbus], [vt, vt], [vt+nbus, vt+nbus], srt, [vr, vt+nbus], [vt, vr+nbus], srt .+ nbus],
[branch["rate_a"]^2*tm^4/mvr, -ab1, -ab1, -cd1, -cd1, -2acbd1, 2bcad1, -2bcad1, -2acbd1])
p2 = mkpoly(x, Vector{Int}[[], [vt, vt], [vt+nbus, vt+nbus], [vr, vr], [vr+nbus, vr+nbus], srt, [vt, vr+nbus], [vr, vt+nbus], srt .+ nbus],
[branch["rate_a"]^2*tm^4/mvt, -ab2, -ab2, -cd2, -cd2, -2acbd2, 2bcad2, -2bcad2, -2acbd2])
push!(ineqs, normalize_poly(p1), normalize_poly(p2))
end
end
# Generation bounds: pmin ≤ pᵍ ≤ pmax and qmin ≤ qᵍ ≤ qmax.
for i in 1:ng
gen = ref[:gen][gens[i]]
# TSSOS fixes the active power of synchronous condensers to zero.
if gen["pmax"] >= 1e-6
p = mkpoly(x, Vector{Int}[[], [2nbus+i], [2nbus+i, 2nbus+i]],
[-gen["pmin"]*gen["pmax"], gen["pmin"]+gen["pmax"], -1])
push!(ineqs, normalize_poly(p))
else
push!(eqs, x[2nbus+i])
end
p = mkpoly(x, Vector{Int}[[], [2nbus+ng+i], [2nbus+ng+i, 2nbus+ng+i]],
[-gen["qmin"]*gen["qmax"], gen["qmin"]+gen["qmax"], -1])
push!(ineqs, normalize_poly(p))
end
# Power-flow balance at each bus (Kirchhoff's laws): equality constraints.
for (r, i) in enumerate(bus)
bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]]
bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]]
na = 4 * length(ref[:bus_arcs][i]) + 3
coe1 = zeros(na); supp1 = Vector{Vector{Int}}(undef, na)
coe2 = zeros(na); supp2 = Vector{Vector{Int}}(undef, na)
supp1[1:3] = [Int[], [r, r], [r+nbus, r+nbus]]
supp2[1:3] = [Int[], [r, r], [r+nbus, r+nbus]]
coe1[1] = fl_sum(load["pd"] for load in bus_loads)
coe2[1] = fl_sum(load["qd"] for load in bus_loads)
sgs = fl_sum(shunt["gs"] for shunt in bus_shunts)
sbs = fl_sum(shunt["bs"] for shunt in bus_shunts)
coe1[2:3] = [sgs, sgs]
coe2[2:3] = [-sbs, -sbs]
j = 1
for flow in ref[:bus_arcs][i]
branch = ref[:branch][flow[1]]
vr = bfind(bus, branch["f_bus"])
vt = bfind(bus, branch["t_bus"])
srt = sort([vr, vt])
g, b = PowerModels.calc_branch_y(branch)
tr, ti = PowerModels.calc_branch_t(branch)
g_fr = branch["g_fr"]; b_fr = branch["b_fr"]
g_to = branch["g_to"]; b_to = branch["b_to"]
tm = branch["tap"]
a1 = (g+g_fr)/tm^2; b1 = -(b+b_fr)/tm^2
c1 = (-g*tr+b*ti)/tm^2; d1 = (b*tr+g*ti)/tm^2
a2 = g+g_to; b2 = -(b+b_to)
c2 = -(g*tr+b*ti)/tm^2; d2 = -(-b*tr+g*ti)/tm^2
supp1[j+3:j+6] = [srt, [vt, vr+nbus], [vr, vt+nbus], srt .+ nbus]
supp2[j+3:j+6] = [srt, [vt, vr+nbus], [vr, vt+nbus], srt .+ nbus]
if vr == r
coe1[2:3] .+= a1; coe1[j+3:j+6] = [c1, -d1, d1, c1]
coe2[2:3] .+= b1; coe2[j+3:j+6] = [d1, c1, -c1, d1]
else
coe1[2:3] .+= a2; coe1[j+3:j+6] = [c2, d2, -d2, c2]
coe2[2:3] .+= b2; coe2[j+3:j+6] = [d2, -c2, c2, d2]
end
j += 4
end
for gen_id in ref[:bus_gens][i]
gen = bfind(gens, gen_id)
push!(supp1, [2nbus + gen]); push!(coe1, -1)
push!(supp2, [2nbus + ng + gen]); push!(coe2, -1)
end
push!(eqs, normalize_poly(mkpoly(x, supp1, coe1)))
push!(eqs, normalize_poly(mkpoly(x, supp2, coe2)))
end
# Reference bus: the imaginary part of the voltage is set to zero.
for key in keys(ref[:ref_buses])
i = bfind(bus, key)
push!(eqs, mkpoly(x, Vector{Int}[[i+nbus, i+nbus]], Float64[1]))
end
return x, f, ineqs, eqs
end
x, f, ineqs, eqs = build_opf_pop(data)
length(x), length(ineqs), length(eqs)(38, 115, 32)The first-order relaxation
We look for the largest t such that f - t is nonnegative over the feasible set, certified by a Putinar-type representation of degree two (the first order of the moment-SOS hierarchy, also known as Shor's relaxation for this Quadratically Constrained Quadratic Program).
At order one each quadratic equality has a free scalar multiplier. A linear equality, such as zero active power at a synchronous condenser, admits an affine multiplier. The degree-two truncated ideal enforces these equations.
import Clarabel
function build_domain(ineqs, eqs)
V = SemialgebraicSets.truncated(SemialgebraicSets.algebraic_set(eqs), 2)
return V ∩ mapreduce(g -> (@set g >= 0), intersect, ineqs)
end
function relaxation(f, ineqs, eqs; sparsity = Sparsity.NoPattern())
model = SOSModel(Clarabel.Optimizer)
set_silent(model)
@variable(model, t)
@objective(model, Max, t)
con_ref = @constraint(
model, f >= t,
domain = build_domain(ineqs, eqs), maxdegree = 2, sparsity = sparsity,
)
optimize!(model)
return model, con_ref
endrelaxation (generic function with 1 method)The maximal size of the semidefinite blocks is what drives the cost of the SDP, so we define a small helper to read it off the Gram matrix of the certificate.
function block_sizes(g)
if g isa SumOfSquares.BlockDiagonalGramMatrix
return sort!([length(b.basis) for b in g.blocks]; rev = true)
else
return [length(g.basis)]
end
endblock_sizes (generic function with 1 method)Dense relaxation
Without exploiting sparsity, the objective's Sum-of-Squares multiplier uses a single dense block. The degree-two ideal includes all affine multiples of the three linear equations fixing active generator powers to zero.
model, con_ref = relaxation(f, ineqs, eqs)
dense_bound = objective_value(model)
solution_summary(model)solution_summary(; result = 1, verbose = false)
├ solver_name : Clarabel
├ Termination
│ ├ termination_status : OPTIMAL
│ ├ result_count : 1
│ └ raw_status : SOLVED
├ Solution (result = 1)
│ ├ primal_status : FEASIBLE_POINT
│ ├ dual_status : FEASIBLE_POINT
│ ├ objective_value : 2.17808e+03
│ └ dual_objective_value : 2.17808e+03
└ Work counters
├ solve_time (sec) : 7.08296e-01
└ barrier_iterations : 18dense_bound2178.0793247675515Both dense relaxations and the Ipopt operating point give 2178.08 to the cent on case14. We report the gap from each SOS bound to the Ipopt cost as a percentage of that cost.
gap(opt) = 100 * (AC - opt) / AC
gap(dense_bound)4.9931691440236684e-5Removing the three fixed generator coordinates leaves 35 variables and the constant in the dense Gram basis. TSSOS keeps a row and column for each of those coordinates. Its moment equalities force their diagonal entries to zero, so positive semidefiniteness forces the entire rows and columns to zero.
dense_blocks = block_sizes(gram_matrix(con_ref))
fixed = [only(effective_variables(h)) for h in eqs if maxdegree(h) == 1]
dense_blocks1-element Vector{Int64}:
36Correlative sparsity
Sparsity.Variable is the correlative sparsity of CS-TSSOS: it splits the variables into the maximal cliques of (a chordal extension of) the correlative sparsity graph and uses one semidefinite block per clique. The bound is preserved. At order one each quadratic balance equation has a single scalar multiplier. Its individual terms can therefore belong to different cliques. Joining all variables appearing in the equation would create larger blocks.
model, con_ref = relaxation(f, ineqs, eqs; sparsity = Sparsity.Variable())
correlative_bound = objective_value(model)
gap(correlative_bound)3.084331658150866e-5correlative_blocks = block_sizes(gram_matrix(con_ref))
correlative_blocks28-element Vector{Int64}:
7
7
7
7
7
7
6
6
6
6
⋮
2
2
2
2
2
2
2
2
2Term sparsity
Sparsity.Monomial is the term sparsity of TSSOS. With a chordal extension of the term sparsity graph it also breaks the dense block into many small ones while preserving the bound. We take one support-extension step and keep all monomials in the selected Gram basis, as in the first-order example in the authors’ runopf.jl.
model, con_ref = relaxation(f, ineqs, eqs; sparsity = Sparsity.Monomial(ChordalCompletion(), 1, true))
term_bound = objective_value(model)
gap(term_bound)6.210286259873632e-5term_blocks = block_sizes(gram_matrix(con_ref))
term_blocks25-element Vector{Int64}:
6
6
6
6
6
6
5
5
5
5
⋮
3
3
2
2
2
2
2
2
2Combined correlative and term sparsity
Sparsity.VariableMonomial() first finds cliques of variables. Within each clique it builds a term graph on that clique's monomials and takes one minimum-fill chordal extension. This is the order-one TSSOS call with CS = "MF", TS = "MF", and MomentOne = false.
On case14 the largest Gram block shrinks from six to five. The lower bound also drops, leaving about a 0.11% gap to the local AC solution.
model, con_ref = relaxation(f, ineqs, eqs; sparsity = Sparsity.VariableMonomial())
combined_bound = objective_value(model)
gap(combined_bound)0.1113239952250739combined_blocks = block_sizes(gram_matrix(con_ref))
combined_blocks80-element Vector{Int64}:
5
5
5
5
4
4
4
4
4
4
⋮
1
1
1
1
1
1
1
1
1Summary
On this instance the authors' pop_opf_real model has 115 inequalities and 32 equalities. The table counts objective Gram blocks. All four bounds agree with their TSSOS counterparts to the displayed cents.
| Pattern | TSSOS blocks × largest size | SumOfSquares blocks × largest size |
|---|---|---|
| Dense | 1 × 39 | 1 × 36 |
| Correlative | 28 × 7 | 28 × 7 |
| Term | 28 × 6 | 25 × 6 |
| Combined | 80 × 5 | 80 × 5 |
For term sparsity the surviving Gram cliques agree monomial for monomial. TSSOS also has a block on [1, pᵍ] for each fixed generator. On setting pᵍ = 0, each becomes a constraint on the constant moment already present in the other generator blocks. For correlative sparsity the two minimum-fill orderings choose five different fill edges apiece. Those entries occur in none of the problem data. Both chordal extensions describe the same PSD completion problem on the specified first-order moments.
In the combined case all 80 Gram blocks agree with TSSOS, including their monomial labels and multiplicities. On the 135 moments appearing in this relaxation, the truncated ideal and the TSSOS equality multipliers impose the same 35 independent linear equations. TSSOS assigns a scalar inequality multiplier to every clique containing its constraint, producing 211 copies across 115 inequalities here. The copies for a given inequality enter only through their sum, so SumOfSquares uses one nonnegative scalar per inequality.
The comparison uses the real voltage–power formulation, relaxed thermal limits, and order one throughout. Wang, Magron and Lasserre also study a minimum-order relaxation with different orders across cliques.
using Printf
for (name, bound, blocks) in [
("dense", dense_bound, dense_blocks),
("correlative", correlative_bound, correlative_blocks),
("term", term_bound, term_blocks),
("combined", combined_bound, combined_blocks),
]
@printf(
"%-12s bound = %.2f gap = %6.3f%% #blocks = %3d max block = %d\n",
name, bound, gap(bound), length(blocks), maximum(blocks),
)
enddense bound = 2178.08 gap = 0.000% #blocks = 1 max block = 36
correlative bound = 2178.08 gap = 0.000% #blocks = 28 max block = 7
term bound = 2178.08 gap = 0.000% #blocks = 25 max block = 6
combined bound = 2175.66 gap = 0.111% #blocks = 80 max block = 5This page was generated using Literate.jl.