from defs import wavs
from defs import paths as pt
from defs import stats
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.decomposition import PCA


# klastrovani pomoci affinity propagation s vektorem priznaku
names = pt.listdir('data/_wavs')
stngs = wavs.Settings(sr=44100, frame_length=2048, hop_length=512)

# slozeni vektoru priznaku
for i, name in enumerate(names):
    fts_sts = stats.FeatsStats()
    fts_sts.load('data/' + pt.stat(name))
    stdevs, nms = fts_sts.get_stdev(set='corr')

    if i == 0:
        matrix = stdevs
    else:
        matrix = np.vstack((matrix, stdevs))

# skalovani od -1 do 1
min_max_scaler = sklearn.preprocessing.MinMaxScaler(feature_range=(-1, 1))
matrix_s = min_max_scaler.fit_transform(matrix)

model = sklearn.cluster.KMeans(n_clusters=4)
# model = sklearn.cluster.AffinityPropagation(random_state=None)
labels = model.fit_predict(matrix_s)

# serazeni kategorii
# lbls = np.array(names)[labels.argsort()]
# labels.sort()
# print(np.column_stack((names, labels)))

# graf serazenych kategorii
# plt.figure()
# plt.bar(range(len(labels)), labels)
# plt.xticks(ticks=range(len(labels)), labels=lbls)

# vzdalenostni matice
# plt.figure()
# plt.imshow(model.affinity_matrix_, cmap='hot')
# plt.colorbar()
# plt.grid('off')

# klastrovani pomoci affiniti s vektorem priznaku redukovanym pomoci analyzy hlavnich komponent
data = matrix

# transformace dat pomoci analyzy hlavnich komponent
pca = PCA(2)
df = pca.fit_transform(data)

# skalovani od -1 do 1
df = min_max_scaler.fit_transform(df)
model = sklearn.cluster.KMeans(n_clusters=4)
# model = sklearn.cluster.AffinityPropagation(random_state=None)
label = model.fit_predict(df)

# graf klastru
u_labels = np.unique(label)
plt.figure()
for i in u_labels:
    plt.scatter(df[label == i, 0], df[label == i, 1], label=i)
plt.legend()
plt.show()

# zarazeni nahravek do kategorii podle prvni a druhe metody
print(np.column_stack((names, labels , label)))


