%==============================================================================
%    rand_control_mix.m
%    Copyright (C) 2007  Amoolya H. Singh, singh@embl.de
%
%    This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
%===============================================================================
function [avg, stdev, pval] = rand_control_mix(n, X1, X2, f, obs)
%------------------------------------------------------------------------------
%
% [avg, stdev, pval] = rand_control_mix(n, X1, X2, f, obs)
% continuously draws a mix of samples from sources X1 and X2 until
% either (1) a threshold number of samples (currently set to 1e+5)
% have been drawn, or (2) a sample is drawn whose value is greater
% than a given observation
%
% Input: 
%   n, number of rows (genes) of X to draw per sample
%   X1, data matrix from which to draw rows (genes from one species)
%   X2, data matrix from which to draw rows (genes from a second
%       species)
%   f, fraction of rows to draw from X1 (the rest from X2)
%   obs, threshold value determining when to stop sampling
% Output:
%   avg, average of all samples drawn
%   std, standard deviation of all samples drawn
%   pval, 1/actual number of samples drawn
%
%------------------------------------------------------------------------------

rand('state',sum(100*clock));

A = [];
count = 0; 
signif = 1e+5;

f1 = round(n*f)
f2 = n - f1

while (1)
  ind1 = ceil(rand(f1,1)*size(X1,1));
  ind2 = ceil(rand(f2,1)*size(X2,1));
  Y = [X1(ind1,:); X2(ind2,:)];
  m = mean(eudist(Y));
  if (m < obs || count == signif)
    ntrials = count;
    break
  else
    count = count + 1;
  end
  A = [A; m];
end

avg = mean(A);
stdev = std(A);

pval = 1/ntrials;
