global DISTM;
global X;
global L;
global N;
global D;



W = load ('../../data/mnist-original.mat');
X = W.data';
L = W.label;
[N,D]= size(X)
X = single(X);

perm = randperm(N)';
ind= perm(1:20000);
X = X(ind,:);
L = L(ind)';
N = size(X,1)
whos;%pause;

%y = kmeans(X',kseeds(X',10));

ind2 = find(L==2);  
ind7 = find(L==7); 
ind5 = find(L==5); 

%whos; pause;

% D = pdist (X);
% DIST = squareform(D);
% whos; pause;


%%%%%%%%%. PCA  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
% [C,P] = pca(X);
% size(P)
% X = P(:,1:50);
% [N,D]= size(X)
 
% X(find(X<50))=0;
% X(find(X>=50))=1;


% e = reshape(X(t,:),28,28)'
% image(e,'CDataMapping','scaled')
%pause;


%%%%%%% Euclidian distance fast
 X2 = dot(X,X,2);
%%%% euclidian
DIST_euclid_vip = bsxfun(@plus, X2, X2') - 2 * X * X';

DISTM = DIST_euclid_vip;

avd_dist = mean(mean(DISTM))
pause;
%t = 35678; L(t)
%[B,I] = mink(DIST_euclid_vip(t,:),10); Y(I) 



% %cosine
%  X2R = sqrt(X2);
%  X2Kron = kron(X2R,X2R');
%  XCOS = X*X' ./ X2Kron;
%  clear X2Kron;
%  format shortg
%
%
%  DISTM = XCOS*-1 + 1;




%[B,I] = maxk(XCOS(t,:),50); [I' Y(I) B']


%
% XS = sparse(double(X));
% XST = XS*XS';


% %edit distance loop
% ed = zeros(70000);
% for i=1:70000
% 	i
% 	E = bsxfun(@minus, X, X(i,:));
% 	ed(:,i) = sum(E~=0, 2);
% end;
%



%edit distance approx matrix multiplication
%  S=X;
%  S(find(S<=0))=-1;
%  S(find(S>0))=1;
% ed = S*S';
% ed = (784 - ed )/2;
% DISTM = ed;
% clear ed;
% whos


 
% figure(11)
%   plot3 (X3(ind5,1), X3(ind5,2), X3(ind5,3), 'g.')
%   grid on
%   hold on
%   plot3 (X3(ind2,1), X3(ind2,2), X3(ind2,3), 'r.')
%   plot3 (X3(ind7,1), X3(ind7,2), X3(ind7,3), 'b.')
%   pause;
 
 
 % y3 = kmeans(X3',kseeds(X3',10));
 % figure(2)
 % histogram(y3(ind2))
 %
 % X20 = P(:,1:20);
 % y20 = kmeans(X20',kseeds(X20',10));
 % figure(3);
 % histogram(y20(ind2))
 %
 % X100 = P(:,1:100);
 % y100 = kmeans(X100',kseeds(X100',10));
 % figure(4);
 % histogram(y100(ind2))
 %
 
 dbcolor = dbscan_alg(avd_dist/5, N/1000, avd_dist/5);
 
 figure(2); clf; 
 c = unique(dbcolor) 
 c = reshape(c,[1,length(c)])
 for t = c
 	ind = find(dbcolor==t);
 	plot3(X(ind,1), X(ind,2), X(ind,3),'.', 'markersize',10);
 	hold on; grid on;
 end;
