close all, clear all, clc

%% KmeansClustering
% Skript slouzi k preduprave priznaku a k vytvoreni shluku pomoci metody 
% kmeans. Na konci skriptu se ulozi clusters.mat, ve kterem jsou ulozeny
% souradnice centroidu pro funkci FindMyClusters.
% 
% Na radku 8 je nutne do promenne filePath ulozit cestu v pocitaci, na
% ktere se nachazi dana data, title.mat a index.mat.
% 
% Pouzite funkce: FindAttributes - vyber priznaku pro shlukovani.
%
%%

filePath = 'C:\Users\zanet\Documents\BP\ready';

load([filePath '\titles.mat']); % titles = titles of files in cell array 100x1
number_files = size(titles, 1);

attributes = [];

%% loading 1 file

for i = 1 : number_files
    
    title1 = titles{i, 1};
    
    file = jsondecode(fileread([ filePath '\' title1 ]));
    
    %atributes for 1 file
    attributes = [attributes, FindAttributes(file)]; 
 
end
%% removal of outliers

attributes = attributes';
[attributes] =  rmoutliers(attributes,'percentiles',[5 95]);

%% standardization
% C, S - center and scale

[attributes, C, S] = normalize(attributes, 'zscore');

%% correlation plot

names_attr = {'CS1' 'CS2' 'CS3' 'CS4' 'CS5' 'PQ' 'QP' 'A' 'RMSSD' 'P:Q' 'U'};
figure;
[R, val] = corrplot(attributes, 'type', 'Pearson', 'rows', 'complete', 'varNames',  names_attr);

%% K-means

[idx, clusters, sumdist] = kmeans(attributes, 5, 'Distance', 'SqEuclidean', 'Display', 'final', 'MaxIter', 250, 'Replicates', 100); 

figure
[silh, h] = silhouette(attributes, idx, 'SqEuclidean');
xlabel('silueta')
ylabel('shluky')
title('Hodnoty siluet')

% average silhouette
silh_avg = mean(silh, 'omitnan');
disp(['Prumerna silueta je: ', num2str(silh_avg)])

% total of the within-cluster sums of point-to-centroid distances
disp(['Celkova suma vzdalenosti ve shlucich je: ', num2str(sum(sumdist))])

%% save clusters

save('clusters.mat', 'clusters')