% plots performance (squared elementwise correlation) for 1 to 6 synergies for Autoencoder, PCA and NNMF
addpath('/home/hohlochj/masterarbeit/usedMcode')
pathToFile='/nfs/wsi/ti/messor/hohlochj/origData/';
% pathToFile='/home/jph/Uni/masterarbeit/origData/';
showFigure=true;
oneSubject=true;

EMGChannels={'AbdPolLo','Biceps','Triceps','FrontDelt','MidDelt','BackDelt'};
maxFile=5;
windowEMG=0.2;
windowShift=0.05;

maxSize=6;


[subjects,numbers]=namesAndNumbers(pathToFile);
numbersMat=cell2mat(numbers);
subjectsForNumbers=cell(size(numbersMat,2),1);
j=1;
for i=1:size(subjects,2)
    subject=subjects{i};
    for number=numbers{i}
        subjectsForNumbers{j}=subject;
        j=j+1;
    end
end

if oneSubject
    numbersMat=numbersMat(1);
    number=numbersMat(1);
    subject=subjectsForNumbers{1};
end

EMG=cell(size(numbersMat,2),1);

parfor j=1:size(numbersMat,2)
    EMG{j}=readEMGSig(pathToFile,subjectsForNumbers{j},numbersMat(j),...
        maxFile,windowEMG,windowShift,EMGChannels);
end

trainingData=cell2mat(EMG);


r2Autoenc=zeros([maxSize,size(trainingData,2)]);
ae=cell([maxSize,1]);
parfor i=1:maxSize
    ae{i}=trainAutoencoder(trainingData',i,'ShowProgressWindow',false);
    predicted=predict(ae{i},trainingData');
    r2Autoenc(i,:)=correlation2(trainingData,predicted');
end

%PCA
[COEFF,SCORE,~] = pca(trainingData,'Centered',false);
r2PCA=zeros([maxSize,size(trainingData,2)]);
parfor i=1:maxSize
    predicted=SCORE(:,1:i)*COEFF(:,1:i)';
    r2PCA(i,:)=correlation2(trainingData,predicted);   
end

%NNMF
r2NNMF=zeros([maxSize,size(trainingData,2)]);
parfor i=1:maxSize
    [W,H]=nnmf(trainingData,i);
    predicted=W*H;
    r2NNMF(i,:)=correlation2(trainingData,predicted);
end

if showFigure
    legendNames=EMGChannels;
    legendNames{size(EMGChannels,2)+1}='mean';
    fig=figure();
    subplot(1,3,1);
    plot([r2Autoenc,mean(r2Autoenc,2)])
    legend(legendNames','Location','SouthEast')
    title('Autoencoder')
    xlabel('number of syergies')
    ylabel('R^2')

    subplot(1,3,2);
    plot([r2PCA,mean(r2PCA,2)])
    legend(legendNames','Location','SouthEast')
    title('PCA')
    xlabel('number of syergies')
    ylabel('R^2')

    subplot(1,3,3);
    plot([r2NNMF,mean(r2NNMF,2)])
    legend(legendNames','Location','SouthEast')
    title('NNMF')
    xlabel('number of syergies')
    ylabel('R^2')
else
    if oneSubject
        save(strcat(pathToFile,sprintf('../matlabData/%s_noSyn%s%i.mat',datestr(datetime('now')),subject,number)));
    else
        save(strcat(pathToFile,sprintf('../matlabData/%s_noSynAll.mat',datestr(datetime('now')))));
    end
end