function [dqq,PRESSD] = DQ2(Ypred,Y)
% function DQ2 calculates the discriminant Q2 value adjusted for values that are larger then
% 1 for class 1 samples and smaller than 0 for 0 class samples.
% The idea is these values should not be penalized.
% NB: It is assumed y consists of ones and zeros indicating two classes
%
% [dqq,PRESSD] = DQ2(Ypred,Y)
% Y contains class labels (0 and 1)
% Ypred contains predicted Y values
% dqq = DQ2
% PRESSD contains the total squared error for discrimination
% JAW
% BDA/SILS/UvA, 1.09.2008


%Copyright 2008 Biosystems Data Analysis Group; Universiteit van Amsterdam
%
%This is a license to use and modify SOFTWARE  & DATA produced by:
%THE BIOSYSTEMS DATA ANALYSIS GROUP OF THE UNIVERSITEIT VAN AMSTERDAM

%If you use, modify or redistribute the SOFTWARE & DATA and/or your source modifications, you agree: 
%i)	to use the SOFTWARE & DATA and/or your source modifications solely as part of your research and not in any commercial product; 
%	
%ii)	that the SOFTWARE  & DATA and/or your source modifications will not be distributed for profit; 

%iii)	all copyright notices and this license note with the SOFTWARE & DATA are retained any  redistribution of the SOFTWARE & DATA, or any portion thereof; 
%
%(iv)	to indemnify, hold harmless, and defend the "Biosystems Data Analysis Group of the Universiteit van Amsterdam" from and against any claims or lawsuits that arise or result from the use of the SOFTWARE & DATA or your source modifications. 
%
%(v)	to properly reference the SOFTWARE & DATA when used in your reseach in any publication that may result from that research.
%	
%Reserved Rights. The "Biosystems Data Analysis Group of the Universiteit van Amsterdam" retain title and all ownership rights to the SOFTWARE & DATA.


Class0 = find(Y==0)            ;% Find values belonging to Class0
Class1 = find(Y==1)            ;% Find values belonging to Class1

E0 = Ypred(Class0)-Y(Class0)   ;% Calculate Residuals of Class0 samples
E1 = Ypred(Class1)-Y(Class1)   ;% Calculate Residuals of Class1 samples

E0count = find(E0>0)           ;% Find predictions for Class0 samples larger than 0
E1count = find(E1<0)           ;% Find predictions for Class1 samples larger than 1

SSE0 = E0(E0count)'*E0(E0count);% Calculate SSE for those samples of Class0
SSE1 = E1(E1count)'*E1(E1count);% Calculate SSE for those samples of Class1

PRESSD = SSE0 + SSE1           ;% Calculate total SSE for all samples = PRESSD

Ym = Y - mean(Y)               ;% Calculate Total sum of squares (over all samples)
TSS = Ym'*Ym                   ;

dqq = 1 - (PRESSD/TSS)         ;% Calculate DQ2
