% This code show how noise corrected correlation matrics are constructed and calculates decoding accuracy
%

Folder = '/home/sophie/Documents/DataSetToPutOnline';% modify depending on where you downloaded data to
addpath(genpath([Folder filesep 'Code']))
cd(Folder)

Structures = {'CC','ICE','IC','THE','TH','AC'};

for st = 1:length(Structures)
    
    disp(Structures{st})
    load(['Data_',Structures{st},'.mat'])
    
    % Just analyse data around the sound
    Start = find(t<0,1,'last');
    Stop = find(t>0.75,1,'first');
    Data = Data(:,Start:Stop,:,:);

    % Reorganize data for the time-independant code (neur by sound by trials)
    AmpResp = squeeze(nanmean(Data,2));
    % Reorganize data for the sequence code (neurxtimesteps by sound by trials)
    Data = permute(Data,[3,4,1,2]);
    Data = Data(1:end,1:end,:);
    Data = permute(Data,[3,1,2]);
    
    % Noise corrected correlation - sequence code
    [Corr_WiNs_Sq.(Structures{st}),Corr_NoNs_Sq.(Structures{st})] = Compute_similarity_matrix(Data,0);
    
    % Nearest neighbout decoding accuracy - sequence code
    [Acc_NN_Sq.(Structures{st}),Conf_NN_Sq.(Structures{st})] = Compute_accuracyNN_matrix(Data,0);
    clear Data
    
    % Noise corrected correlation - identity code
    [Corr_WiNs_Id.(Structures{st}),Corr_NoNs_Id.(Structures{st})] = Compute_similarity_matrix(AmpResp,0);
    
    % Nearest neighbout decoding accuracy - identity code
    [Acc_NN_Id.(Structures{st}),Conf_NN_Id.(Structures{st})] = Compute_accuracyNN_matrix(AmpResp,0);
    clear AmpResp
    
end
save([Folder, filesep, 'Correlation_' ...
    'Decoding.mat'],'Corr_WiNs_Sq','Acc_NN_Sq','Conf_NN_Sq','Corr_NoNs_Sq',...
    'Corr_WiNs_Id','Corr_NoNs_Id','Acc_NN_Id','Conf_NN_Id')

%
% Compare decoding and correlation

for s = 1:length(Structures)
    
    Corr_Av_Id(s) = nanmean(Corr_NoNs_Id.(Structures{s})(:));
    Corr_Av_Sq(s) = nanmean(Corr_NoNs_Sq.(Structures{s})(:));
    
    Acc_Av_Id(s) = nanmean(nanmean(Acc_NN_Id.(Structures{s})(:,2:end),1),2);
    Acc_Av_Sq(s) = nanmean(nanmean(Acc_NN_Sq.(Structures{s})(:,2:end),1),2);
    
    
end


figure
subplot(121)
plot(Corr_Av_Id,'.-','Color','k','linewidth',3,'MarkerSize',20)
hold on
plot(Corr_Av_Sq,'.-','Color',[0.6 0.6 0.6],'linewidth',3,'MarkerSize',20)
set(gca,'XTick',1:length(Structures),'XTickLabel',Structures)
ylabel('Mean correlation')
ylim([0 0.8]), xlim([0 7])

subplot(122)
Cols = {[0.4 0.4 0.4],[0.2,0.2,1],[0.2,0.2,1]*0.8,...
    [0.2,1,0.2],[0.2,1,0.2]*0.8,...
    [1,0.2,0.2]};
hold on
for i = 1:length(Structures)
    bar(i*3,Acc_Av_Sq(i),'FaceColor',Cols{i})
    bar(i*3+1,Acc_Av_Id(i),'FaceColor',Cols{i}*0.4)
end
ylim([0 1])
set(gca,'XTick',3.5:3:3*length(Structures)+1,'XTickLabel',Structures)
ylabel('Mean Accuracy')