
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Distributed under a 3-Clause BSD License 
%
% Copyright 2021 Lars Eldén, Linköping University, and Maryam Dehghan,
% Federal University of Ceará,
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%%%%%%%%%% Krylov Schur test Code of (1,2)-Symmetric Tensor %%%%%%%%%

format short
%%%%%%%%%%%%%%%%%%%%%%%%% Options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

options.maxitHOOI=5;
options.tolout=1e-12;
options.maxitNG=20;
options.tolin=1e-12;
options.maxit=100;
options.innerHOOI=5;

%% Starting vector for Krylov 
uStart=randn(n(1),1); uStart=1/norm(uStart)*uStart;

%% starting point of AOI method
for i=2:3
    X0_AOI{i}=orth(randn([n(i),r(i)]));
end
X0_AOI{1}=X0_AOI{2};

%% BKS (1,2)-symmetric Krylov-Schur

options.stage=input('Enter stage for BKS: ');
options.p=input('Enter p for BKS: ');
options.initHOOI=5;
options.innerHOOI=5;

tic
[Iu,Iw,UIu,WIw,U,W,OutConv,F]=BlockKrylovSchurSym(A,options);
time=toc;
% Save results for the plot for the paper
BKSF=F; BKSU=U; BKSW=W;  BKSRelGrad=OutConv;

timeBKS=time;


%%  HOOI for comparison

AOIIT=130; % max([maxIt modIt minIt]);
clear itstep
itstep=input('Itstep for HOOI [1]:   ');
if isempty(itstep), itstep=1; end
tolout=options.tolout;
tic
[XX1, f1, nn1,itaoi] = Sym_algAOI(A,X0_AOI,r',AOIIT,tolout,itstep);
timeHOOI1=toc;
aoiRelGrad=nn1/f1(end);


%% Plot convergence 
% First iterations
figure(13)
semilogy(itaoi,aoiRelGrad,'-.+b','LineWidth',1.7), hold on , 
semilogy(OutConv,'--r','LineWidth',1.7)
legend('HOOI','BKS')
xlabel('Iteration')
hold off


%% Check results

% disp(BKSU'*XX1{1})
% disp(BKSW'*XX1{3})
aoiF=ttm(A,XX1,'t');

disp(['Objective function: ' num2str([norm(BKSF) norm(aoiF)])  '    Difference: ' num2str(abs(norm(BKSF)-norm(aoiF)))])
disp(['Angles between subspaces (1,3), BKS-HOOI:  ' num2str([angles(BKSU,XX1{1}) angles(BKSW,XX1{3})])])

[eiggap1,eiggap3, condH] = CondBestSym3(A,{BKSU,BKSU,BKSW});
disp(['condH:    ' num2str(condH)])
disp(['gap1:     '  num2str(eiggap1)])
disp(['gap3:    ' num2str(eiggap3)]) 

 
 
 
