#!/usr/local/bin/python

"""
    Skeleton code for k-means clustering mini-project.
"""




import pickle
import numpy
import matplotlib.pyplot as plt
import sys
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler


def Draw(pred, features, poi, mark_poi=False, name="image.png", f1_name="feature 1", f2_name="feature 2"):
    """ some plotting code designed to help you visualize your clusters """

    ### plot each cluster with a different color--add more colors for
    ### drawing more than five clusters
    colors = ["b", "c", "k", "m", "g"]
    for ii, pp in enumerate(pred):
        plt.scatter(features[ii][0], features[ii][1], color = colors[pred[ii]])

    ### if you like, place red stars over points that are POIs (just for funsies)
    if mark_poi:
        for ii, pp in enumerate(pred):
            if poi[ii]:
                plt.scatter(features[ii][0], features[ii][1], color="r", marker="*")
    plt.xlabel(f1_name)
    plt.ylabel(f2_name)
    plt.savefig(name)
    plt.show()



### load in the dict of dicts containing all the data on each person in the dataset
data_dict = pickle.load( open("../final_project/final_project_dataset.pkl", "r") )
### there's an outlier--remove it!
data_dict.pop("TOTAL", 0)


### the input features we want to use
### can be any key in the person-level dictionary (salary, director_fees, etc.)
feature_1 = "salary"
feature_2 = "exercised_stock_options"
feature_3 = "total_payments"
poi  = "poi"
features_list = [poi, feature_1, feature_2, feature_3]
data = featureFormat(data_dict, features_list )

### Scaling
weights = numpy.array(data)
scaler = MinMaxScaler()
rescaled_weights = scaler.fit_transform(weights)
data = rescaled_weights
###

poi, finance_features = targetFeatureSplit( data )




### in the "clustering with 3 features" part of the mini-project,
### you'll want to change this line to
### for f1, f2, _ in finance_features:
### (as it's currently written, the line below assumes 2 features)
for f1, f2, f3 in finance_features:
    plt.scatter( f1, f2 )
plt.show()

### cluster here; create predictions of the cluster labels
### for the data and store them to a list called pred

from sklearn.cluster import KMeans
pred = KMeans(n_clusters=2, init='k-means++', n_init=10, max_iter=300).fit_predict(finance_features)






### rename the "name" parameter when you change the number of features
### so that the figure gets saved to a different file
try:
    Draw(pred, finance_features, poi, mark_poi=False, name="clustersJesse.pdf", f1_name=feature_1, f2_name=feature_2)
except NameError:
    print "no predictions object named pred found, no clusters to plot"


#calculo de maior valor de exercised_stock_options
maxStock = None
personName = None
for keys,values in data_dict.items():
    if values["exercised_stock_options"]!="NaN" :
        insideList = (keys, values["exercised_stock_options"])
        if maxStock < values["exercised_stock_options"]:
            maxStock = values["exercised_stock_options"]
            personName = keys
print "Nome da pessoa com exercised_stock_options mais alto: ",personName
print "Maior valor do exercised_stock_options: ",maxStock

#calculo de menor valor de exercised_stock_options
minStock = maxStock
personName = "teste"
for keys,values in data_dict.items():
    if values["exercised_stock_options"]!="NaN":
        insideList = (keys, values["exercised_stock_options"])
        if minStock >= values["exercised_stock_options"]:
            minStock = values["exercised_stock_options"]
            personName = keys
print "Nome da pessoa com exercised_stock_options mais baixo: ",personName
print "Menor valor do exercised_stock_options: ",minStock


#calculo de maior valor de salary
maxSalary = None
personName = None
for keys,values in data_dict.items():
    if values["salary"]!="NaN" :
        insideList = (keys, values["salary"])
        if maxSalary < values["salary"]:
            maxSalary = values["salary"]
            personName = keys
print "Nome da pessoa com salario mais alto: ",personName
print "Maior valor do salario: ",maxSalary

#calculo de menor valor de salary
minSalary = maxSalary
personName = None
for keys,values in data_dict.items():
    if values["salary"]!="NaN":
        insideList = (keys, values["salary"])
        if minSalary >= values["salary"]:
            minSalary = values["salary"]
            personName = keys
print "Nome da pessoa com salario mais baixo: ",personName
print "Menor valor do salario: ",minSalary

#Calculo do fator de escalonamento do salario
salary_scale = numpy.array([[minSalary],[200000.],[maxSalary]])
min_max_scaler = MinMaxScaler()
salary_minmax_scaler = min_max_scaler.fit_transform(salary_scale)
print "Valor escalonado de um salario de $200.000:","\n",salary_minmax_scaler

#Calculo do fator de escalonamento do exercised_stock_options
stock_scale = numpy.array([[minStock],[1000000.],[maxStock]])
min_max_scaler = MinMaxScaler()
stock_minmax_scaler = min_max_scaler.fit_transform(stock_scale)
print "Valor escalonado de opcao de acoes no valor de $1milhao:","\n",stock_minmax_scaler
