from sklearn.cluster import KMeans
from sklearn import metrics
from sklearn.preprocessing import MinMaxScaler
import numpy as np
from kneed import KneeLocator
import matplotlib.pyplot as plt

x1 = np.array([3, 1, 1, 2, 1, 6, 6, 6, 5, 6, 7, 8, 9, 8, 9, 9, 8])
x2 = np.array([5, 4, 6, 6, 5, 8, 6, 7, 6, 7, 1, 2, 1, 2, 3, 2, 3])

# create new plot and data
plt.plot()
X = np.array(list(zip(x1, x2))).reshape(len(x1), 2)
colors = ['b', 'g', 'c']
markers = ['o', 'v', 's']

mms = MinMaxScaler()
mms.fit(X)
data_transformed = mms.transform(X)

Sum_of_squared_distances = []
K = range(1,10)
for k in K:
    km = KMeans(n_clusters=k)
    km = km.fit(data_transformed)
    Sum_of_squared_distances.append(km.inertia_)
    print(km.cluster_centers_)
    centers = np.array(km.cluster_centers_)


plt.plot(K, Sum_of_squared_distances, 'bx-')
plt.xlabel('k [-]')
plt.ylabel('opt(e) [-]')
plt.title('Vizualizace optimálního K')
plt.show()

kn = KneeLocator(K, Sum_of_squared_distances, curve='convex', direction='decreasing')
print(str(kn.knee))
print(str(kn.elbow))

# KMeans algorithm 
K = kn.elbow
km = KMeans(n_clusters=K).fit(X)
print(km.cluster_centers_)
centers = np.array(km.cluster_centers_)

plt.plot()
plt.title('Shluky v algoritmu K-means')
plt.xlabel('x [-]')
plt.ylabel('y [-]')

for i, l in enumerate(km.labels_):
    plt.plot(x1[i], x2[i], color=colors[l], marker=markers[l],ls='None')
    plt.xlim([0, 10])
    plt.ylim([0, 10])

plt.scatter(centers[:,0], centers[:,1], marker="x", color='r')
plt.show()

print(" ")

clist = centers.tolist()
print(str(clist[1][1]))
