#!/usr/bin/env python
import fileinput
from fuzzy_davi import *
import random
import sys

if '-h' in sys.argv:
	print 'cfuzzy tree_dist num_cluster fuzzyness precision'
	sys.exit()
if len(sys.argv) < 4:
	print 'not enough arguments'
	sys.exit()


names, Dmatrix = readDm(sys.argv[1])

#for name in names:
#	print name + ' - ' + str(Dmatrix[name])

X = coord(names, Dmatrix, sys.argv[1])

output = ''

for name, line in X.iteritems():
	output = output + name + '{'
	for val in line:
		output = output + str(val) + ' , '
	output = output + '}\n'
print '\n\n\n Coordinates\n\n' + output

#Finding the highest density region

#x_avg, x_std = x_stat(X)




# centroids generators

C = {}
Cnames = []
for i in range(int(sys.argv[2])):
        Ct = []
	for j in range(len(X)):
                centroid = random.gauss(-2,2)
		Ct.append(centroid)
        C[i+1] = Ct
	Cnames.append(i+1)

U_old = UmatrixG(names,X,Cnames,C,sys.argv[3])
C = centroidesG(names,X,U_old,sys.argv[3])
U_new = UmatrixG(names,X,Cnames,C,sys.argv[3])

max_Uold = 0
for i in U_old:
	if max_Uold < max(i):
                max_Uold = max(i)

max_Unew = 0
for i in U_new:
        if max_Unew < max(i):
                max_Unew = max(i)

step = 0
e = float(sys.argv[4])

while abs(max_Unew - max_Uold) > e:
        step = step + 1
        U_old = []
        for i in U_new:
                U_old.append(i)
        C = centroidesG(names,X,U_old,float(sys.argv[3]))
        U_new = UmatrixG(names,X,Cnames,C,float(sys.argv[3]))
 
	max_Uold = 0
        for i in U_old:
                if max_Uold < max(i):
			max_Uold = max(i)
	
	max_Unew = 0
	for i in U_new:
		if max_Unew < max(i):
			max_Unew = max(i)
	
	print str(step) + ' --- Error: ' + str(max_Unew - max_Uold)
	if max_Unew - max_Uold < 0 and step == 1:
		print 'Decrease fuzzyness'
		sys.exit()
#	for i in Cnames:
#		print str(C[i]) + '\n'

output = ''
for i in range(len(names)):
	output = output + names[i] + ' --- '
	total = 0
	for j in U_new[i]:
		if j < 0.0001:
			j = 0.0001
		val = str(j)[:5]
		total = total + j
		output = output + val + '   '
	output = output + ' --- ' + str(total) + '\n'

print '\n\n\n Results \n\n' + output

outfile = open(sys.argv[1][:-4] + str(sys.argv[2]) + '.m' + str(sys.argv[3]) + '.results.txt','w')
outfile.write(output)
outfile.close

