% "FIR Filter Design via Spectral Factorization and Convex Optimization"
% by S.-P. Wu, S. Boyd, and L. Vandenberghe
% (figures are generated)
%
% Designs an FIR lowpass filter using spectral factorization method where we:
% - minimize maximum stopband attenuation
% - have a constraint on the maximum passband ripple
%
%   minimize   max |H(w)|                      for w in the stopband
%       s.t.   1/delta <= |H(w)| <= delta      for w in the passband
%
% We change variables via spectral factorization method and get:
%
%   minimize   max R(w)                        for w in the stopband
%       s.t.   (1/delta)^2 <= R(w) <= delta^2  for w in the passband
%              R(w) >= 0                       for all w
%
% where R(w) is the squared magnited of the frequency response
% (and the Fourier transform of the autocorrelation coefficients r).
% Variables are coeffients r. delta is the allowed passband ripple.
% This is a convex problem (can be formulated as an LP after sampling).
%
% Written for CVX by Almir Mutapcic 02/02/06

%*********************************************************************
% user's filter specs (for a low-pass filter example)
%*********************************************************************
% number of FIR coefficients (including the zeroth one)
n = 20;

wpass = 0.12*pi;   % end of the passband
wstop = 0.24*pi;   % start of the stopband
delta = 1;         % maximum passband ripple in dB (+/- around 0 dB)

%*********************************************************************
% create optimization parameters
%*********************************************************************
% rule-of-thumb discretization (from Cheney's Approx. Theory book)
m = 15*n;
w = linspace(0,pi,m)'; % omega

% A is the matrix used to compute the power spectrum
% A(w,:) = [1 2*cos(w) 2*cos(2*w) ... 2*cos(n*w)]
A = [ones(m,1) 2*cos(kron(w,[1:n-1]))];

% passband 0 <= w <= w_pass
ind = find((0 <= w) & (w <= wpass));    % passband
Lp  = 10^(-delta/20)*ones(length(ind),1);
Up  = 10^(+delta/20)*ones(length(ind),1);
Ap  = A(ind,:);

% transition band is not constrained (w_pass <= w <= w_stop)

% stopband (w_stop <= w)
ind = find((wstop <= w) & (w <= pi));   % stopband
As  = A(ind,:);

%********************************************************************
% optimization
%********************************************************************
% formulate and solve the magnitude design problem
cvx_begin
  variable r(n,1)

  % this is a feasibility problem
  minimize( max( abs( As*r ) ) )
  subject to
    % passband constraints
    Ap*r >= (Lp.^2);
    Ap*r <= (Up.^2);
    % nonnegative-real constraint for all frequencies (a bit redundant)
    A*r >= 0;
cvx_end

% check if problem was successfully solved
disp(['Problem is ' cvx_status])
if ~strfind(cvx_status,'Solved')
  return
end

% compute the spectral factorization
h = spectral_fact(r);

% compute the max attenuation in the stopband (convert to original vars)
Ustop = 10*log10(cvx_optval);
fprintf(1,'The max attenuation in the stopband is %3.2f dB.\n\n',Ustop);

%*********************************************************************
% plotting routines
%*********************************************************************
% frequency response of the designed filter, where j = sqrt(-1)
H = [exp(-j*kron(w,[0:n-1]))]*h;

figure(1)
% FIR impulse response
plot([0:n-1],h','o',[0:n-1],h','b:')
xlabel('t'), ylabel('h(t)')

figure(2)
% magnitude
subplot(2,1,1)
plot(w,20*log10(abs(H)), ...
     [0 wpass],[delta delta],'r--', ...
     [0 wpass],[-delta -delta],'r--', ...
     [wstop pi],[Ustop Ustop],'r--')
xlabel('w')
ylabel('mag H(w) in dB')
axis([0 pi -50 5])
% phase
subplot(2,1,2)
plot(w,angle(H))
axis([0,pi,-pi,pi])
xlabel('w'), ylabel('phase H(w)')
 
Calling Mosek 9.1.9: 1056 variables, 249 equality constraints
   For improved efficiency, Mosek is solving the dual problem.
------------------------------------------------------------

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            : 249             
  Cones                  : 228             
  Scalar variables       : 1056            
  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            : 249             
  Cones                  : 228             
  Scalar variables       : 1056            
  Matrix variables       : 0               
  Integer variables      : 0               

Optimizer  - threads                : 8               
Optimizer  - solved problem         : the primal      
Optimizer  - Constraints            : 21
Optimizer  - Cones                  : 228
Optimizer  - Scalar variables       : 792               conic                  : 456             
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 : 231               after factor           : 231             
Factor     - dense dim.             : 0                 flops                  : 2.36e+05        
ITE PFEAS    DFEAS    GFEAS    PRSTATUS   POBJ              DOBJ              MU       TIME  
0   2.3e+02  1.3e+00  1.0e+00  0.00e+00   0.000000000e+00   0.000000000e+00   1.0e+00  0.01  
1   7.7e+01  4.3e-01  3.1e-01  4.79e+00   -9.689817320e-01  -2.679040995e-01  3.4e-01  0.01  
2   1.8e+01  9.8e-02  1.9e-02  1.64e+00   -2.871570204e-01  -2.475512489e-01  7.8e-02  0.01  
3   8.3e+00  4.6e-02  3.3e-03  3.39e+00   -4.916078061e-02  -4.418477451e-02  3.7e-02  0.01  
4   2.1e+00  1.2e-02  3.2e-04  1.97e+00   -7.912557910e-03  -7.279261325e-03  9.5e-03  0.02  
5   3.7e-01  2.1e-03  2.1e-05  1.22e+00   -1.263634519e-03  -1.175928674e-03  1.6e-03  0.02  
6   8.7e-02  4.8e-04  2.2e-06  1.02e+00   -3.109323780e-04  -2.974930960e-04  3.8e-04  0.02  
7   3.3e-02  1.8e-04  4.1e-07  1.01e+00   -1.432630617e-04  -1.422573687e-04  1.5e-04  0.02  
8   2.6e-02  1.4e-04  2.7e-07  1.01e+00   -1.383673651e-04  -1.380079676e-04  1.1e-04  0.02  
9   7.3e-03  4.1e-05  3.2e-08  1.00e+00   -1.090134135e-04  -1.095447483e-04  3.2e-05  0.02  
10  3.1e-03  1.7e-05  7.8e-09  9.96e-01   -1.068189067e-04  -1.071657638e-04  1.4e-05  0.02  
11  4.7e-04  2.6e-06  3.7e-10  9.99e-01   -1.048900673e-04  -1.049575908e-04  2.1e-06  0.02  
12  6.6e-05  3.7e-07  1.3e-11  1.00e+00   -1.048298597e-04  -1.048420565e-04  2.9e-07  0.02  
13  2.9e-07  1.6e-09  2.4e-15  1.00e+00   -1.048366625e-04  -1.048367200e-04  1.3e-09  0.02  
Optimizer terminated. Time: 0.03    


Interior-point solution summary
  Problem status  : PRIMAL_AND_DUAL_FEASIBLE
  Solution status : OPTIMAL
  Primal.  obj: -1.0483666252e-04   nrm: 1e+00    Viol.  con: 1e-08    var: 6e-11    cones: 0e+00  
  Dual.    obj: -1.0483672002e-04   nrm: 1e+00    Viol.  con: 0e+00    var: 8e-11    cones: 0e+00  
Optimizer summary
  Optimizer                 -                        time: 0.03    
    Interior-point          - iterations : 13        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): +0.000104837
 
Problem is Solved
The max attenuation in the stopband is -39.79 dB.