% KOHDEMO -- demo of Kohonen net learning
% Set the variable KohDataSet to one of the following:
%   KohDataSet = 1	Square distribution
%   KohDataSet = 2	Circular distribution
%   KohDataSet = 3	L-shape distribution
%   KohDataSet = 4	Triangular distribution
%   KohDataSet = 5	Square with cutout
%   KohDataSet = 6	Two blobs
%   KohDataSet = 7      Sine wave

% Copyright (c) 1997 David S. Touretzky

if ~exist('KohDataSet'), KohDataSet=4, end
Data = kohgenerate(KohDataSet);

if ~exist('GridSize'), GridSize = [9 9], end
if ~exist('InitNeighborhoodSize')
  InitNeighborhoodSize = 3	% scale factor for neighborhood gaussian
end
if ~exist('LearnRate'), LearnRate = 0.10, end
if ~exist('CollapseRate'),
  CollapseRate = 0.05		% rate of contraction of neighborhood size
end

NeighborhoodSize = InitNeighborhoodSize;
W = rand([GridSize 2]);
Iter = 0;
kohshow


% -----> Main Loop <-----
for Iter = 1:100
  if Iter>1, NeighborhoodSize = NeighborhoodSize * (1-CollapseRate); end
  Neighbs = kohneighbs(GridSize,NeighborhoodSize,LearnRate);

  for item = 1:size(Data,1);

    distx = W(:,:,1) - Data(item,1);
    disty = W(:,:,2) - Data(item,2);
    dist = distx.^2 + disty.^2;
    [v,k] = min(dist(:));   % k is the index of the winning unit
    [wi,wj] = kohcoords(k,GridSize);
    nmat = Neighbs{wi,wj};
    cnmat = 1 - nmat;

    W(:,:,1) = W(:,:,1).*cnmat + Data(item,1)*nmat;
    W(:,:,2) = W(:,:,2).*cnmat + Data(item,2)*nmat;

  end

  fprintf('%d..',Iter);
  kohshow

end
