%Ekta Gujral,Ravdeep Pasricha , Vagelis Papalexakis 2017
%Computer Science and Engineering, University of California, Riverside
%Demonstrating the use of the SambaTen algorithm, using samplaing based
%approach for online tensors
clear all;close all;clc;
load('sampledata.mat');
X=sptensor(X);

%% Parameter for SamBaTen
F = 5; %default
batchsize=10;sample_factor = [2 2 2];
repetitions =1;nonneg = 0;dims=size(X);
I=dims(1);J=dims(2);K=dims(3);incTime=zeros(5,1);
X_init=X(:,:,1:batchsize);
%% Tensor decomposition for existing Tensor.
disp('Initialization');
[FacMat, lambda_old, fixed_1] = SamBaTen_start(X_init,F,sample_factor,nonneg);
fixed_old=fixed_1;
t=1;
%% incremental decomposition .
 for i=batchsize+1:batchsize:K
            if(i+batchsize-1>dims(3))
             batchsize=dims(3)-i+1;
            end
        
         % geting samples from previous data
           X_new=X(:,:,i:i+batchsize-1);
          [Xs]=Slicing(X_init,X_new,fixed_old);
          disp('Processing new slice');
          st=tic;
          [FacMatnew, lambda_2, fixed_2] = SamBaTen(Xs,F,sample_factor,repetitions,nonneg);
          incTime(t,1)=toc(st);
          [A, B ,C ,lambda]=getMergeData(FacMat,FacMatnew,X(:,:,1:i+batchsize-1),fixed_2,lambda_2);
         t=t+1;
         FacMat{1}=A;FacMat{2}=B;FacMat{3}=C;
         X_init=Xs;
       fixed_old=fixed_2;
end
    totaltime=sum(incTime);
    Xorg=sptensor(X);
    Xinc=ktensor(lambda,A,B,C);
    [rerror,fitness] = relativeError(Xorg,(Xinc)); % error=1-(||Xinc||/||Xorg||), fitness=1-{(||Xorg||-||Xinc||)/||Xorg||}
    fprintf('Total time taken: %5.3f seconds, Error :%6.6f \n.',totaltime,rerror);
   

