import numpy as np
import copy
from RF import *
import torch
from connected_component import *
from sklearn.metrics.cluster import normalized_mutual_info_score
from sklearn.metrics.cluster import adjusted_mutual_info_score
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.metrics.cluster import rand_score
import matplotlib.pyplot as plt
import matplotlib.pyplot as plot
from itertools import product

MS_clustering_h               = {'a1':0.15,'a2':0.15,'a3':0.15,'unbalance':0.3 ,'s1':0.15,'s2':0.15,'s3':0.15,'s4':0.15}
MS_clustering_iteration       = {'a1':100 ,'a2':100 ,'a3':100 ,'unbalance':100 ,'s1':100 ,'s2':100 ,'s3':100 ,'s4':100 }
MS_clustering_threshold       = {'a1':0.9 ,'a2':0.9 ,'a3':0.9 ,'unbalance':0.9 ,'s1':0.9 ,'s2':0.9 ,'s3':0.9 ,'s4':0.9 }


def run_MSPP(X, y,count,dataset):
	h = MS_clustering_h[dataset]
	iteration = MS_clustering_iteration[dataset]
	threshold = MS_clustering_threshold[dataset]


	X[:,0] = X[:,0] - np.min(X[:,0])
	X[:,1] = X[:,1] - np.min(X[:,1])


	new = copy.deepcopy(X)
	current = copy.deepcopy(X)

	t = 0
	v = [-1, 0, 1]

	offsets = list(product(v, repeat=2))

	while True:
		current = copy.deepcopy(new)
		maxs = current.max(axis=0)
		shapes = np.ceil((maxs)/h).astype(int) + 1

		C = np.zeros(shapes)
		S = np.zeros(shapes.tolist() + [current.shape[1]]) 
		
		cell_idx = np.floor(current/h).astype(int)
		
		for pt, idx in zip(current, cell_idx):
			C[tuple(idx)] += 1
			S[tuple(idx)] += pt


		sum_vec = np.zeros_like(current)
		count = np.zeros(len(X))
		idx = np.floor(current/h).astype(int)


		for offset in offsets:
			neighbor_idx = idx + offset
			neighbor_idx[neighbor_idx<0] = 0
			
			neighbor_idx[:,0][neighbor_idx[:,0]>=shapes[0]] = shapes[0]-1
			neighbor_idx[:,1][neighbor_idx[:,1]>=shapes[1]] = shapes[1]-1
			
			temp = list(map(tuple, neighbor_idx.T))
			sum_vec += S[temp[0],temp[1]]
			count += C[temp[0],temp[1]]
		count[count == 0] = 1
		new = sum_vec / count.reshape(-1,1)

		t+=1
		if t>=iteration:
			break


	final_gram = Gaussian_kernel(new,new,1)
	labels = CC(final_gram,threshold)

	NMI = normalized_mutual_info_score(labels,y)
	AMI = adjusted_mutual_info_score(labels,y)
	ARS = adjusted_rand_score(labels,y)
	RS = rand_score(labels,y)
	return NMI, AMI, ARS, RS