% Non-negative CCA. 
%
%The algorithm is described in paper W. Wang, T. Adali, and D. Emge, “Unsupervised 
% detection using canonical correlation analysis and its application to 
% Raman spectroscopy,” in Proc. IEEE Workshop on Machine Learning for 
% Signal Processing,  Thessaloniki, Greece, Aug. 2007.

% Wei Wang, 01/30/2007

function [A,B,r]=CCA_nonnegative(x,y)
[lx,n]=size(x);
[ly,m]=size(y);
if lx~=ly
    disp('The size of x and y are not matched!');
    stop;
end

x=x-ones(lx,1)*mean(x);
y=y-ones(lx,1)*mean(y);

Pc=x*inv(x'*x)*x';

tol=1e-7;
if n==1    
    [p,idx]=NonNegativeLS(y,x);
    if norm(p)<1e-7
        A=1;
        B=0;
        r=0;
    else
        A=1;
        B=p/norm(p);
        r=corr2(x,y*p);
    end
    return;
else
    a=sum(x')';
end

maxitrnum=200;
count=0;
pre_a=0;
pre_b=0;
flag_allnegative=0;
while 1
    count=count+1;
    
    [p,idx]=NonNegativeLS(y,a);
    if sum(idx)==0
%        disp('No positive projection exists!!!');
        flag_allnegative=1;
        break;
    end
%    idd(count,:)=idx';
    b=y*p;
    b=b/norm(b);
    
    a=Pc*b;
    a=a/norm(a);

%    r(count)=corr2(a,b);
    
    tola=norm(a-pre_a);
    tolb=norm(b-pre_b);
    
    if (tola < tol) & (tolb < tol)
        break;
    elseif count>maxitrnum
        break;
    end
    pre_a=a;
    pre_b=b;
end
if flag_allnegative==1
   disp('No positive projection exists!!!');
   A=zeros(n,1);
   B=zeros(m,1);
   r=0;
   return;
end

yy=y(:,idx');
%[A,B,rr]=canoncorr(x,y)
[AA,BB,rr] = canoncorr(x,yy);
A=AA(:,1);
B1=BB(:,1);
r=rr(1);
if abs(r-corr2(a,b))>1e-3
    disp('Something is wrong in CCA_nonnegative positon 1 !!!');
end


signb=sum(sign(B1));
if (signb~=length(B1) & signb~=-length(B1))
    disp('Something is wrongin CCA_nonnegative position 2 !!!!');
end

B1=abs(B1)/norm(B1);
if signb==-length(B1)
    A=-A/norm(A);
end
B=zeros(m,1);
B(idx)=B1;
% bn=B1(:,1)/norm(B1(:,1));
% pn=p(idx)/norm(p(idx));
% nfb=norm(abs(bn)-pn);
% nrr=abs(r(count)-r1(1));


