
import json
import numpy as np
import matplotlib.pyplot as plt

#--------------------------------------
#USER PARAM
#--------------------------------------
file_name='01-cluster_data.json'
n_clusters=3

#--------------------------------------
#LOAD DATA 
#--------------------------------------
f = open(file_name,)
data = json.load(f)

#CONVERT TO NUMPY ARRAY WITH 2 COLUMNS 
x=[]; y=[]; true_label=[]
for i in data.keys():
	x=x+data[i][0]
	y=y+data[i][1]
	for j in range(0,len(data[i][0])): true_label.append(int(i))
labels=np.array(true_label) #.reshape(len(true_label), 1)
X=np.transpose(np.array([x,y]))

#PLOTTING FUNCTION
def plot(title=''):
	#PLOT KMEANS LABELS
	fig, ax = plt.subplots()
	sp=ax.scatter(X[:,0], X[:,1],c=labels,marker=".", cmap="viridis")
	plt.colorbar(sp)
	plt.title(title)
	plt.show()

plot('CORRECT LABELS')

#--------------------------------------
#KMEANS (PARTITION BASED METHOD)
#--------------------------------------
print("---------KMEANS-----------")

from sklearn.cluster import KMeans
import numpy as np

# X = np.array([[1, 2], [1, 4], [1, 0],
#               [10, 2], [10, 4], [10, 0]])
print("X SHAPE:", X.shape)

#TEST WITH n_clusters=2
n_clusters=2
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
labels=np.array(kmeans.labels_)
#EXPLORE SELECT OBJECT ATTRIBUTIES 
print("n_iter_:",kmeans.n_iter_)
print("n_features_in_:",kmeans.n_features_in_)
print("cluster_centers_:",kmeans.cluster_centers_)
print("inertia_:",kmeans.inertia_)
print("PREDICTION-1:", kmeans.predict([[0, 0]]))
print("PREDICTION-2:", kmeans.predict([[1, 1], [12, 3]]))

plot("KMEANS LABELS WITH NCLUSTER="+str(n_clusters))

#TUNING: LOOP OVER NCLUSTER PARAMETER
for n_clusters in range(3,6):
	kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
	labels=np.array(kmeans.labels_)
	plot("KMEANS LABELS WITH NCLUSTER="+str(n_clusters))


#--------------------------------------
#DBSCAN (DENSITY BASED METHOD)
#--------------------------------------
print("---------DBSCAN-----------")
from sklearn.cluster import DBSCAN
import numpy as np

#TUNING: LOOP OVER EPS PARAM
for eps in [0.25,0.5,0.75,1.0,1.25,1.5,2.0]:
	clustering = DBSCAN(eps=eps).fit(X)
	labels=clustering.labels_
	plot("DBSCAN LABELS WITH eps="+str(eps))
