Algorithm Search⌘K

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 z(x)TQz(x)z(x)^T Q z(x) for a vector z(x)z(x) of monomials and a positive semidefinite matrix QQ, and matching coefficients gives linear equations on QQ. The coefficients of the polynomial can themselves be unknowns, provided that they enter linearly. This turns the search for a polynomial Lyapunov function VV into a convex problem: ask that VV and −V˙-\dot V 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 2x4+2x3y−x2y2+5y42x^4 + 2x^3 y - x^2 y^2 + 5y^4 is hard to check for negative values by looking at it. If one can write it as 12(2x2−3y2+xy)2+12(y2+3xy)2\tfrac12 (2x^2 - 3y^2 + xy)^2 + \tfrac12 (y^2 + 3xy)^2, the question is closed: squares are never negative. To find such squares, list the monomials that can appear inside them, here x2x^2, y2y^2 and xyxy. Any sum of squares of combinations of these monomials is zTQzz^T Q z with z=(x2,y2,xy)z = (x^2, y^2, xy) and QQ positive semidefinite, and any positive semidefinite QQ 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 Rn\mathbb{R}^n or on a set described by polynomial inequalities. Rational data can be cleared of denominators first.
  • The number of variables nn and the degree 2d2d are small. With all monomials of degree at most dd, the Gram matrix has size (n+dd)\binom{n+d}{d} and there is one linear equation for each of the (n+2d2d)\binom{n+2d}{2d} monomials of degree at most 2d2d. For n=2n = 2 and 2d=42d = 4 this is a 6×66 \times 6 matrix and 1515 equations; for n=6n = 6 and 2d=82d = 8 it is 210×210210 \times 210 with 30033003 equations.
  • In control, the polynomials are a Lyapunov candidate VV and its derivative V˙=∇V⋅f\dot V = \nabla V \cdot f along a polynomial vector field ff, a barrier certificate, or the conditions of an S-procedure on a semialgebraic set. For a quadratic VV and a linear ff it reduces to a linear matrix inequality.

Deciding whether a polynomial of degree 44 is nonnegative is NP-hard, so no fast exact test is expected. A semidefinite program is solved by an interior point method to accuracy ϵ\epsilon in time polynomial in the size of the matrices, the number of equations and log⁡(1/ϵ)\log(1/\epsilon), 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

  1. Choose the degree and the monomials. For a polynomial pp of degree 2d2d, take z(x)z(x) as the monomials of degree at most dd. Remove every monomial whose exponent is not in half the Newton polytope of pp, the convex hull of the exponents of pp; such monomials cannot appear in any decomposition.
  2. Match coefficients. Write p(x)=z(x)TQz(x)p(x) = z(x)^T Q z(x) with QQ symmetric. For each monomial xαx^\alpha, the sum of the entries QijQ_{ij} with zizj=xαz_i z_j = x^\alpha must equal the coefficient of xαx^\alpha in pp. This is a linear system Au=bA u = b in the entries of QQ and in the free coefficients cc of pp, if there are some.
  3. Solve the semidefinite program. Find uu with Au=bA u = b and every Gram block Qj⪰0Q_j \succeq 0, or optimize a linear objective over this set, for example the largest γ\gamma such that p−γp - \gamma is a sum of squares.
  4. Extract the squares. Factor Q=LDLTQ = L D L^T with D≥0D \ge 0 diagonal; then p=∑idi(ℓiTz)2p = \sum_i d_i (\ell_i^T z)^2, where ℓi\ell_i is column ii of LL. A Cholesky decomposition does the same for a positive definite QQ.
  5. Make it a proof. A numerical solver returns a QQ that satisfies the equations and the cone condition only up to a tolerance. If the computed QQ is positive definite with some margin, round it to rationals, project it back onto Au=bA u = b in exact arithmetic, and check that it is still positive semidefinite.

For the search for a Lyapunov function of x˙=f(x)\dot x = f(x) with f(0)=0f(0) = 0, the unknown is V(x)=∑kckmk(x)V(x) = \sum_k c_k m_k(x) for chosen monomials mkm_k with no constant or linear term, and the program has two constraints for a small ϵ>0\epsilon > 0: V(x)−ϵ∥x∥2V(x) - \epsilon \|x\|^2 is a sum of squares, and −∇V(x)⋅f(x)−ϵ∥x∥2-\nabla V(x) \cdot f(x) - \epsilon \|x\|^2 is a sum of squares. Both are linear in cc. A solution gives V(x)≥ϵ∥x∥2V(x) \ge \epsilon \|x\|^2 and V˙(x)≤−ϵ∥x∥2\dot V(x) \le -\epsilon \|x\|^2 on all of Rn\mathbb{R}^n, 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:

  1. SOS-FEASIBLE(constraints p_j(c) = z_j^T Q_j z_j for j = 1..k, margin ε)
  2. 1match coefficients: build the linear equations A u = b in u = (c, Q_1, ..., Q_k)
  3. 2u ← 0
  4. 3repeat at most T times
  5. 4u ← the orthogonal projection of u onto {u : A u = b}
  6. 5if λ_min(Q_j) ≥ ε/2 for every j then exit the loop
  7. 6for each j: write Q_j = V Λ V^T and set Q_j ← V max(Λ, ε) V^T ▷ projection onto {Q ⪰ ε I}
  8. 7if the loop did not exit then return FAIL ▷ not a proof that no certificate exists
  9. 8round every entry of u to a fraction with a small denominator
  10. 9u ← the orthogonal projection of u onto {u : A u = b}, in exact rational arithmetic
  11. 10factor each Q_j = L D L^T exactly; if a pivot is negative then return FAIL
  12. 11return (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 Qj⪰ϵIQ_j \succeq \epsilon I. When the two sets intersect, alternating projections converge to a point of the intersection, often slowly. The off-diagonal entries are scaled by 2\sqrt 2 in uu, so that the Euclidean distance on uu 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 ϵ/2\epsilon/2. 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 LDLTL D L^T with D≥0D \ge 0 shows that every QjQ_j 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 p=2x4+2x3y−x2y2+5y4p = 2x^4 + 2x^3 y - x^2 y^2 + 5y^4 and z=(x2,y2,xy)z = (x^2, y^2, xy), matching coefficients gives Q11=2Q_{11} = 2 from x4x^4, Q22=5Q_{22} = 5 from y4y^4, 2Q13=22Q_{13} = 2 from x3yx^3 y, 2Q23=02Q_{23} = 0 from xy3x y^3, and Q33+2Q12=−1Q_{33} + 2Q_{12} = -1 from x2y2x^2 y^2. One parameter is free:

Q(λ)=[2λ1λ5010−1−2λ].Q(\lambda) = \begin{bmatrix} 2 & \lambda & 1 \\ \lambda & 5 & 0 \\ 1 & 0 & -1 - 2\lambda \end{bmatrix}.

Every λ\lambda gives a matrix with zTQ(λ)z=pz^T Q(\lambda) z = p, and pp is a sum of squares exactly when some Q(λ)Q(\lambda) is positive semidefinite. For λ=0\lambda = 0 the last diagonal entry is −1-1, so that choice fails. For λ=−3\lambda = -3 the exact factorization gives D=(2,12,0)D = (2, \tfrac12, 0), rank 22, and the decomposition p=12(2x2−3y2+xy)2+12(y2+3xy)2p = \tfrac12 (2x^2 - 3y^2 + xy)^2 + \tfrac12 (y^2 + 3xy)^2. For λ=−2\lambda = -2 it gives D=(2,3,136)D = (2, 3, \tfrac{13}{6}), a positive definite matrix and a sum of three squares. The determinant is (λ+3)(2λ2−5λ−5)(\lambda + 3)(2\lambda^2 - 5\lambda - 5), and Q(λ)⪰0Q(\lambda) \succeq 0 exactly for −3≤λ≤(5−65)/4≈−0.766-3 \le \lambda \le (5 - \sqrt{65})/4 \approx -0.766. The implementation finds a positive definite member of this interval and returns its exact factorization.

The Motzkin polynomial. M(x,y)=x4y2+x2y4−3x2y2+1M(x, y) = x^4 y^2 + x^2 y^4 - 3x^2 y^2 + 1 is nonnegative: the arithmetic mean of x4y2x^4 y^2, x2y4x^2 y^4 and 11 is at least their geometric mean x2y2x^2 y^2. It is not a sum of squares. The Newton polytope of MM is the triangle with corners (0,0)(0,0), (4,2)(4,2) and (2,4)(2,4), so a square in a decomposition can only use the monomials 11, xyxy, x2yx^2 y and xy2x y^2. Of all products of two of these, only xy⋅xyxy \cdot xy equals x2y2x^2 y^2. So the coefficient −3-3 of x2y2x^2 y^2 must equal the diagonal entry Qxy,xyQ_{xy,xy}, 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 x˙1=x2\dot x_1 = x_2, x˙2=−x1−x2−x13\dot x_2 = -x_1 - x_2 - x_1^3. A quadratic V=ax12+bx1x2+cx22V = a x_1^2 + b x_1 x_2 + c x_2^2 cannot prove global asymptotic stability by this program: the quartic part of −V˙-\dot V is bx14+2cx13x2b x_1^4 + 2c x_1^3 x_2, which takes both signs unless c=0c = 0, and c=0c = 0 makes VV indefinite or degenerate. With VV in the span of x12x_1^2, x1x2x_1 x_2, x22x_2^2 and x14x_1^4, and the Gram basis (x1,x2,x12)(x_1, x_2, x_1^2) for both constraints, the program is feasible. One solution is

V=34x12+12x1x2+12x22+14x14,V˙=−12(x12+x22+x14).V = \tfrac34 x_1^2 + \tfrac12 x_1 x_2 + \tfrac12 x_2^2 + \tfrac14 x_1^4, \qquad \dot V = -\tfrac12 \left(x_1^2 + x_2^2 + x_1^4\right).

The quadratic part of VV has the matrix [3/41/41/41/2]\begin{bmatrix} 3/4 & 1/4 \\ 1/4 & 1/2 \end{bmatrix}, with pivots 34\tfrac34 and 512\tfrac{5}{12}, so VV is positive definite and radially unbounded. The implementation finds a certificate of this form with ϵ=1/100\epsilon = 1/100 in a few milliseconds, and the tests check along a simulated solution that VV decreases at every step.

Variations

  • Global lower bounds. The largest γ\gamma such that p−γp - \gamma is a sum of squares is a lower bound on min⁡xp(x)\min_x p(x), and it is exact when p−pmin⁡p - p_{\min} is a sum of squares, for example for every univariate pp. The dual of this program is a moment relaxation; Lasserre's hierarchy raises the degree step by step.
  • Nonnegativity on a set. To show p≥0p \ge 0 where g1(x)≥0,…,gm(x)≥0g_1(x) \ge 0, \dots, g_m(x) \ge 0, find sums of squares s0,…,sms_0, \dots, s_m with p=s0+∑isigip = s_0 + \sum_i s_i g_i. 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 gig_i is R2−∥x∥2R^2 - \|x\|^2. 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 −V˙−s(x)(β−V)-\dot V - s(x)(\beta - V) is a sum of squares with ss a sum of squares. Then V˙<0\dot V < 0 on the sublevel set V≤βV \le \beta. The product s⋅βs \cdot \beta 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 P(x)P(x) is a sum of squares if yTP(x)yy^T P(x) y is one in (x,y)(x, y). 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 66.
  • VV a sum of squares gives only V≥0V \ge 0, not a positive definite VV. Add the margin ϵ∥x∥2\epsilon \|x\|^2 or another positive definite term. This margin also excludes some correct Lyapunov functions: V=12x14+x22V = \tfrac12 x_1^4 + x_2^2 is not above ϵ(x12+x22)\epsilon (x_1^2 + x_2^2) 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 x˙=−x+xy\dot x = -x + x y, y˙=−y\dot y = -y. 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 QQ that satisfies the equations has a zero row and column for it, and no positive definite QQ exists. In the Lyapunov search, the constant monomial 11 in the basis for V−ϵ∥x∥2V - \epsilon\|x\|^2 has this problem, because V(0)=0V(0) = 0 forces Q11=0Q_{11} = 0. With such a basis the method of this page fails, and interior point solvers become inaccurate. Remove the monomials first.
  • The size grows as (n+dd)\binom{n+d}{d}. Ten variables with a quartic VV already need several matrices of size 6666, and degree 88 in ten variables needs size 10011001.

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.

sum_of_squares_programming.pyI0RawGitHub
# 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

  1. Show that x4+1x^4 + 1 is a sum of squares, and find all Gram matrices for z=(1,x,x2)z = (1, x, x^2). Which of them have rank 22?
  2. For the family Q(λ)Q(\lambda) above, verify the determinant (λ+3)(2λ2−5λ−5)(\lambda + 3)(2\lambda^2 - 5\lambda - 5) and show that Q(λ)⪰0Q(\lambda) \succeq 0 exactly for −3≤λ≤(5−65)/4-3 \le \lambda \le (5 - \sqrt{65})/4.
  3. Show that for a univariate polynomial pp of even degree, the largest γ\gamma such that p−γp - \gamma is a sum of squares equals min⁡xp(x)\min_x p(x).
  4. For x˙1=−x1+x2\dot x_1 = -x_1 + x_2, x˙2=−x13−x2\dot x_2 = -x_1^3 - x_2, show that V=12x14+x22V = \tfrac12 x_1^4 + x_2^2 gives V˙=−2x14−2x22\dot V = -2x_1^4 - 2x_2^2. Explain why the two constraints with the margin ϵ∥x∥2\epsilon \|x\|^2 reject this VV, and propose a margin that accepts it.
  5. Write the program for the Duffing example with VV in the span of x12x_1^2, x1x2x_1 x_2 and x22x_2^2 only, and prove by hand that it is infeasible for every ϵ>0\epsilon > 0.

References

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples