% AREA = ROCarea(POSITIVE_SCORES, NEGATIVE_SCORES, DOPLOT)
% 
% AREA is the area under the ROC curve, POSITIVE_SCORES is a vector of the
% scores of the positive data, NEGATIVE_SCORES is a vector of the scores of
% the negative data.
% Set DOPLOT to be non-zero if you want a plot.
%
% Assumes that a higher score means more likely to be positive.
%
% (c) copyright Vladimir Jojic and Quaid Morris, 2003.

function [area, xcoord, ycoord] = ROCarea(posscores, negscores, doplot)

all = [posscores(:)' negscores(:)'];
all = sort(all);
thres(1) = min(all)-1;
thres(2:length(all)) = (all(2:length(all))+all(1:length(all)-1))/2;
thres(end+1) = max(all)+1;

np = length(posscores);
nn = length(negscores);

for ii = 1:length(thres)
  TP(ii) = length(find(posscores > thres(ii)));
  FP(ii) = length(find(negscores > thres(ii)));
  FN(ii) = np - TP(ii);
  TN(ii) = nn - FP(ii);
  Sens(ii) = TP(ii)/(TP(ii)+FN(ii));
  Spec(ii) = TN(ii)/(FP(ii)+TN(ii));
  xcoord(ii) = 1-Spec(ii);
  ycoord(ii) = Sens(ii);
end
sorted = sortrows([xcoord(:) ycoord(:)]);
xcoord = sorted(:,1);
ycoord = sorted(:,2);

dx = diff(xcoord);
my = (ycoord(1:end-1)+ycoord(2:end))/2;
area =  sum(dx .* my);

if nargin == 3 & doplot
  plot(xcoord, ycoord, 'linewidth', 3);
  xlabel('1-Specificity');
  ylabel('Sensitivity');
  hold on;
  plot([0 1], [0 1], '--');
  axis square;
  hold off;
end

