Phase transition diagrams for the Basis Pursuit via the cvxopt package for linear programming (python 3)¶

$\newcommand{\eps}{\varepsilon}$ $\newcommand{\R}{\mathbb{R}}$ $\newcommand{\bR}{\mathbb{R}}$ $\newcommand{\cC}{\mathbb{C}}$ $\newcommand{\1}{{\rm 1}\kern-0.24em{\rm I}}$ $\newcommand{\inr}[1]{\bigl< #1 \bigr>}$ $\newcommand{\norm}[1]{\|#1\|}$ $\newcommand{\abs}[1]{\left|#1\right|}$ $\DeclareMathOperator*{\argmin}{argmin}$

In this notebook, phase transition diagrams of the $\ell_1$ minimization procedure Basis Pursuit (BP) are drawn for various type of random measurements matrices and also for matrices constructed from the cover by $3$-sets problem used to show that $\ell_0$-minimization is NP-hard.

An example of a phase transition diagram is as follows No description has been provided for this image In this example, we are interested in the reconstruction of sparse signals of size $N=100$. For every pixel indexed by a couple $(m,s)$ ($m$: number of measurements, $s$: sparsity parameter), we construct $15$ signals in $\R^N$ with sparsity $s$ and we observed $m$ linear measurements for each one of those signals. In the example, the measurement vectors were constructed from $N$ i.i.d. exponential symmetric random variables. Every time the Basis Pursuit procedure (implemented here via cvx LP solver) reconstructs all of the $15$ signals, a red pixel is drawn. When none of the $15$ signals are recovered a blue pixel is drawn. And for every results in between, an other color is drawn.

Phase transition diagrams are used for at least two reasons:

  1. compare procedures (like BP, IHT, OMP, etc) and algorithms used to implement those procedures
  1. compare measurement matrices (constructed from various random variables or structured measurements or determinsitic matrices)

The idea is that procedures / algorithms / measurement matrices are better when their phase transition curves (obtained when the number of failures becomes larger than the number of successes) are lower. For instance, below are plotted phase transition curves for various measurements matrices. No description has been provided for this image One can see that measurements matrices with exponential power $2$ are better.

In this notebook, we consider the Basis Pursuit procedure -- (BP). It can be recast to a linear program. We use the optimization library cvxopt to solve this linear program. An introduction to this library is provided for pedagogical purpose.

In [1]:
import numpy as np
import matplotlib.pylab as plt

%matplotlib inline

Compressed sensing -- presentation of the problem¶

In Compressed sensing, one is given a measurement matrice $A\in\R^{m\times N}$ and a measures vector $y=Ax$ of some unknown signal $x\in\R^N$. We want to reconstruct exactly $x$ given $y$ and $A$.

One way to look at this problem is as a highly underdetermined linear system: one has $m$ equations but $N>>m$ unknown variables. So what is going to save the day is that the signal to recover has a short support of size $s$ where $s<<N$.

A classical procedure is the Basis Pursuit: $$ \hat x \in\argmin_{t\in\R^N: At = y}\norm{t}_1.$$ This procedure is searching for the vector with the smallest $\ell_1$-norm in the set of solutions to the equation $Ax=y$.

Construction and representation of signals¶

In this section, we construct $s$-sparse vectors in $\R^n$ and find a good vizualization of those signals.

In [2]:
def signal(N, s):
    """Construct a signal of lenght n with s gaussian variables localized randomly and zeros everywhere else"""
    x = np.zeros(N)
    sel = np.random.permutation(N)[0:s]
    x[sel] = np.random.randn(s)
    return x
In [3]:
x = signal(100,15)
In [4]:
plt.stem(x)
titre = 'Représentation du vecteur x'
plt.title(titre)
Out[4]:
<matplotlib.text.Text at 0x108affb00>
No description has been provided for this image

Construction of measurements matrices¶

We construct various random measurement matrices:

  1. The first one is constructed using power of Gaussian random variables: that is the measurement matrix $A$ is populated with i.i.d. random variables like $${\rm sign}(g) |g|^p$$ where $g$ is a standard Gaussian variable and $p\geq1$ is some power.

  2. The second one are Student variable with degree $p$. That is a random variable absolutly continuous with a density of the order of $(1+t)^{-(p+1)}$.

In [5]:
def measurement_matrix(m, N, rand_type = "gauss", power = 2):
    if rand_type == "student":
        A = np.random.standard_t(power, size=(m, N))
    else:
        A = np.random.randn(m, N)
        A = np.multiply(np.power(np.absolute(A),power), np.sign(A))          
    return A    
In [6]:
A = measurement_matrix(2, 10, rand_type = "gauss")#, power = 4)

Basis Pursuit as a linear program¶

One can recast the Basis Pursuit procedure as a linear program.

Let $A\in\R^{m\times N}$ be a measurements matrix and $y\in\R^m$ be a measurements vector. We consider the following linear programming problem (LP):

$$\min_{z^+,z^-\in\bR^n} \sum_{j=1}^n z_i^+ + z_i^-$$

subject to $$ [A|-A]\left[\begin{array}{c} z^+\\ z^-\end{array}\right] = y \mbox{ and } \left[\begin{array}{c} z^+\\ z^-\end{array}\right]\geq 0 $$

For any $x\in\R^N$, we denote by $x^+\in\R^N$ and $x^-\in\R^N$ vectors with coordinates given for any $j=1,\ldots,N$ by \begin{equation*} (x^+)_j = \max(0,x_j) \mbox{ et } (x^-)_j = \max(0,-x_j). \end{equation*} There is equivalence between the Basis Pursuit procedure and (LP) in the following way:

If $\hat x$ is a solution to (BP) then $(\hat x^+, \hat x^-)$ is solution to (LP)

If $(\hat z^+, \hat z^-)$ is a solution to (LP) then $\hat z^+-\hat z^-$ is solution to (BP).

Import cvxopt library for solving linear programming problems¶

CVXOPT is a very powerfull library for solving various type of convex optimization problems. We refer to examples from Non-linear convex optimization and Xavier's TD9 .

solvers.cp solves non-linear convex optimization problems with twices differentiable objective and constraint functions with closed form solutions for the gradient and the Hessian.

Here we are concerned about Linear Programming -- that is for convex optimization problems where both the objective and the constraints are linear.

In [7]:
from cvxopt import matrix, solvers, sparse, sparse, spmatrix, spdiag
solvers.options['show_progress'] = False # No logs printed

matrix objects in cvxopt¶

cvxopt has its own matrix object which is different from the numpy's one

In [8]:
A = matrix([[1,2,3],[4,5,6]])
#print(A, '-'*10, '\n',  A[1,:], '-'*10, '\n', A[::-1,::-1], '-'*10, '\n', A[0:4])
#print('-'*10, '\n', A.size)
In [9]:
A = matrix([1, 2, 3, 4, 5, 6], (2,3))
B = matrix([ [1, 2], [3, 4] ])
C = matrix([ [A] ,[B], [-A]])
D = matrix(range(16),(4,4))
E = matrix(np.ones(5))
F = matrix(np.random.randn(2,3))
G = matrix(np.zeros(2))
#print(A,'-'*10, '\n', B, '-'*10, '\n', C, '-'*10, '\n', D, '-'*10, '\n', E, '-'*10, '\n', F, '-'*10, '\n', G)
In [10]:
A = matrix([[1,2,3],[4,5,6]])
B = np.array(A)
#print(A, '-'*10, '\n', B)

sparse matrix objects¶

cvxopti has its own sparse matrix object which is different from the scipy's one

In [11]:
E = spmatrix([1, 2], [0, 1], [0, 1], (4,2)) #(value, row, column)
B = matrix([ [1, 2], [3, 4] ])
F = sparse([ [B, B], [E] ])
G = spdiag([B, -B, 1, 2])
H = spdiag([1]*2)
K = matrix([B, -B])
K2 = matrix([[B], [-B]])
J = matrix([[B,-B, -H],[-B, B, -H]])
#print(E, '-'*30, '\n', F, '-'*30, '\n', G, '-'*30, '\n', H)
#print(K, '-'*30, '\n', K2, '-'*30, '\n', J)

Linear programming in cvxopt (cf. <a \href = 'http://cvxopt.org/userguide/coneprog.html#cvxopt.solvers.conelp'> cvxopt conelp solver and <a \href = 'http://cvxopt.org/userguide/coneprog.html#linear-programming'> cvxopt lp solver )

Linear Programming problems in cvxopt have the following form $$\min \inr{c,x} \mbox{ subject to } Gx + s =h, Ax=b, s\geq 0$$

CVXOPT command to solve this problem is

sol = cvxopt.solvers.lp(c, G, h[, A, b[, solver[, primalstart[, dualstart]]]])

sol = sol['x']

The solver argument is used to choose among three solvers. When it is omitted or None, the CVXOPT function conelp is used. The external solvers GLPK and MOSEK (if installed) can be selected by setting solver to 'glpk' or 'mosek'.

Using option 'glpk' speeds up cvxopt by a factor of $2$ or $10$ (cf. <a \href = 'https://scaron.info/blog/linear-programming-in-python-with-cvxopt.html'> Stéphane Caron's webpage )

Solving (BP) via cvxopt¶

Let $A\in\bR^{m\times N}$ and $y\in\R^m$. (LP) is defined by:

$$(\hat z^+, \hat z^-)\in\argmin_{(z^+,z^-)\in\bR^{2N}} \sum_{j=1}^n z_i^+ + z_i^- \mbox{ subject to } [A|-A]\left[\begin{array}{c} z^+\\ z^-\end{array}\right] = y \mbox{ and } \left[\begin{array}{c} z^+\\ z^-\end{array}\right]\geq 0 $$

Solution to (BP) is recovered via $t= \hat z^+- \hat z^-$.

Linear Programming problem considered in cvxopt have the following form:

$$\min \inr{c,x} \mbox{ subject to } Gx + s =h, Ax=b, s\geq 0.$$

In the case of (LP) :

$$c = \left[\begin{array}{c} \1 \\ \1 \end{array}\right]\in\R^{2N};\hspace{1cm} G=-I_{2N}; \hspace{1cm} h = 0\in\R^{2N}; \hspace{1cm} A = [A|-A]\in\R^{m\times 2N};\hspace{1cm} b = y\in\R^m$$

construction of cvxopt matrices $c, G, h, A, b$¶

In [12]:
def cvx_mat(A, y):
    '''A, y: numpy array or cvx matrices
    return parameters c, G, h, A, b for CVXOPT solvers.lp method'''
    A = matrix(A)
    y = matrix(y)
    m, N = matrix(A).size
    # matrix c, G, h, A, b
    c = matrix(np.ones(2*N))
    G = -spdiag([1]*2*N)
    h = matrix(np.zeros(2*N))
    A = matrix([[A],[-A]])
    b = y
    return c, G, h, A, b
In [13]:
N, m, s = 1000, 50, 3
A, x = measurement_matrix(m, N), signal(N, s) 
y = np.dot(A,x)
c, G, h, A, b = cvx_mat(A, y)
#print(c, '-'*10, '\n', G,'-'*10, '\n', h,'-'*10, '\n', A,'-'*10, '\n', b)

cvxopt linear solver cvx lp ¶

In [14]:
sol = solvers.lp(c, G, h, A, b, solver = 'glpk')
sol = sol['x']
x_recover = sol[0:N] - sol[N:2*N]
In [15]:
np.linalg.norm(matrix(x) - x_recover,2)
Out[15]:
8.3278185096902772e-16
In [16]:
def dist(x, sol):
    N = len(x)
    x_recover = sol[0:N] - sol[N:2*N]
    return np.linalg.norm(matrix(x) - x_recover,2)
In [17]:
N, m, s = 500, 80, 10
A, x = measurement_matrix(m, N), signal(N, s) 
y = np.dot(A,x)
c, G, h, A, b = cvx_mat(A, y)
sol = solvers.lp(c, G, h, A, b)
sol = sol['x']
x_recover = sol[0:N] - sol[N:2*N]
print('erreur ell_2 = {}'.format(dist(x, sol)))
erreur ell_2 = 1.4767102442127161e-08
In [18]:
fig, (subfig1,subfig2) = plt.subplots(1,2,figsize=(16,7)) # one figure with two horizontal subfigures
subfig1.stem(x)
subfig1.set_title('signal')
subfig2.stem(x_recover)
subfig2.set_title('reconstruction')
Out[18]:
<matplotlib.text.Text at 0x1078b7e10>
No description has been provided for this image

Performance comparison between solver with and without solver = 'glpk' option¶

In [19]:
N, m, s = 1000, 200, 30
A, x = measurement_matrix(m, N), signal(N, s) 
y = np.dot(A,x)
c, G, h, A, b = cvx_mat(A, y)
In [20]:
%timeit solvers.lp(c, G, h, A, b)
1 loops, best of 3: 299 ms per loop
In [21]:
%timeit solvers.lp(c, G, h, A, b, solver = 'glpk')
1 loops, best of 3: 1.97 s per loop

Phase transition diagrams for (BP)¶

We say that the reconstruction is a success when $||x-x_{recover}||_2\leq 0.001$

In [22]:
def phase_transition_mat(N, nbtest, rand_type = "gauss", power = 2):
    """return a n.n/2 matrix with the number of reconstruction success for every  1\leq m \leq n measurements 
    and sparsity 1\leq sparsity \leq n/2
    N : ambiant dimension of the signals
    nbtest : number of tests for each pixel"""
    PTM = np.zeros((N,int(N/2)))
    set_ind_failure = []
    for m in range(1,N+1):#construct one line of the Phase transition matrix for a given number of measurements m
        if (m % 20) == 0:
            print("line number {} done".format(m))
        M = measurement_matrix(m, N, rand_type, power)
        ind_failure = 0
        for sparsity in range(1,min(m+1, int(N/2))+1):
            nb_success = 0         
            for i in range(nbtest):
                x = signal(N, sparsity)
                y = np.dot(M,x)
                c, G, h, A, b = cvx_mat(M, y)
                sol = solvers.lp(c, G, h, A, b)
                sol = sol['x']
                if dist(x, sol) <= 0.001:
                    nb_success = nb_success + 1
            PTM[m-1, sparsity-1] = nb_success
    return PTM
In [23]:
def frontier(mat, nbtest):
    """construction of the phase transition frontier, i.e. first time the number of success goes below nbtest/2"""
    L = []
    N = len(mat)
    for s in range(int(N/2)):
        P = 0
        while mat[P,s]<nbtest/2 and P<N-1:
            P = P + 1
        L.append(P)
    return L
In [24]:
N, nbtest = 50, 16
mat = phase_transition_mat(N, nbtest)# construction of the matrix with the number of success among nbtest
line number 20 done
line number 40 done
In [25]:
P_min, P_max, S_min, S_max = 0, N, 0, int(N/2)
fig = plt.imshow(mat[P_min:P_max, S_min:S_max], interpolation="gaussian",  
                 aspect='auto', origin = 'lower', extent=[S_min, S_max, P_min, P_max])
plt.xlabel('sparsity')
plt.ylabel('number of measurements')

#empirical phase transition
X = range(int(N/2))
L = frontier(mat, nbtest)
plt.plot(X,L, linewidth=4, color = 'black', label='phase transition')
plt.legend(loc=4)

#filename = 'noisy_gaussian_{}_eps_{}.png'.format(n, eps)
#plt.savefig(filename,bbox_inches='tight')
Out[25]:
<matplotlib.legend.Legend at 0x10cf3ceb8>
No description has been provided for this image

Repeat the construction of the frontier nb_curves times to "smooth it"¶

nb_curves: number of phase transition curves constructed. Those curves are then averaged to "smooth" the effect of randomness in phase transition and get a "stable" phase transition

In [ ]:
#n, eps, nbtest = 100, 0.1, 16
nb_curves = 5
L = np.zeros(int(N/2))
for i in range(nb_curves):
    if (i % 10) == 0:
        print('step {} done'.format(i))
    mat = phase_transition_mat(N, nbtest)
    F = frontier(mat, nbtest)
    L = [sum(a) for a in zip(L,F)] 
L_gauss = [i/nb_curves for i in L]
step 0 done
line number 20 done
line number 40 done
line number 20 done
line number 40 done
line number 20 done
line number 40 done
line number 20 done
line number 40 done
In [403]:
#For next use, save the Gaussian phase transition frontier in a txt file 
#import pickle
#filename = 'phase_transition_diagram_N_{}_nbtest_{}_nbcurves.p'.format(N, nbtest, nb_curves)
#with open(filename, "wb") as f:
#    pickle.dump(L_gauss, f)

#import the phase transition diagram
#filename = 'phase_transition_diagram_N_{}_nbtest_{}_nbcurves.p'
#with open(filename, "rb") as inputfile:
#    L_gauss = pickle.load(inputfile)
#L_gauss = [int(float(ele[0])) for ele in L_gauss]

Draw the phase transition frontier of the Basis Pursuit procedure (via cvx.lp) for Gaussian measurements¶

In [407]:
X = range(len(L_gauss))
plot(X,L_gauss, linewidth=4, color = 'blue', label="Gaussian phase transition")

plt.xlabel('sparsity')
plt.ylabel('number of measurements')
plt.legend(loc=4)
#filename = 'gaussian_phase_transition_quantized_cs_{}_eps_{}.png'.format(n, eps)
#plt.savefig(filename,bbox_inches='tight')
No description has been provided for this image

Measurement matrices used in the proof of the NP-hardness of the $\ell_0$-minimization procedure¶

NP-hardness of the $\ell_0$-minimization procedure is based on a reduction principle. One can tranform the $\ell_0$-minimization problem in polynomial time into a "classical" NP-complete problem: the cover by $3$-sets problem.

Cover by $3$-sets problem: given a collection $\cC=\{C_1, \ldots, C_N\}$ of subsets of $\{1,\ldots,m\}$ all of cardinality $3$, is it possible to answer the question about the existence of a partition of $\{1,\ldots,m\}$ within this collection?

To prove that $\ell_0$-minimization problem can be reduced to the cover by $3$-sets problem, one can consider the following measurement vector $$ y = \left( \begin{array}{c} 1\\ 1\\ \vdots\\ 1\\ \end{array} \right) $$ and a measurement matrix: $$ A=[1_{C_1}| \cdots | 1_{C_N}] $$ where $1_{C_1}$ is a vector in $\R^m$ such that $(1_{C_1})_i = 1$ if $i\in C_1$ and $0$ if $i\notin C_1$.

One can see that a solution to the $\ell_0$-minimization procedure $\hat x_0$ obtained from $y$ and $A$ can be used to answer the cover by $3$-sets problem: if $\norm{\hat x_0}=m/3$ then there is a partition of $\{1,\ldots,m\}$ in the collection $\cC$; if $\norm{\hat x_0}>m/3$ then there is no such a partition (and one can show that necessarily $\norm{\hat x_0}\geq m/3$).

Hence solving the $\ell_0$-minimization procedure for this $y$ and $A$ can be reduced in polynomial time to a solution of an NP-complete problem (and so by definition $\ell_0$-minimization is an NP-Hard problem).

Phase transition of (BP) for the $0-1$ matrix $A$¶

We construct matrices $A$ introduced in the last paragraph in the two cases: either there is a partition and so the solution of the $\ell_0$-minimization problem should have a support of size $m/3$ either there is no partition and so $\hat x_0$ should have a strictly larger support.

We want to check the performances of (BP) in this setup. We expect it to fail otherwise this would give a polynomial time algorithm to solve an NP-hard problem.

In [51]:
def measurement_mat_partition(N, m, partition = 'yes', shuffling = 'yes'):
    A = np.zeros((m,N))
    if partition == 'yes':
        perm = np.random.permutation(m)
        perm_bis = np.random.permutation(N)
        for k in range(int(m/3)):
            ind = perm[3*k:3*k+3]
            if shuffling == 'yes':
                A[ind, perm_bis[k]] = [1, 1, 1]
            else:
                A[ind, k] = [1, 1, 1]
        for k in list(perm_bis[int(m/3):]):
            perm = np.random.permutation(m)
            ind = perm[0:3]
            A[ind, k] = [1, 1, 1]
    else:
        for k in range(N):
            perm = np.random.permutation(m-1)#we insure that there is no partition by removing the last element
            ind = perm[0:3]
            A[ind, k] = [1, 1, 1]
    return A
In [52]:
def measures_vectors(m):
    return np.ones(m)
In [55]:
N, m = 500, 3*20
A = measurement_mat_partition(N, m, partition = 'yes', shuffling ='no') 
y = measures_vectors(m)
c, G, h, A, b = cvx_mat(A, y)
sol = solvers.lp(c, G, h, A, b)
sol = sol['x']
x_recover = sol[0:N] - sol[N:2*N]
plt.stem(x_recover)
Out[55]:
<Container object of 3 artists>
No description has been provided for this image

Basis Pursuit does not work for this type of $0-1$ valued measurement matrices.

In [ ]: