// Data clustering using a one-layer NN trained with WTA algorithm
function [nn,etichete]=WTA(a,b,K)
//[x,n]=generare(a,b,K); // randomly generated data
[x,n]=selectiePcte(a,b); // data points selection (right click - selection; left click - end)
nn=tlist(["retea WTA", "X","W","Y"],zeros(2,1),zeros(K,2),zeros(K,1));
disp(nn.W,"nn=");
C=init(x,n,K); // random selection of prototypes
nn.W=C';       // a row in the weight matrix = prototype
etichete=zeros(1,n);
disp(nn.W,"W=");
eta=0.1;
for t=1:100   // unsupervised training (Winner Takes All)
  for i=1:n   // loop on the training set
     imin=winner(nn,x(:,i));   // find the winning unit   
     nn.W(imin,:)=nn.W(imin,:)+eta*(x(:,i)'-nn.W(imin,:));  // weights adjustment
  end
  eta=eta*0.995;   // learning rate adjustment
  disp(t,"t="); disp(eta,"eta=");
end

clf;
plot(x(1,:),x(2,:),'ko');   // visualizing the points in the training set
culori=['ro','go','bo','ko','yo','co'];
culori2=['r*','g*','b*','k*','y*','c*'];
// data assignment to clusters
for i=1:n do
   etichete(i)=winner(nn,x(:,i)); // find the winning unit
end   
// visualization of the identified clusters 
for i=1:n do
    plot(x(1,i),x(2,i),culori(etichete(i)));
end

for k=1:K do
    plot(nn.W(k,1),nn.W(k,2));
end
endfunction

function imin=winner(nn,x)
        for k=1:K
           d(k)=dist(x,nn.W(k,:)');
        end   
        imin=1;
        for k=2:K
            if d(k)<d(imin) 
                imin=k;
            end
        end     
endfunction    

// search for an element
function rez=prezent(ind,m,i)
rez=0;
for j=1:m
    if ind(j)==ind(i) 
        rez=1;
    end
end    
endfunction        

// prototypes initialization
function C=init(x,n,K)
ind=zeros(1,K);
for i=1:K
    ind(i)=grand(1,1,"uin",1,n);
    //check if the prototype has been already selected 
    while prezent(ind,i-1,i)==1   
        ind(i)=grand(1,1,"uin",1,n);
    end
end    
for i=1:K
   C(:,i)=x(:,ind(i));
end   
disp(ind,"Selected indices:");
disp(C,"C=");
endfunction

// square of the euclidean distance
function d=dist(x,y)
n=length(x);
d=0;
for i=1:n
    d=d+(x(i,1)-y(i,1))^2;
end    
endfunction

// random data generation (the data in each cluster are generated using a normal 
//distribution with the mean in [a,b]x[a,b])
function [x,n]=generare(a,b,K)
x=[]; n=0; sigma=(b-a)/(8*K);
for k=1:K
  nr=grand(1,1,"uin",5,50);
  n=n+nr;
  xc=grand(1,1,"unf",a,b);
  yc=grand(1,1,"unf",a,b);
  for i=1:nr
    x=[x [grand(1,1,"nor",xc,sigma);grand(1,1,"nor",yc,sigma)]];
  end
end
endfunction

function [x,n]=selectiePcte(a,b)
   // data input
   clf;
   plot2d(0,0,0,rect=[a,a,b,b]);
   xgrid(3);
   p=locate(-1,1);   
   n=size(p,2); 
   x = p;
endfunction  

WTA(0,1,3)
