clc;
clear all;

% Compare the convergence rates of PGD and FNSL for low-rank transition matrices estimation

addpath(genpath('..\Software_Linear_Convergence_VAR'));

%%%%%Ambient dimension
d = 100;
%%%%%Number of measurements
n = 8000;
%%%%%Rank
r = 2;

%%%%%Repeated trials
T = 100;

%%%%%Initialization
errorFNSL = [];
errorPGD = [];

%%%%%Parallel processing
parfor tT = 1 : T
%%%%%Ordinary processing
% for tT = 1 : T

%%%%%Construct low-rank matrix
LL = randn(d, r);
LR = randn(d, r);

L = LL * LR';

%%%%%Rescaling
L = 0.9 * L / norm(L);

%%%%%Construct AR process
E = eye(d) * randn(d, n); 

x0 = zeros(d, 1);
[Y, xStart] = ARProduce(x0, L, E, n);

X = [xStart'; Y(:, 1: (n-1))'];

%%%%%Maximum iteration
kmax = 50;


%%%%%Initial point
D = norm(svd(L), 1);
A0 = D * eye(d,d);    %%%%%Stasify the requirement of PGD since the second step

[path_1, relative_error_1] = FNSL_lowrank(X, Y, A0, L, kmax, r);
[path_2, relative_error_2] = PGD_Lowrank(X, Y, A0, kmax, L);

errorFNSL = [errorFNSL; [norm(A0 - L, 'fro') / norm(L, 'fro'), relative_error_1]];
errorPGD = [errorPGD; [norm(A0 - L, 'fro') / norm(L, 'fro'), relative_error_2]];

end


figure(1)
ite=(1:size(errorFNSL,2));
curveFNSL = shadedErrorBar(ite, errorFNSL, {@mean,@std}, 'lineprops', '-b','patchSaturation',0.075);
curveFNSL.mainLine.LineWidth = 1.5;
hold on;
curveAltPGD = shadedErrorBar(ite, errorPGD(:, [1 : (size(errorPGD,2) - 1)]), {@mean,@std}, 'lineprops', '-r','patchSaturation',0.075);
curveAltPGD.mainLine.LineWidth = 1.5;


set(gca, 'YScale', 'log')
axis tight
xlabel('Iteration', 'fontsize',15)
ylabel('Relative error of \boldmath${\Gamma}$','interpreter','latex', 'fontsize',15)
legend('FNSL', 'PGD', 'fontsize',14);
grid on
