% function [SP SS AC NERRORS] = calcPerformance(A, T2) 
% Calculate the specificity (SP), sensitivity (SS), accuracy (AC)
%   A - Neural network output
%   T2 - Target of Test matrix (just one column)
%
% Copyright 2007-2008 Rui P. Costa (http://student.dei.uc.pt/~racosta)
%
function [SP SS AC NERRORS] = calcPerformance(A, T2) 
%Classes:
%1 - Normal state
%2 - Pre-ictal 
%3 - Ictal
%4 - Pos-ictal
%T2 - Must have 1 column and n rows with the classes
    NORMAL=1;
    PREICTAL=2;
    ICTAL=3;
    POSICTAL=4;        
                
    %0 Calc the total number of errors and corrects
    NERRORS=zeros(4);
    CORRECTS=zeros(4,1);
    for i=1:length(A(1,:))
        aux=find(A(:,i)==max(A(:,i)));
        NERRORS(T2(i),aux(1))=NERRORS(T2(i),aux(1))+(T2(i)~=aux(1));
        CORRECTS(T2(i))=CORRECTS(T2(i))+(T2(i)==aux(1)); %Add the correct situations
    end

    %1 Calc TP, TN, FP, FN
    %1.1 True Negatives
    TN_NORMAL=(CORRECTS(NORMAL)+NERRORS(ICTAL,NORMAL)+NERRORS(POSICTAL,NORMAL));
    TN_ICTAL=(NERRORS(NORMAL,ICTAL)+CORRECTS(ICTAL)+NERRORS(POSICTAL,ICTAL));
    TN_POSICTAL=(NERRORS(NORMAL,POSICTAL)+NERRORS(ICTAL,POSICTAL)+CORRECTS(POSICTAL));
    TN=TN_NORMAL+TN_ICTAL+TN_POSICTAL;
    disp({'Neg Verdadeiros=' TN});

    %1.2 False Negatives
    FN=NERRORS(PREICTAL,NORMAL)+NERRORS(PREICTAL,ICTAL)+NERRORS(PREICTAL,POSICTAL);
    disp({'Neg Falsos=' FN});

    %1.3 True Positives
    TP=CORRECTS(PREICTAL);
    disp({'Pos Verdadeiros=' TP});

    %1.4 False Positives
    FP=NERRORS(NORMAL,PREICTAL)+NERRORS(ICTAL,PREICTAL)+NERRORS(POSICTAL,PREICTAL);
    disp({'Pos Falsos=' FP});


    %2. Metrics
    %2.1 Calc the sensitivity (TP/TP+FN)
    SS = (TP/(TP+FN))*100; 

    %2.2 Calc the specificity (TN/TN+FP)
    SP = (TN/(TN+FP))*100;  
    
    %2.3 Calc the classifier precision (CORRECT/TOTAL)
    CORRECT=sum(CORRECTS);
    TOTAL=length(T2);
    AC = (CORRECT/TOTAL)*100;


    SS
    SP
    AC
    NERRORS
    CORRECTS
    end    
    