#!/usr/bin/python

import copy
import networkx as nx
import sys
import csv
import os
import Queue
import random
import time
import thread
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from multiprocessing import Pool

import numpy
from collections import defaultdict
import math
import shutil
import tempfile

import subprocess
import community

def calculateNMIFortunato(filename1,filename2):
    proc = subprocess.Popen(["mutual", filename1,filename2],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    (out,err)=proc.communicate()

    return out.split("\t")[1].strip()


def writeOutClusterAndGroundTruthFiles(G,filename):
    internalToExternalID = dict()
    count = 1
    for node in G.nodes():
        internalToExternalID[node] = count
        count += 1


    f = open(filename + "_foundClustersOriginalNames", 'w')
    clusters = defaultdict(set)

    for node in G.nodes():
        clusters[G.node[node]['partition']].add(node)
    for key in clusters:
        f.write(" ".join([str(x) for x in clusters[key]]) + "\n")
    f.close()

    f = open(filename + "_foundClusters", 'w')
    clusters = defaultdict(set)

    for node in G.nodes():
        clusters[G.node[node]['partition']].add(node)
    for key in clusters:
        f.write(" ".join([str(internalToExternalID[x]) for x in clusters[key]]) + "\n")
    f.close()

    f = open(filename + "_groundTruthClusters", 'w')
    clusters = defaultdict(set)

    for node in G.nodes():
#        print "Node: ", node , " groundTruth: ", G.node[node]['groundTruth']
        if 'groundTruth' in G.node[node]:
            clusters[G.node[node]['groundTruth']].add(node)
        else:
            print >> sys.stderr, "Error, node: ", node , " from network, has no ground truth value!"
    for key in clusters:
        f.write(" ".join([str(internalToExternalID[x]) for x in clusters[key]]) + "\n")
    f.close()

def writeOutGraphviz(G, outputFileName = "renderPlain"):

    outputGraph = copy.deepcopy(G)

    maxLength = 0.0
    for src,dst in outputGraph.edges():
        if (G[src][dst]['weight'] + G[dst][src]['weight']) > maxLength:
            maxLength = (G[src][dst]['weight'] + G[dst][src]['weight'])

def doBlondelPartitioning(Network, filename):
    partition = community.best_partition(Network)
    #dendo = community.generate_dendogram(Network, None)
    #partition = community.partition_at_level(dendo, 0)
    for node in Network:
        Network.node[node]['partition'] = partition[node]

file = csv.reader(open(sys.argv[1],'r'), delimiter=' ',quotechar='"')

G = nx.Graph()
for row in file:
    G.add_edge(row[0],row[1])
    if 'weight' in G[row[0]][row[1]]:
        #G[row[0]][row[1]]['weight'] += int(float(row[2]))
        G[row[0]][row[1]]['weight'] += int(row[2])
    else:
        #G[row[0]][row[1]]['weight'] = int(float(row[2]))
        G[row[0]][row[1]]['weight'] = int(row[2])

doBlondelPartitioning(G,sys.argv[1])

groundTruth = csv.reader(open(sys.argv[2]) , delimiter = " ", quotechar='"')
for line in groundTruth:
    theNode = line[0]
    if theNode in G.nodes():
        G.node[theNode]['groundTruth'] = int(line[1])
    else:
        print >>sys.stderr ,"Error, node: ", theNode , " from ground truth, not found in network!"


writeOutGraphviz(G,sys.argv[1])



writeOutClusterAndGroundTruthFiles(G,sys.argv[1])
LFKNmi = calculateNMIFortunato(sys.argv[1] + "_foundClusters", sys.argv[1] + "_groundTruthClusters")
print "NMI_vs_groundTruth,",LFKNmi#, ",",onmi
