% Section 6.2, Boyd & Vandenberghe "Convex Optimization"
% "Just relax: Convex programming methods for subset selection
%  and sparse approximation" by J. A. Tropp
% Written for CVX by Almir Mutapcic - 02/28/06
%
% We consider a set of linear inequalities A*x <= b which are
% feasible. We apply two heuristics to find a sparse point x that
% satisfies these inequalities.
%
% The (standard) l1-norm heuristic for finding a sparse solution is:
%
%   minimize   ||x||_1
%       s.t.   Ax <= b
%
% The log-based heuristic is an iterative method for finding
% a sparse solution, by finding a local optimal point for the problem:
%
%   minimize   sum(log( delta + |x_i| ))
%       s.t.   Ax <= b
%
% where delta is a small threshold value (determines what is close to zero).
% We cannot solve this problem since it is a minimization of a concave
% function and thus it is not a convex problem. However, we can apply
% a heuristic in which we linearize the objective, solve, and re-iterate.
% This becomes a weighted l1-norm heuristic:
%
%   minimize sum( W_i * |x_i| )
%       s.t. Ax <= b
%
% which in each iteration re-adjusts the weights W_i based on the rule:
%
%   W_i = 1/(delta + |x_i|), where delta is a small threshold value
%
% This algorithm is described in papers:
% "An Affine Scaling Methodology for Best Basis Selection"
%  by B. D. Rao and K. Kreutz-Delgado
% "Portfolio optimization with linear and �xed transaction costs"
%  by M. S. Lobo, M. Fazel, and S. Boyd

% fix random number generator so we can repeat the experiment
seed = 0;
randn('state',seed);
rand('state',seed);

% the threshold value below which we consider an element to be zero
delta = 1e-8;

% problem dimensions (m inequalities in n-dimensional space)
m = 100;
n = 50;

% construct a feasible set of inequalities
% (this system is feasible for the x0 point)
A  = randn(m,n);
x0 = randn(n,1);
b  = A*x0 + rand(m,1);

% l1-norm heuristic for finding a sparse solution
fprintf(1, 'Finding a sparse feasible point using l1-norm heuristic ...')
cvx_begin
  variable x_l1(n)
  minimize( norm( x_l1, 1 ) )
  subject to
    A*x_l1 <= b;
cvx_end

% number of nonzero elements in the solution (its cardinality or diversity)
nnz = length(find( abs(x_l1) > delta ));
fprintf(1,['\nFound a feasible x in R^%d that has %d nonzeros ' ...
           'using the l1-norm heuristic.\n'],n,nnz);

% iterative log heuristic
NUM_RUNS = 15;
nnzs = [];
W = ones(n,1); % initial weights

disp([char(10) 'Log-based heuristic:']);
for k = 1:NUM_RUNS
  cvx_begin quiet
    variable x_log(n)
    minimize( sum( W.*abs(x_log) ) )
    subject to
      A*x_log <= b;
  cvx_end

  % display new number of nonzeros in the solution vector
  nnz = length(find( abs(x_log) > delta ));
  nnzs = [nnzs nnz];
  fprintf(1,'   found a solution with %d nonzeros...\n', nnz);

  % adjust the weights and re-iterate
  W = 1./(delta + abs(x_log));
end

% number of nonzero elements in the solution (its cardinality or diversity)
nnz = length(find( abs(x_log) > delta ));
fprintf(1,['\nFound a feasible x in R^%d that has %d nonzeros ' ...
           'using the log heuristic.\n'],n,nnz);

% plot number of nonzeros versus iteration
plot(1:NUM_RUNS, nnzs, [1 NUM_RUNS],[nnzs(1) nnzs(1)],'--');
axis([1 NUM_RUNS 0 n])
xlabel('iteration'), ylabel('number of nonzeros (cardinality)');
legend('log heuristic','l1-norm heuristic','Location','SouthEast')
Finding a sparse feasible point using l1-norm heuristic ... 
Calling Mosek 9.1.9: 200 variables, 100 equality constraints
------------------------------------------------------------

MOSEK Version 9.1.9 (Build date: 2019-11-21 11:32:15)
Copyright (c) MOSEK ApS, Denmark. WWW: mosek.com
Platform: MACOSX/64-X86

Problem
  Name                   :                 
  Objective sense        : min             
  Type                   : CONIC (conic optimization problem)
  Constraints            : 100             
  Cones                  : 50              
  Scalar variables       : 200             
  Matrix variables       : 0               
  Integer variables      : 0               

Optimizer started.
Presolve started.
Linear dependency checker started.
Linear dependency checker terminated.
Eliminator started.
Freed constraints in eliminator : 0
Eliminator terminated.
Eliminator - tries                  : 1                 time                   : 0.00            
Lin. dep.  - tries                  : 1                 time                   : 0.00            
Lin. dep.  - number                 : 0               
Presolve terminated. Time: 0.00    
Problem
  Name                   :                 
  Objective sense        : min             
  Type                   : CONIC (conic optimization problem)
  Constraints            : 100             
  Cones                  : 50              
  Scalar variables       : 200             
  Matrix variables       : 0               
  Integer variables      : 0               

Optimizer  - threads                : 8               
Optimizer  - solved problem         : the primal      
Optimizer  - Constraints            : 100
Optimizer  - Cones                  : 50
Optimizer  - Scalar variables       : 200               conic                  : 100             
Optimizer  - Semi-definite variables: 0                 scalarized             : 0               
Factor     - setup time             : 0.00              dense det. time        : 0.00            
Factor     - ML order time          : 0.00              GP order time          : 0.00            
Factor     - nonzeros before factor : 5050              after factor           : 5050            
Factor     - dense dim.             : 0                 flops                  : 1.35e+06        
ITE PFEAS    DFEAS    GFEAS    PRSTATUS   POBJ              DOBJ              MU       TIME  
0   6.9e+00  0.0e+00  5.1e+01  0.00e+00   5.000000000e+01   0.000000000e+00   1.0e+00  0.00  
1   2.5e+00  1.2e-15  1.1e+01  1.52e-01   4.011789130e+01   1.918514069e+01   3.5e-01  0.01  
2   2.6e-01  5.7e-15  1.2e-01  9.60e-01   3.596246600e+01   3.398708338e+01   3.8e-02  0.01  
3   3.5e-02  3.4e-14  1.4e-02  1.17e+00   3.590440920e+01   3.566690230e+01   5.0e-03  0.01  
4   3.8e-03  2.2e-14  5.6e-04  1.03e+00   3.594107223e+01   3.591508466e+01   5.6e-04  0.01  
5   4.4e-04  5.1e-14  2.2e-05  1.01e+00   3.594136121e+01   3.593843210e+01   6.3e-05  0.01  
6   6.9e-05  2.1e-13  1.5e-06  1.00e+00   3.594075920e+01   3.594029396e+01   1.0e-05  0.02  
7   9.8e-06  5.6e-13  7.9e-08  1.00e+00   3.594077965e+01   3.594071398e+01   1.4e-06  0.02  
8   1.9e-08  3.0e-12  6.8e-12  1.00e+00   3.594077695e+01   3.594077682e+01   2.8e-09  0.02  
Optimizer terminated. Time: 0.02    


Interior-point solution summary
  Problem status  : PRIMAL_AND_DUAL_FEASIBLE
  Solution status : OPTIMAL
  Primal.  obj: 3.5940776947e+01    nrm: 2e+01    Viol.  con: 6e-08    var: 7e-09    cones: 0e+00  
  Dual.    obj: 3.5940776819e+01    nrm: 1e+00    Viol.  con: 0e+00    var: 6e-10    cones: 0e+00  
Optimizer summary
  Optimizer                 -                        time: 0.02    
    Interior-point          - iterations : 8         time: 0.02    
      Basis identification  -                        time: 0.00    
        Primal              - iterations : 0         time: 0.00    
        Dual                - iterations : 0         time: 0.00    
        Clean primal        - iterations : 0         time: 0.00    
        Clean dual          - iterations : 0         time: 0.00    
    Simplex                 -                        time: 0.00    
      Primal simplex        - iterations : 0         time: 0.00    
      Dual simplex          - iterations : 0         time: 0.00    
    Mixed integer           - relaxations: 0         time: 0.00    

------------------------------------------------------------
Status: Solved
Optimal value (cvx_optval): +35.9408
 

Found a feasible x in R^50 that has 44 nonzeros using the l1-norm heuristic.

Log-based heuristic:
   found a solution with 44 nonzeros...
   found a solution with 37 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...
   found a solution with 35 nonzeros...

Found a feasible x in R^50 that has 35 nonzeros using the log heuristic.