%GANdemo.m
clear all 
close all 
%Generator 
z=[rand(1,1000)*2-1;ones(1,1000)]'; 
Walpha1=randn(2,50)*0.5;
Halpha=logsig(z*Walpha1);
Halpha=[Halpha ones(1000,1)];
Walpha2=randn(51,1)*0.5; 
xcap=logsig(Halpha*Walpha2); 
xori=random('exp',1,1,1000);
xori=xori/max(xori);
x=[xori xcap'];
t=[ones(1,1000) zeros(1,1000)]; 
[p,q]=sort(rand(1,2000));
x=x(q);
t=t(q);
%Update weights based on the output %from the discriminator as follows.
Wbeta1=randn(2,50)*1; 
Wbeta2=randn(51,1)*1; 
xmod=[x;ones(1,2000)]; 
for iteration=1:1:50 
    %Updating beta for discriminator 
    for iteration1=1:1:2 
        ycol=[]; 
        for n=1:1:2000 
            Hbeta=logsig(Wbeta1'*xmod(:,n));
            Hbeta=[Hbeta; 1]; 
            y=logsig(Hbeta'*Wbeta2);
            ycol=[ycol y]; 
            Wbeta2=Wbeta2+0.01*[t(n)-y]*Hbeta; 
            G1=(t(n)-y)*Wbeta2(:,1).*Hbeta.*(1-Hbeta);
            G1=G1(1:1:50);
            Wbeta1=Wbeta1+0.01*xmod(:,n)*G1';
        end
[mean(ycol(1:1:1000)) mean(ycol(1001:1:2000))]
    end
    %Updating alpha for generator 
 for iteration2=1:1:2 
     xcap=[];
     for n=1:1:1000 
         Halpha=logsig(Walpha1'*z(n,:)');
         Halpha=[Halpha; 1]; 
         temp=logsig(Halpha'*Walpha2); 
         xcap=[xcap temp]; 
         Hbeta=logsig(Wbeta1'*[temp 1]');
         Hbeta=[Hbeta; 1]; 
         y=logsig(Hbeta'*Wbeta2);
         temp1=Hbeta(1:1:50);
         temp2=y*(1-t(n+1000))*sum(temp1.*Wbeta2(1:50,1).* Wbeta1(1,:)');
         Walpha2=Walpha2+0.7*(Halpha'*temp2)'*temp*(1-temp);
         G1=temp2*Walpha2(:,1).*Halpha.*(1-Halpha)*temp* (1-temp);
         G1=G1(1:1:50);
         Walpha1=Walpha1+0.7*[z(n,:)]'*G1';
     end
 end
 Halpha=logsig(z*Walpha1); 
 Halpha=[Halpha ones(1000,1)]; 
 xcap=logsig(Halpha*Walpha2); 
 figure(1) 
 subplot(2,1,1) 
 plot(xori) 
 subplot(2,1,2)
 plot(xcap,'r')
 x=[xori xcap'];
 xmod=[x;ones(1,2000)];
 figure(2)
 subplot(5,1,2)
 [a1,b1]=hist(xori,20);
 stem(a1) 
 xcap=xcap/max(xcap);
 subplot(5,1,3) 
 [a2,b2]=hist(xcap,20);
 stem(a2)
 subplot(5,1,4)
 stem(a1./(a1+a2)) 
 subplot(5,1,1)
 [a4,b4]=hist(z(:,1),20);
 pause(0.5) 
 stem(a4,'r') 
 subplot(5,1,5) 
 [a5,b5]=hist(z(:,1),20);
 pause(0.5) 
 stem(a1./(a1+a5)) 
 end
