%% DNN ANALYSIS
%dnnType: AlexNet_avg

%%%%%%%%%%%%%%%%%%%% PREPARE ANALYSIS PARAMETERS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
function DNN_BtwItem_Analysis(atlasType,atlasIdx,dnnType)
    %% ANALYSIS parameters
    all_subjects = [1:22 24:28 30:37 39:49]; %%%  exclude 23 and 29 for negative d' and 38 for different stimset and 2nd time implant
    load(['..\subject_list.mat']);
    fs = '\';
    %set colormap
    cmap = flipud(cbrewer('div','RdBu',51)); cmap(cmap>1) = 1; cmap(cmap<0) = 0;

    %% RSA sliding window settings
    rsawidth = 300; %window size
    rsastep = 50;   %window slide step
    maxT = 1500;    %max time
    %set directory names for storing (ers settings)
    rsa_tag = [num2str(rsawidth) 'width_' num2str(rsastep) 'step_' num2str(maxT) 'ms'];

    %% ROI (Define ROI for which to compute ERS analysis)
    %atlasType = 'BA'; % 'BA' for Brodmann, or 'HO' for HarvardOxford
    %atlasIdx = [17 18];

    %set directory names for storing (roi selection)
    if strcmp(atlasType,'BA')
        roi_tag = [atlasType char(replace(join(string(atlasIdx)),' ','_'))];
    elseif strcmp(atlasType,'HO')
        %load dir_labels and not numbers for HO naming
        load(['F:\iEEG_PFC\ECoG_MemDev\ATLAS\HarvardOxford\labels_both.mat']);
        fileTag_labels = labels(atlasIdx,3);
        roi_tag = [atlasType '_' char(replace(join(fileTag_labels),' ','_'))];
    end

    %% find all subjects that contribute to current ROI analysis
    [subjects,numChans,channels] = FindSubjOfROI(all_subjects,atlasType,atlasIdx,'both','all');
    disp([num2str(length(subjects)) ' subjects contribute ' num2str(sum(numChans)) ' channels in ' roi_tag])
    %for all further analyses run from this script, only subjects who
    %contribute channels are included!

    %%%%%%%%%%%%%%%%% CONDUCT ANALYSES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Between Item Similarity

    %computes stimXstim similarity matrices across channels and freqs
    %for each timestep of sliding window of rsa settings
    %separately for encoding and recognition
    %trial order is sorted by memory and category

    for num = 1:length(subjects)
        %check whether BtwItem Similarity of rsa features and for roi
        %already exists!
        file_dir = ['..\Data' fs subNames{subjects(num)} fs 'stats' fs 'BtwItem' fs rsa_tag fs roi_tag];
        if ~exist([file_dir fs 'BtwInfo.mat'],'file')
            BetweenItemSimilarity(subjects(num),channels{num},atlasType,atlasIdx,rsawidth,rsastep,maxT,rsa_tag,roi_tag);
        else
            disp(['Between Item Similarity Matrices of ' subNames{subjects(num)} ' already exist'])
        end
    end

    %% DNN Between Item Similarity
    % prepare subject-specific dnn between item similarity matrices
    % load dnn preds of all pairwise stimuli from experiment and reduce to
    % subj-specific trials in same order
    %dnnType = 'AlexNet_avg';
    dnnCorrType = 'spearman';

    STIMINFO = readtable('..\STIMINFO_040322.csv');

    for num = 1:length(subjects)
        DNNpredictorMatrices(subjects(num),dnnType,dnnCorrType,rsa_tag,roi_tag,STIMINFO)
    end

    %% First-level Between Item Similarity of Neural and DNN predictions across VVS
    % estimate degree of similarity of between item representations between
    % neural and dnn data
    % correlate whole matrices, and separately for remembered and forgotten
    % items
    % permutation shuffle within memory and category fields to control for
    % differences in pairwise sims within categories
    disp([' ----- FIRST LEVEL STATS ----- '])
    tic
    nrep = 1000;
    for num = 1:length(subjects)
        DNN_first_level_item(subjects(num),dnnType,nrep,dnnCorrType,rsa_tag,roi_tag)
    end
    disp(['first level stats took ' num2str(toc/60) ' minutes'])

    %% Second-level stats Between Item similarity
    disp([' ----- SECOND LEVEL STATS ----- '])
    DNN_second_level_item(subjects,dnnType,dnnCorrType,rsa_tag,roi_tag,nrep)
    
    %% plot results
    %DNN_plot_results(dnnType,'spearman',rsa_tag,roi_tag,'pos','enc','mem')
end

%plot results
%encoding
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA17_18_19','pos','enc','mem')
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA37','pos','enc','mem')
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA20','pos','enc','mem')
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA39_40','neg','enc','mem')
%recognition
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA17_18_19','pos','rec','mem')
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA37','pos','rec','mem')
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA20','pos','rec','mem')
%%% DNN_plot_results('AlexNet_avg','spearman',rsa_tag,'BA39_40','neg','rec','mem')

