clear all; close all;
addpath(genpath('algorithm'))
randn('seed',2020); rand('seed',2020)

%set up
n=50;  
trails = 10;

% add varing outliers ratio and number of measurments
outlier_ratio_grid = 0.05:0.05:0.5; r_grid = 1:2:19;
error_gd = [];  error_apg = [];
for i = 1:length(outlier_ratio_grid)
    outlier_ratio = outlier_ratio_grid(i);
    for j = 1:length(r_grid)
        r = r_grid(j);
        parfor Num = 1:trails
            Uo = randn(n,r);
            L = Uo*Uo';
            
            %add outlier
            E = zeros(n,n);
            indx = randperm(n^2);
            m = ceil(outlier_ratio*n^2);
            E(indx(1:m)) = 10*randn(m,1);
            
            %observation
            X = L + E;
            
            % ------implicit regularization by gradient descent--------

            [U_gd,S_gd] = RPCA_gd_implicit(X);
            error_gd(i,j,Num) = (norm(U_gd*U_gd'-L,'fro')/norm(L,'fro')); 
            
            
            %----accelerated proximal gradient--
            [L_apg,S_apg] = partial_proximal_gradient_rpca(X);
            error_apg(i,j,Num) = (norm(L_apg-L,'fro')/norm(L,'fro'));
        end
        disp(['i = ', num2str(i), '/ ', num2str(length(outlier_ratio_grid)),' ... j = ', num2str(j), '/ ', num2str(length(r_grid))]);
    end
end

%%

succes_threshold = 0.1;

Flag_gd = zeros(length(outlier_ratio_grid),length(r_grid));
for i = 1:length(outlier_ratio_grid)
        for j = 1:length(r_grid)
            Flag_gd(i,j) = nnz(error_gd(i,j,:) < succes_threshold)/trails;
        end
end

Flag_apg = zeros(length(outlier_ratio_grid),length(r_grid));
for i = 1:length(outlier_ratio_grid)
        for j = 1:length(r_grid)
            Flag_apg(i,j) = nnz(error_apg(i,j,:) < succes_threshold)/trails;
        end
end

%
fontsize = 24;

figure;
imagesc(outlier_ratio_grid,r_grid,Flag_gd');
axis xy
 
set(gca,'XTick'      , outlier_ratio_grid)
set(gca,'YTick'      ,r_grid )
xlabel('$p$','FontSize',fontsize,'FontName','Times New Roman','Interpreter','LaTex');
ylabel('$r$','FontSize',fontsize,'FontName','Times New Roman','Interpreter','LaTex','rot',1)
set(gcf, 'Color', 'w')
set(gca,'FontSize',fontsize,'FontName','Times New Roman',...
    'Xtick',0.1:0.1:0.5,...
    'Ytick',1:4:19);
colormap(gray(256));
cbh = colorbar; set(cbh,'YTick',[0,1])


figure;
imagesc(outlier_ratio_grid,r_grid,Flag_apg');
axis xy
%fontsize = 14;
set(gca,'XTick'      , outlier_ratio_grid)
set(gca,'YTick'      ,r_grid  )
xlabel('$p$','FontSize',fontsize,'FontName','Times New Roman','Interpreter','LaTex');
ylabel('$r$','FontSize',fontsize,'FontName','Times New Roman','Interpreter','LaTex','rot',1)
set(gcf, 'Color', 'w');
set(gca,'FontSize',fontsize,'FontName','Times New Roman',...
    'Xtick',0.1:0.1:0.5,...
    'Ytick',1:4:19);
colormap(gray(256));
cbh = colorbar; set(cbh,'YTick',[0,1])


