import networkx as nx
import numpy as np
import scipy as sp
import scipy.cluster.vq as vq
import matplotlib.pyplot as plt
import math
import random
import operator

################################################################################
# draw graph and color communities

def draw_comm_graph(G, comms):
	colors = [comms[v] for v in G.nodes()]
	
	nx.draw_kamada_kawai(G, with_labels=True, node_color=colors)
	plt.show()

################################################################################
# ground truth communities

G = nx.read_edgelist("karate.data", comments="%")
comms = {}
with open("karate.gt") as f:
	for line in f:
		(key, val) = line.split()
		comms[key] = int(val)

draw_comm_graph(G, comms)

################################################################################
# spectral clustering

A = nx.to_numpy_matrix(G)
D = np.diag(np.sum(np.array(A), axis=1))
L = D - A

(e, V) = np.linalg.eigh(L)
x = V[:,1]
comms = {}
counter = 0
for n in G.nodes():
	if x[counter] > 0:
		comms[n] = 0
	else:
		comms[n] = 1
	counter += 1

draw_comm_graph(G, comms)


################################################################################
# for a larger numbers of clusters

k = 3
means, labels = sp.cluster.vq.kmeans2(V[:,1:k], k)

comms = {}
counter = 0
for n in G.nodes():
	comms[n] = labels[counter]
	counter += 1

draw_comm_graph(G, comms)

