% racuna centroide projiciranih koeficijenata.
% takodjer vraca prosjecnu distorziju svakog clustera

function [centroids, distorsion] = get_centroids(coeffs, nr_clusters) 


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   projekcija podataka (niza koeficijenata) na jedinicnu sferu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

space_size = size(coeffs);
for c1 = 1 : space_size(1),
    proj_coeffs(c1,:) = double(coeffs(c1,:)./norm(coeffs(c1,:), 'fro'));
end
proj_coeffs(:,:) = abs(proj_coeffs(:,:));
% moze se zbog simetrije; centralna projekcija kroz centar jedinicne sfere je abs


%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   c-means clust
%%%%%%

[centroids, clust_matrix, obj_f] = fcm(proj_coeffs,nr_clusters);
[X,clust_index] = max(clust_matrix);
clusters = cell(1,nr_clusters);
%organizacija koeficijenata po clusterima:
for c1 = 1 : space_size(1), 
    temp = clust_index(c1);
    clusters{temp} = [clusters{temp}(:,:); proj_coeffs(c1,:)];
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% distorzija unutar pojedinacnih clustera  
%%%%%%%%%%%%%%%%%%%%

%theta = cell(1, nr_clusters);
for c1 = 1 : nr_clusters,
    distorsion(c1,:) = sum(distfcm(centroids(c1,:), clusters{c1}));
    % alternativna mjera je sa theta
    %centroids(c1,:) = double(centroids(c1,:)./norm(centroids(c1,:), 'fro'));
    %theta{c1} = acos(centroids(c1,:)*clusters{c1}'); %/(1*1)  
    %nr_points = size(clusters{c1});
    %distorsion(c1) = sum(theta{c1})/nr_points(1);
end
distorsion = sum(distorsion)/nr_clusters;

% plotanje (za nr_mixtures = 2)
%figure, plot(clusters{1}(:,1),clusters{1}(:,2), 'r.')
%hold, plot(centroids(1,1), centroids(2,1), 'rp'),
%plot(clusters{2}(:,1),clusters{2}(:,2), 'b.'),
%plot(centroids(1,2), centroids(2,2), 'bp')