function [Q2, RMSEP,REP, TXT]=CalculateQ2(Y,RES)
%calculates Q2 value from a leave-one-out or leave-group-out excersize
%Usage:
%[Q2, RMSEP,REP, TXT]=CalculateQ2(Y,YF)
%
%Inputs:
%Y(n)           :dependend variable
%YF(n)          :fitted values 
%RES(n)         :Residuals based on differences between measured and fitted values
%                based on LOO or LGO procedure
%Outputs:
%Q2             : Q2 statistic. Good models have positive Q2, bad models
%                 negative value. Can become smaller than -1!
%RMSEP          : Validation RMSE 
%REP            : Validation relative error of prediction
%TXT            : Textline showing results
%
%Dr AGT Schut March 2013

n=size(Y,1);

%STATISTICS
MY=mean(Y); %mean Y
SDY=std(Y);
 
vary = sum((Y-mean(Y)).^2) ./ n;
varr= sum(RES.^2) ./ n; %Mean squared error

%Q2 calculation
Q2 = (vary-varr) ./ vary;
% is exactly equal to Q2n= ( 1- sum( (y-yfit).^2 ) ./ sum( (y-mean(y)).^2 ) );
        
RMSEP=sqrt(varr);
    
REP =RMSEP ./ MY;%relative error
MQP= RMSEP ./ SDY;% error compared to SD. Good model has RMSE much smaller than SD

TXT = sprintf('VALIDATION STATS: Q2 %5.2f, RMSEP: %5.2f, RE: %5.2f RMSEP/SD: %5.2f', Q2,RMSEP,REP,MQP);
disp(TXT);


