Techniqueadvanced
Sum-of-squares programming
Also called SOS programming, SOS optimization.
Proves that a polynomial is nonnegative by writing it as a sum of squares, checked by a semidefinite program, and so finds polynomial Lyapunov functions.
Sum-of-squares programming proves that a polynomial is nonnegative by writing it as a sum of squares of other polynomials. A sum of squares can never be negative, so the decomposition is a certificate that anyone can check by expanding it. The search for the squares is a semidefinite program: the polynomial must equal for a vector of monomials and a positive semidefinite matrix , and matching coefficients gives linear equations on . The coefficients of the polynomial can themselves be unknowns, provided that they enter linearly. This turns the search for a polynomial Lyapunov function into a convex problem: ask that and both be sums of squares, up to a small positive definite margin. Hilbert (1888) showed that most nonnegative polynomials are not sums of squares, so the method is a sufficient test, not an exact one. Parrilo (2000, 2003) gave the semidefinite formulation and its use for Lyapunov functions, regions of attraction and other questions in control.
In plain words
A polynomial such as is hard to check for negative values by looking at it. If one can write it as , the question is closed: squares are never negative. To find such squares, list the monomials that can appear inside them, here , and . Any sum of squares of combinations of these monomials is with and positive semidefinite, and any positive semidefinite gives such a sum. So the task is to find a positive semidefinite matrix whose entries satisfy a few linear equations. That is a semidefinite program, and convex optimization solves it.
When it applies
- The question is that a polynomial, or a family of polynomials with unknown coefficients that enter linearly, is nonnegative on or on a set described by polynomial inequalities. Rational data can be cleared of denominators first.
- The number of variables and the degree are small. With all monomials of degree at most , the Gram matrix has size and there is one linear equation for each of the monomials of degree at most . For and this is a matrix and equations; for and it is with equations.
- In control, the polynomials are a Lyapunov candidate and its derivative along a polynomial vector field , a barrier certificate, or the conditions of an S-procedure on a semialgebraic set. For a quadratic and a linear it reduces to a linear matrix inequality.
Deciding whether a polynomial of degree is nonnegative is NP-hard, so no fast exact test is expected. A semidefinite program is solved by an interior point method to accuracy in time polynomial in the size of the matrices, the number of equations and , under assumptions such as a strictly feasible point and a known bound on the solution. This is a statement about approximate solutions, not about an exact decision.
The template
- Choose the degree and the monomials. For a polynomial of degree , take as the monomials of degree at most . Remove every monomial whose exponent is not in half the Newton polytope of , the convex hull of the exponents of ; such monomials cannot appear in any decomposition.
- Match coefficients. Write with symmetric. For each monomial , the sum of the entries with must equal the coefficient of in . This is a linear system in the entries of and in the free coefficients of , if there are some.
- Solve the semidefinite program. Find with and every Gram block , or optimize a linear objective over this set, for example the largest such that is a sum of squares.
- Extract the squares. Factor with diagonal; then , where is column of . A Cholesky decomposition does the same for a positive definite .
- Make it a proof. A numerical solver returns a that satisfies the equations and the cone condition only up to a tolerance. If the computed is positive definite with some margin, round it to rationals, project it back onto in exact arithmetic, and check that it is still positive semidefinite.
For the search for a Lyapunov function of with , the unknown is for chosen monomials with no constant or linear term, and the program has two constraints for a small : is a sum of squares, and is a sum of squares. Both are linear in . A solution gives and on all of , so the origin is globally asymptotically stable.
The implementation solves the feasibility problem with a short method that needs no external solver, and it returns only exact certificates:
SOS-FEASIBLE(constraints p_j(c) = z_j^T Q_j z_j for j = 1..k, margin ε)- 1
match coefficients: build the linear equations A u = b in u = (c, Q_1, ..., Q_k) - 2
u ← 0 - 3
repeat at most T times - 4
u ← the orthogonal projection of u onto {u : A u = b} - 5
if λ_min(Q_j) ≥ ε/2 for every j then exit the loop - 6
for each j: write Q_j = V Λ V^T and set Q_j ← V max(Λ, ε) V^T ▷ projection onto {Q ⪰ ε I} - 7
if the loop did not exit then return FAIL ▷ not a proof that no certificate exists - 8
round every entry of u to a fraction with a small denominator - 9
u ← the orthogonal projection of u onto {u : A u = b}, in exact rational arithmetic - 10
factor each Q_j = L D L^T exactly; if a pivot is negative then return FAIL - 11
return (c, Q_1, ..., Q_k) ▷ an exact certificate
Lines L3 to L6 are alternating projections between the affine set and the closed convex set where every block satisfies . When the two sets intersect, alternating projections converge to a point of the intersection, often slowly. The off-diagonal entries are scaled by in , so that the Euclidean distance on is the Frobenius distance on the matrices and line L6 is the true projection. Line L5 stops at a point that has a margin of . The rounding in L8 and the exact projection in L9 move the matrices only a little, so the margin keeps them positive semidefinite in practice, and line L10 confirms it exactly. A returned result is therefore a proof: the equations hold exactly, and with shows that every is positive semidefinite. A FAIL means only that this search did not succeed. A production code uses an interior point solver in step 3 and keeps steps 4 and 5.
Classic examples
A Gram matrix family. For and , matching coefficients gives from , from , from , from , and from . One parameter is free:
Every gives a matrix with , and is a sum of squares exactly when some is positive semidefinite. For the last diagonal entry is , so that choice fails. For the exact factorization gives , rank , and the decomposition . For it gives , a positive definite matrix and a sum of three squares. The determinant is , and exactly for . The implementation finds a positive definite member of this interval and returns its exact factorization.
The Motzkin polynomial. is nonnegative: the arithmetic mean of , and is at least their geometric mean . It is not a sum of squares. The Newton polytope of is the triangle with corners , and , so a square in a decomposition can only use the monomials , , and . Of all products of two of these, only equals . So the coefficient of must equal the diagonal entry , which cannot be negative in a positive semidefinite matrix. This is the standard example of a nonnegative polynomial that the method cannot certify; Motzkin published it in 1967.
A Lyapunov function for a damped Duffing oscillator. Take , . A quadratic cannot prove global asymptotic stability by this program: the quartic part of is , which takes both signs unless , and makes indefinite or degenerate. With in the span of , , and , and the Gram basis for both constraints, the program is feasible. One solution is
The quadratic part of has the matrix , with pivots and , so is positive definite and radially unbounded. The implementation finds a certificate of this form with in a few milliseconds, and the tests check along a simulated solution that decreases at every step.
Variations
- Global lower bounds. The largest such that is a sum of squares is a lower bound on , and it is exact when is a sum of squares, for example for every univariate . The dual of this program is a moment relaxation; Lasserre's hierarchy raises the degree step by step.
- Nonnegativity on a set. To show where , find sums of squares with . This is a polynomial S-procedure. Putinar (1993) showed that every polynomial that is strictly positive on such a set has this form when the description of the set is archimedean, for example when one of the is . The degrees needed are not bounded in advance. The Positivstellensatz gives certificates of infeasibility in the same spirit, much as the Nullstellensatz does for equations.
- Regions of attraction. For a local result, ask that is a sum of squares with a sum of squares. Then on the sublevel set . The product is bilinear, so one fixes one factor, solves, and alternates, as described in region-of-attraction estimation.
- Smaller programs. Newton polytope reduction, symmetry and sparsity cut the Gram matrix. Diagonally dominant and scaled diagonally dominant sums of squares (Ahmadi and Majumdar) replace the semidefinite constraint by linear or second-order cone constraints, with more conservatism.
- Matrix sums of squares. A polynomial matrix is a sum of squares if is one in . This certifies state-dependent metrics for contraction and other matrix inequalities.
Pitfalls
- A sum of squares is nonnegative, but a nonnegative polynomial need not be a sum of squares. Hilbert proved that the two sets are equal only for univariate polynomials, for quadratic polynomials and for bivariate quartics (in homogeneous form: binary forms, quadratic forms and ternary quartics). The Motzkin polynomial is a counterexample in two variables of degree .
- a sum of squares gives only , not a positive definite . Add the margin or another positive definite term. This margin also excludes some correct Lyapunov functions: is not above near the origin.
- A polynomial vector field can be globally asymptotically stable and have no polynomial Lyapunov function of any degree. Ahmadi, Krstic and Parrilo (2011) gave the example , . So a failed search at every degree tried does not show that the origin is not asymptotically stable; see the converse Lyapunov theorem.
- Numerical solvers accept small violations of the equations and of the cone. A solver message "feasible" is not a proof. Round and check exactly, as in step 5. Peyrl and Parrilo (2008) studied this rounding and projection.
- The rounding step needs a margin, so it needs a strictly feasible point. If the basis contains a monomial that the Newton polytope rules out, every positive semidefinite that satisfies the equations has a zero row and column for it, and no positive definite exists. In the Lyapunov search, the constant monomial in the basis for has this problem, because forces . With such a basis the method of this page fails, and interior point solvers become inaccurate. Remove the monomials first.
- The size grows as . Ten variables with a quartic already need several matrices of size , and degree in ten variables needs size .
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sum-of-squares-programming/. The authors are listed in prov/501R5E.jsonl.
"""A small sum-of-squares feasibility solver with exact certificates.
A polynomial is a dict that maps an exponent tuple to a coefficient, for
example {(4, 0): 2, (3, 1): 2, (2, 2): -1, (0, 4): 5} is
2 x^4 + 2 x^3 y - x^2 y^2 + 5 y^4.
An SOS program has m free scalars c_1, ..., c_m and a list of constraints.
Constraint j says that p0_j + c_1 p1_j + ... + c_m pm_j equals z_j^T Q_j z_j
for a positive semidefinite Gram matrix Q_j, where z_j is a list of
monomials (the basis). Matching the coefficients of every monomial gives
linear equations A u = b in the unknowns u = (c, entries of the Q_j).
solve() follows the pseudocode of the page (lines L1 to L11). It finds a
point of the affine set {A u = b} whose Gram blocks are positive definite,
by alternating projections between the affine set and the shifted cone
{Q >= eps I} in floating point. Then it rounds to rationals, projects back
onto {A u = b} exactly, and checks every block by an LDL^T factorization in
Fraction. A returned result is therefore an exact certificate. A return
value of None means that the search failed; it is not a proof that no
certificate exists.
"""
import math
from fractions import Fraction
# ---------------------------------------------------------------- polynomials
def monomials(nvars, lo, hi):
"""Exponent tuples of total degree lo..hi, by degree, then lexicographic
from the largest power of the first variable."""
out = []
def rec(prefix, left, k):
if k == nvars - 1:
out.append(tuple(prefix + [left]))
return
for e in range(left, -1, -1):
rec(prefix + [e], left - e, k + 1)
for d in range(lo, hi + 1):
rec([], d, 0)
return out
def padd(p, q, s=1):
r = dict(p)
for k, v in q.items():
r[k] = r.get(k, 0) + s * v
if r[k] == 0:
del r[k]
return r
def pscale(p, s):
return {k: s * v for k, v in p.items() if s * v != 0}
def pmul(p, q):
r = {}
for a, u in p.items():
for b, v in q.items():
k = tuple(x + y for x, y in zip(a, b))
r[k] = r.get(k, 0) + u * v
return {k: v for k, v in r.items() if v != 0}
def pclean(p):
return {k: v for k, v in p.items() if v != 0}
def peval(p, x):
s = 0
for k, v in p.items():
t = v
for xi, e in zip(x, k):
t = t * xi ** e
s += t
return s
def pderiv(p, i):
r = {}
for k, v in p.items():
if k[i] > 0:
kk = list(k)
kk[i] -= 1
kk = tuple(kk)
r[kk] = r.get(kk, 0) + v * k[i]
return pclean(r)
def gram_form(basis, Q):
"""The polynomial z^T Q z for the monomial list z = basis."""
r = {}
n = len(basis)
for a in range(n):
for b in range(n):
if Q[a][b] == 0:
continue
k = tuple(x + y for x, y in zip(basis[a], basis[b]))
r[k] = r.get(k, 0) + Q[a][b]
return pclean(r)
# ------------------------------------------------------------- linear algebra
def ldl(Q):
"""Exact LDL^T of a symmetric matrix of Fractions.
Returns (L, D) with Q = L diag(D) L^T if Q is positive semidefinite, and
None if it is not. A zero pivot is allowed only if the rest of its column
is zero after elimination."""
n = len(Q)
A = [[Fraction(v) for v in row] for row in Q]
L = [[Fraction(int(i == j)) for j in range(n)] for i in range(n)]
D = [Fraction(0)] * n
for k in range(n):
d = A[k][k] - sum(L[k][j] ** 2 * D[j] for j in range(k))
col = [A[i][k] - sum(L[i][j] * L[k][j] * D[j] for j in range(k))
for i in range(k + 1, n)]
if d < 0:
return None
if d == 0:
if any(v != 0 for v in col):
return None
continue
D[k] = d
for i, v in zip(range(k + 1, n), col):
L[i][k] = v / d
return L, D
def jacobi_eig(S, tol=1e-13, sweeps=60):
"""Eigenvalues and eigenvectors (columns of V) of a symmetric float
matrix, by the cyclic Jacobi method."""
n = len(S)
A = [list(map(float, row)) for row in S]
V = [[float(i == j) for j in range(n)] for i in range(n)]
for _ in range(sweeps):
off = sum(A[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
if off <= tol * tol * max(1.0, sum(A[i][i] ** 2 for i in range(n))):
break
for p in range(n - 1):
for q in range(p + 1, n):
if A[p][q] == 0.0:
continue
theta = (A[q][q] - A[p][p]) / (2.0 * A[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
s = t * c
for k in range(n):
akp, akq = A[k][p], A[k][q]
A[k][p] = c * akp - s * akq
A[k][q] = s * akp + c * akq
for k in range(n):
apk, aqk = A[p][k], A[q][k]
A[p][k] = c * apk - s * aqk
A[q][k] = s * apk + c * aqk
for k in range(n):
vkp, vkq = V[k][p], V[k][q]
V[k][p] = c * vkp - s * vkq
V[k][q] = s * vkp + c * vkq
return [A[i][i] for i in range(n)], V
def _orthogonalize(rows, rhs, exact):
"""Gram-Schmidt on the rows of A u = b. Returns (O, g, norms) with
orthogonal rows O, right-hand sides g, and squared norms; or None if the
equations are inconsistent."""
O, g, nn = [], [], []
tol = 0 if exact else 1e-10
for r, beta in zip(rows, rhs):
r = list(r)
for o, go, no in zip(O, g, nn):
f = sum(x * y for x, y in zip(r, o)) / no
if f != 0:
r = [x - f * y for x, y in zip(r, o)]
beta = beta - f * go
n2 = sum(x * x for x in r)
if n2 <= tol:
if abs(beta) > (0 if exact else 1e-8):
return None
continue
O.append(r)
g.append(beta)
nn.append(n2)
return O, g, nn
def _project(u, O, g, nn):
for o, go, no in zip(O, g, nn):
f = (sum(x * y for x, y in zip(u, o)) - go) / no
if f != 0:
u = [x - f * y for x, y in zip(u, o)]
return u
# ----------------------------------------------------------------- the solver
class SOSProgram:
"""Free scalars c_1..c_m and constraints p0 + sum c_i p_i is SOS."""
def __init__(self, nfree=0):
self.m = nfree
self.cons = [] # (p0, [p_1, ..., p_m], basis)
def add_sos(self, p0, ps=None, basis=None):
ps = list(ps or [])
ps = ps + [{}] * (self.m - len(ps))
self.cons.append((dict(p0), ps, list(basis)))
def _layout(prog):
"""Index of every unknown: c_i first, then the upper triangle of each Q_j."""
idx = prog.m
blocks = []
for _, _, basis in prog.cons:
n = len(basis)
pos = {}
for a in range(n):
for b in range(a, n):
pos[(a, b)] = idx
idx += 1
blocks.append(pos)
return idx, blocks
def _equations(prog, blocks, scale):
"""Rows of A u = b. With scale=True an off-diagonal unknown is sqrt(2)
times the entry, so that the Euclidean norm of u is the Frobenius norm."""
N = prog.m + sum(len(p) for p in blocks)
rows, rhs = [], []
for (p0, ps, basis), pos in zip(prog.cons, blocks):
mons = set(p0)
for p in ps:
mons |= set(p)
terms = {}
for (a, b), k in pos.items():
al = tuple(x + y for x, y in zip(basis[a], basis[b]))
mons.add(al)
if a == b:
w = 1
else:
w = math.sqrt(2.0) if scale else 2
terms.setdefault(al, []).append((k, w))
for al in sorted(mons):
row = [0.0 if scale else Fraction(0)] * N
for i, p in enumerate(ps):
if al in p:
row[i] = float(p[al]) if scale else Fraction(p[al])
for k, w in terms.get(al, []):
row[k] = -w
b0 = p0.get(al, 0)
rows.append(row)
rhs.append(-float(b0) if scale else -Fraction(b0))
return rows, rhs
def _block(u, pos, n, scale):
Q = [[0] * n for _ in range(n)]
for (a, b), k in pos.items():
v = u[k]
if a != b and scale:
v = v / math.sqrt(2.0)
Q[a][b] = Q[b][a] = v
return Q
def solve(prog, eps=1e-3, iters=3000, denom=10 ** 6):
"""Search for an exact SOS certificate. Returns a dict with the free
scalars 'c' (Fractions), the Gram matrices 'Q' and their LDL^T factors
'ldl', or None if the search fails."""
N, blocks = _layout(prog)
rows, rhs = _equations(prog, blocks, True) # @line L1
fl = _orthogonalize(rows, rhs, False) # @line L1
if fl is None: # @line L1
return None # @line L1
u = [0.0] * N # @line L2
sizes = [len(c[2]) for c in prog.cons]
found = False
for _ in range(iters): # @line L3
u = _project(u, *fl) # @line L4
eig = [jacobi_eig(_block(u, pos, n, True)) for pos, n in zip(blocks, sizes)]
if all(min(w) >= eps / 2 for w, _ in eig): # @line L5
found = True # @line L5
break # @line L5
for (w, V), pos, n in zip(eig, blocks, sizes): # @line L6
Q = [[sum(V[i][k] * max(w[k], eps) * V[j][k] for k in range(n)) # @line L6
for j in range(n)] for i in range(n)] # @line L6
for (a, b), k in pos.items(): # @line L6
u[k] = Q[a][b] * (math.sqrt(2.0) if a != b else 1.0) # @line L6
if not found: # @line L7
return None # @line L7
q = list(u) # @line L8
for pos in blocks: # @line L8
for (a, b), k in pos.items(): # @line L8
if a != b: # @line L8
q[k] = u[k] / math.sqrt(2.0) # @line L8
q = [Fraction(v).limit_denominator(denom) for v in q] # @line L8
ex = _orthogonalize(*_equations(prog, blocks, False), True) # @line L9
if ex is None: # @line L9
return None # @line L9
q = _project(q, *ex) # @line L9
Qs, facs = [], []
for pos, n in zip(blocks, sizes): # @line L10
Q = _block(q, pos, n, False) # @line L10
f = ldl(Q) # @line L10
if f is None: # @line L10
return None # @line L10
Qs.append(Q)
facs.append(f)
return {"c": q[:prog.m], "Q": Qs, "ldl": facs} # @line L11
def certificate_holds(prog, res):
"""Exact check: every constraint polynomial equals its Gram form, and
every Gram matrix is positive semidefinite."""
c = res["c"]
for (p0, ps, basis), Q in zip(prog.cons, res["Q"]):
p = dict(p0)
for ci, pi in zip(c, ps):
p = padd(p, pscale(pi, ci))
if pclean(padd(p, gram_form(basis, Q), -1)):
return False
if ldl(Q) is None:
return False
return True
def sos_terms(basis, L, D):
"""The decomposition sum_k D[k] * l_k^2 with l_k = (column k of L)^T z."""
out = []
n = len(basis)
for k in range(n):
if D[k] == 0:
continue
lk = {}
for i in range(n):
if L[i][k] != 0:
lk[basis[i]] = L[i][k]
out.append((D[k], lk))
return out
def lyapunov_program(f, vbasis, eps, vgram=None, dgram=None):
"""SOS program for a polynomial Lyapunov function V = sum c_i v_i with
V - eps |x|^2 SOS and -dV/dt - eps |x|^2 SOS, for x' = f(x).
f is a list of polynomials, vbasis a list of monomials for V, and vgram
and dgram the Gram bases of the two constraints. By default they are all
monomials of degree 1 to half the degree of each polynomial, rounded up.
The solver needs a strictly feasible point, so a basis with monomials
that no solution can use (outside the half Newton polytope) makes it
fail; then pass smaller bases."""
n = len(f)
sq = {}
for i in range(n):
e = [0] * n
e[i] = 2
sq[tuple(e)] = Fraction(eps)
vs = [{m: 1} for m in vbasis]
vdots = []
for v in vs:
d = {}
for i in range(n):
d = padd(d, pmul(pderiv(v, i), f[i]))
vdots.append(d)
dv = max(sum(m) for m in vbasis)
df = max(sum(m) for p in f for m in p)
prog = SOSProgram(len(vbasis))
if vgram is None:
vgram = monomials(n, 1, (dv + 1) // 2)
if dgram is None:
dgram = monomials(n, 1, (dv + df) // 2)
prog.add_sos(pscale(sq, -1), vs, vgram)
prog.add_sos(pscale(sq, -1), [pscale(d, -1) for d in vdots], dgram)
return prog
test_sum_of_squares_programming.py 239 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sum-of-squares-programming/. The authors are listed in prov/501R5E.jsonl.
import math
import random
from fractions import Fraction as F
from sum_of_squares_programming import (
SOSProgram,
certificate_holds,
gram_form,
jacobi_eig,
ldl,
lyapunov_program,
monomials,
padd,
pclean,
pderiv,
peval,
pmul,
pscale,
solve,
sos_terms,
)
# 2 x^4 + 2 x^3 y - x^2 y^2 + 5 y^4 in the basis z = (x^2, y^2, x y).
P = {(4, 0): 2, (3, 1): 2, (2, 2): -1, (0, 4): 5}
Z = [(2, 0), (0, 2), (1, 1)]
MOTZKIN = {(4, 2): 1, (2, 4): 1, (2, 2): -3, (0, 0): 1}
# x1' = x2, x2' = -x1 - x2 - x1^3 (a damped Duffing oscillator).
DUFFING = [{(0, 1): 1}, {(1, 0): -1, (0, 1): -1, (3, 0): -1}]
def gram_family(lam):
return [[2, lam, 1], [lam, 5, 0], [1, 0, -1 - 2 * lam]]
def square(p):
return pmul(p, p)
def from_terms(terms):
s = {}
for d, l in terms:
s = padd(s, pscale(square(l), d))
return s
def ldl_product(L, D):
n = len(D)
return [[sum(L[i][k] * D[k] * L[j][k] for k in range(n)) for j in range(n)] for i in range(n)]
def vdot(V, f):
d = {}
for i in range(len(f)):
d = padd(d, pmul(pderiv(V, i), f[i]))
return d
def test_monomial_count_is_binomial():
for n in range(1, 4):
for d in range(0, 4):
assert len(monomials(n, 0, d)) == math.comb(n + d, d)
def test_every_gram_matrix_of_the_family_gives_p():
for lam in (-3, -2, F(-1, 2), 0, 7):
assert gram_form(Z, gram_family(lam)) == P
def test_ldl_on_the_family():
L, D = ldl(gram_family(-3))
assert D == [2, F(1, 2), 0]
assert ldl_product(L, D) == gram_family(-3)
L, D = ldl(gram_family(-2))
assert D == [2, 3, F(13, 6)]
assert ldl(gram_family(0)) is None
def test_hand_decomposition():
a = {(2, 0): 2, (0, 2): -3, (1, 1): 1}
b = {(0, 2): 1, (1, 1): 3}
s = padd(pscale(square(a), F(1, 2)), pscale(square(b), F(1, 2)))
assert s == P
L, D = ldl(gram_family(-3))
assert from_terms(sos_terms(Z, L, D)) == P
def test_solver_finds_an_exact_certificate():
prog = SOSProgram()
prog.add_sos(P, [], Z)
res = solve(prog)
assert res is not None
assert certificate_holds(prog, res)
L, D = res["ldl"][0]
assert all(d > 0 for d in D)
assert from_terms(sos_terms(Z, L, D)) == P
def test_motzkin_basis_forces_a_negative_diagonal_entry():
basis = [(0, 0), (1, 1), (2, 1), (1, 2)]
rng = random.Random(3)
for _ in range(20):
Q = [[0] * 4 for _ in range(4)]
for i in range(4):
for j in range(i, 4):
Q[i][j] = Q[j][i] = F(rng.randint(-5, 5))
# The only product of two basis monomials equal to x^2 y^2 is (xy)(xy).
assert gram_form(basis, Q).get((2, 2), 0) == Q[1][1]
prog = SOSProgram()
prog.add_sos(MOTZKIN, [], basis)
assert solve(prog) is None
def test_motzkin_is_nonnegative_but_search_fails():
# Grid check of nonnegativity (the proof is the AM-GM inequality).
for i in range(41):
for j in range(41):
x, y = -2 + i * 0.1, -2 + j * 0.1
assert peval(MOTZKIN, (x, y)) >= -1e-12
prog = SOSProgram()
prog.add_sos(MOTZKIN, [], monomials(2, 0, 3))
assert solve(prog, iters=300) is None
def test_negative_polynomial_has_no_certificate():
p = {(4, 0): 1, (0, 4): 1, (2, 2): -3}
assert peval(p, (1, 1)) == -1
prog = SOSProgram()
prog.add_sos(p, [], [(2, 0), (1, 1), (0, 2)])
assert solve(prog, iters=300) is None
def test_univariate_positive_polynomials():
for p in ({(4,): 1, (0,): 1}, {(4,): 1, (3,): -2, (2,): 3, (1,): -2, (0,): 1}):
prog = SOSProgram()
prog.add_sos(p, [], [(0,), (1,), (2,)])
res = solve(prog)
assert res is not None and certificate_holds(prog, res)
def test_random_interior_sos_polynomials():
rng = random.Random(1)
for n, basis in ((2, monomials(2, 0, 2)), (2, monomials(2, 0, 2)), (3, monomials(3, 1, 2))):
k = len(basis)
G = [[rng.randint(-3, 3) for _ in range(k)] for _ in range(k)]
Q = [[sum(G[i][t] * G[j][t] for t in range(k)) + int(i == j) for j in range(k)] for i in range(k)]
p = gram_form(basis, Q)
prog = SOSProgram()
prog.add_sos(p, [], basis)
res = solve(prog)
assert res is not None and certificate_holds(prog, res)
L, D = res["ldl"][0]
assert from_terms(sos_terms(basis, L, D)) == p
def test_hand_lyapunov_function_for_duffing():
V = {(0, 2): F(1, 2), (2, 0): F(3, 4), (1, 1): F(1, 2), (4, 0): F(1, 4)}
assert vdot(V, DUFFING) == {(2, 0): F(-1, 2), (0, 2): F(-1, 2), (4, 0): F(-1, 2)}
assert ldl([[F(3, 4), F(1, 4)], [F(1, 4), F(1, 2)]])[1] == [F(3, 4), F(5, 12)]
def test_solver_finds_a_quartic_lyapunov_function():
vb = [(2, 0), (1, 1), (0, 2), (4, 0)]
gb = [(1, 0), (0, 1), (2, 0)]
eps = F(1, 100)
prog = lyapunov_program(DUFFING, vb, eps, gb, gb)
res = solve(prog)
assert res is not None and certificate_holds(prog, res)
V = {m: c for m, c in zip(vb, res["c"]) if c != 0}
W = vdot(V, DUFFING)
sq = {(2, 0): eps, (0, 2): eps}
# Exact: V - eps|x|^2 and -V' - eps|x|^2 are the Gram forms of the certificate.
assert pclean(padd(V, sq, -1)) == gram_form(gb, res["Q"][0])
assert pclean(padd(pscale(W, -1), sq, -1)) == gram_form(gb, res["Q"][1])
# Sanity: V decreases along a simulated solution (RK4, dt = 0.01, T = 10).
Vf = {k: float(v) for k, v in V.items()}
def f(x):
return (x[1], -x[0] - x[1] - x[0] ** 3)
x, dt, steps = (2.0, -1.5), 0.01, int(round(10 / 0.01))
assert steps == 1000
last = peval(Vf, x)
for _ in range(steps):
k1 = f(x)
k2 = f((x[0] + dt / 2 * k1[0], x[1] + dt / 2 * k1[1]))
k3 = f((x[0] + dt / 2 * k2[0], x[1] + dt / 2 * k2[1]))
k4 = f((x[0] + dt * k3[0], x[1] + dt * k3[1]))
x = (x[0] + dt / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]),
x[1] + dt / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]))
now = peval(Vf, x)
assert now < last
last = now
# The linear part has eigenvalues -1/2 +- i sqrt(3)/2, so |x| shrinks like e^(-t/2).
assert math.hypot(*x) < 5e-2
def test_no_quadratic_certificate_for_duffing():
prog = lyapunov_program(DUFFING, monomials(2, 2, 2), F(1, 100),
[(1, 0), (0, 1)], [(1, 0), (0, 1), (2, 0), (1, 1)])
assert solve(prog, iters=300) is None
# The reason: for V = a x1^2 + b x1 x2 + c x2^2, the quartic part of -V'
# is b x1^4 + 2 c x1^3 x2, which is negative somewhere unless c = 0.
a, b, c = F(1), F(1, 3), F(2)
W = pscale(vdot({(2, 0): a, (1, 1): b, (0, 2): c}, DUFFING), -1)
assert {k: v for k, v in W.items() if sum(k) == 4} == {(4, 0): b, (3, 1): 2 * c}
def test_ldl_random_matrices():
rng = random.Random(7)
for _ in range(30):
n = rng.randint(1, 6)
r = rng.randint(1, n)
G = [[F(rng.randint(-3, 3)) for _ in range(r)] for _ in range(n)]
Q = [[sum(G[i][t] * G[j][t] for t in range(r)) for j in range(n)] for i in range(n)]
out = ldl(Q)
assert out is not None
L, D = out
assert ldl_product(L, D) == Q
assert all(d >= 0 for d in D)
Q[0][0] -= 1 + sum(abs(v) for v in Q[0])
assert ldl(Q) is None
def test_jacobi_eigenvalues():
rng = random.Random(11)
for _ in range(20):
n = rng.randint(2, 5)
S = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i, n):
S[i][j] = S[j][i] = rng.uniform(-2, 2)
w, V = jacobi_eig(S)
assert abs(sum(w) - sum(S[i][i] for i in range(n))) < 1e-9
for k in range(n):
Sv = [sum(S[i][j] * V[j][k] for j in range(n)) for i in range(n)]
assert max(abs(Sv[i] - w[k] * V[i][k]) for i in range(n)) < 1e-9
Exercises
- Show that is a sum of squares, and find all Gram matrices for . Which of them have rank ?
- For the family above, verify the determinant and show that exactly for .
- Show that for a univariate polynomial of even degree, the largest such that is a sum of squares equals .
- For , , show that gives . Explain why the two constraints with the margin reject this , and propose a margin that accepts it.
- Write the program for the Duffing example with in the span of , and only, and prove by hand that it is infeasible for every .
References
- P. A. Parrilo, Semidefinite programming relaxations for semialgebraic problems, Mathematical Programming 96(2), 293-320, 2003, the Gram matrix form of the sum-of-squares condition and its use with Positivstellensatz certificates
- P. A. Parrilo, Structured semidefinite programs and semialgebraic geometry methods in robustness and optimization, PhD thesis, California Institute of Technology, 2000, the search for polynomial Lyapunov functions by sum-of-squares programs
- D. Hilbert, Über die Darstellung definiter Formen als Summe von Formenquadraten, Mathematische Annalen 32, 342-350, 1888, the cases in which every nonnegative form is a sum of squares of forms
- M. Putinar, Positive polynomials on compact semi-algebraic sets, Indiana University Mathematics Journal 42(3), 969-984, 1993, the representation of polynomials that are positive on a compact set with an archimedean description
- A. A. Ahmadi, M. Krstic and P. A. Parrilo, A globally asymptotically stable polynomial vector field with no polynomial Lyapunov function, 50th IEEE Conference on Decision and Control, 2011, the example of a quadratic vector field that is globally asymptotically stable and has no polynomial Lyapunov function
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 501R5E Edit this page History Report an error Markdown