# Path: cognitive/app/models.py
# class Experiment(models.Model):
#     EXPERIMENT_STATUS = (
#         ('Stop', ' Saved as stop'),
#         ('InComplete', 'More information required'),
#         ('InExecution', 'Execution started'),
#         ('Error', ' Error when executed'),
#         ('Completed', 'Executed Successfully'),
#     )
#     user = models.ForeignKey(User)
#     name = models.CharField(max_length=50)
#     status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
#     created_time = models.DateTimeField(auto_now=True)
#     modified_time = models.DateTimeField(auto_now=True)
#     execution_start_time = models.DateTimeField(blank=True, null=True)
#     execution_end_time = models.DateTimeField(blank=True, null=True)
#     component_start_id = models.IntegerField(blank=True, null=True)
# 
#     class Meta:
#         ordering = ['-modified_time']
# 
# class Component(models.Model):
#     COMPONENT_STATUS = (
#         ('Stop', ' Saved as stop'),
#         ('InComplete', 'More information required'),
#         ('InExecution', 'Execution started'),
#         ('Error', ' Error when executed'),
#         ('Completed', 'Executed Successfully'),
#     )
# 
#     experiment = models.ForeignKey(Experiment)
#     status = models.CharField(max_length=50, choices=COMPONENT_STATUS, default='Stop')
#     operation_type = models.OneToOneField(DataOperationType, blank=True, null=True)
#     created_time = models.DateTimeField(auto_now=True)
#     modified_time = models.DateTimeField(auto_now=True)
#     execution_start_time = models.DateTimeField(blank=True, null=True)
#     execution_end_time = models.DateTimeField(blank=True, null=True)
#     data_location = models.CharField(max_length=50, blank=True, null=True)
#     preferred_data_location = models.CharField(max_length=50, blank=True, null=True)
#     # component_id = models.IntegerField(blank=True, null=True)
# 
# Path: cognitive/app/ml_models.py
# class Classifier:
#     def __init__(self, input_data, classifier_type, train_data_percentage, input_features, target_feature):
#         self.input_data = input_data
#         self.train_data_percentage = train_data_percentage
#         self.target_feature = target_feature
#         self.input_features = input_features
#         self.parallel_jobs = 1
#         if classifier_type == 'Linear_SVM':
#             self.clf = SVC(kernel='linear', C=0.025)
#         elif classifier_type == 'Nearest_Neighbours':
#             self.clf = KNeighborsClassifier(3)
#         elif classifier_type == 'Decision_Tree':
#             self.clf = DecisionTreeClassifier(max_depth=5)
#         elif classifier_type == 'Random_Forest':
#             self.clf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1, n_jobs=self.parallel_jobs)
#         elif classifier_type == 'Naive_Bayes':
#             self.clf = GaussianNB()
# 
#     def learn(self):
#         print "Input features ", list(self.input_features)
#         print "Target feature ", self.target_feature
#         features = self.input_data[self.input_features].values
#         labels = self.input_data[self.target_feature].values
#         test_data_percentage = 1 - self.train_data_percentage
#         x_train, x_test, y_train, y_actual = cross_validation.train_test_split(
#             features, labels, test_size=test_data_percentage, random_state=0)
#         self.clf.fit(x_train, y_train)
#         y_pred = self.clf.predict(x_test)
#         accuracy = round(accuracy_score(y_actual, y_pred), 2)
#         recall = round(recall_score(y_actual, y_pred), 2)
#         precision = round(precision_score(y_actual, y_pred), 2)
#         f1 = round(f1_score(y_actual, y_pred), 2)
#         mat = confusion_matrix(y_actual, y_pred)
#         true_positives = mat[1][1]
#         false_positives = mat[0][1]
#         true_negatives = mat[0][0]
#         false_negatives = mat[1][0]
#         result = {
#             'Accuracy Score': accuracy, 'Recall Score': recall,
#             'Precision Score': precision, 'F1 Score': f1,
#             'True Positives': true_positives,
#             'False Positives': false_positives,
#             'True Negatives': true_negatives,
#             'False Negatives': false_negatives
#         }
# 
#         print result
#         return result


from ..models import Experiment, Component
from toposort import toposort_flatten
from ..ml_models import Classifier
from rest_framework import viewsets
from django.http import HttpResponse
from collections import Counter
from pandas import *
import threading
import json
            comp = Component.objects.get(pk=component_id)
            print "Component_id", component_id, " ", comp.operation_type
            op = comp.operation_type

            if op.function_type == 'Create':
                if op.function_arg == 'Table':
                    if op.function_subtype == 'Input':
                        filename = op.function_subtype_arg
                        input_data = read_csv(filename)
                        feature_names = input_data.columns

                # TODO: [refactor] elif?
                if op.function_arg == 'Row':
                    if op.function_subtype == 'Row':
                        row_values = json.loads(op.function_subtype_arg)
                        input_data.loc[len(input_data) + 1] = row_values

                if op.function_arg == 'Model':
                    if op.function_subtype == 'Train-Test':
                        params = json.loads(op.function_subtype_arg)
                        train_data_percentage = int(params["train_data_percentage"])
                        target_column = int(params["target_column"])
                        model_type = op.function_arg_id
                        print model_type, train_data_percentage, target_column
                        target_feature = feature_names[target_column]
                        try:
                            actual_target_column = input_data.columns.get_loc(target_feature)
                            input_feature_columns = range(len(input_data.columns))
                            input_feature_columns.remove(actual_target_column)
                            input_features = input_data.columns[input_feature_columns]

# Path: cognitive/app/models.py
# class Experiment(models.Model):
#     EXPERIMENT_STATUS = (
#         ('Stop', ' Saved as stop'),
#         ('InComplete', 'More information required'),
#         ('InExecution', 'Execution started'),
#         ('Error', ' Error when executed'),
#         ('Completed', 'Executed Successfully'),
#     )
#     user = models.ForeignKey(User)
#     name = models.CharField(max_length=50)
#     status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
#     created_time = models.DateTimeField(auto_now=True)
#     modified_time = models.DateTimeField(auto_now=True)
#     execution_start_time = models.DateTimeField(blank=True, null=True)
#     execution_end_time = models.DateTimeField(blank=True, null=True)
#     component_start_id = models.IntegerField(blank=True, null=True)
# 
#     class Meta:
#         ordering = ['-modified_time']
# 
# class Component(models.Model):
#     COMPONENT_STATUS = (
#         ('Stop', ' Saved as stop'),
#         ('InComplete', 'More information required'),
#         ('InExecution', 'Execution started'),
#         ('Error', ' Error when executed'),
#         ('Completed', 'Executed Successfully'),
#     )
# 
#     experiment = models.ForeignKey(Experiment)
#     status = models.CharField(max_length=50, choices=COMPONENT_STATUS, default='Stop')
#     operation_type = models.OneToOneField(DataOperationType, blank=True, null=True)
#     created_time = models.DateTimeField(auto_now=True)
#     modified_time = models.DateTimeField(auto_now=True)
#     execution_start_time = models.DateTimeField(blank=True, null=True)
#     execution_end_time = models.DateTimeField(blank=True, null=True)
#     data_location = models.CharField(max_length=50, blank=True, null=True)
#     preferred_data_location = models.CharField(max_length=50, blank=True, null=True)
#     # component_id = models.IntegerField(blank=True, null=True)
# 
# Path: cognitive/app/ml_models.py
# class Classifier:
#     def __init__(self, input_data, classifier_type, train_data_percentage, input_features, target_feature):
#         self.input_data = input_data
#         self.train_data_percentage = train_data_percentage
#         self.target_feature = target_feature
#         self.input_features = input_features
#         self.parallel_jobs = 1
#         if classifier_type == 'Linear_SVM':
#             self.clf = SVC(kernel='linear', C=0.025)
#         elif classifier_type == 'Nearest_Neighbours':
#             self.clf = KNeighborsClassifier(3)
#         elif classifier_type == 'Decision_Tree':
#             self.clf = DecisionTreeClassifier(max_depth=5)
#         elif classifier_type == 'Random_Forest':
#             self.clf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1, n_jobs=self.parallel_jobs)
#         elif classifier_type == 'Naive_Bayes':
#             self.clf = GaussianNB()
# 
#     def learn(self):
#         print "Input features ", list(self.input_features)
#         print "Target feature ", self.target_feature
#         features = self.input_data[self.input_features].values
#         labels = self.input_data[self.target_feature].values
#         test_data_percentage = 1 - self.train_data_percentage
#         x_train, x_test, y_train, y_actual = cross_validation.train_test_split(
#             features, labels, test_size=test_data_percentage, random_state=0)
#         self.clf.fit(x_train, y_train)
#         y_pred = self.clf.predict(x_test)
#         accuracy = round(accuracy_score(y_actual, y_pred), 2)
#         recall = round(recall_score(y_actual, y_pred), 2)
#         precision = round(precision_score(y_actual, y_pred), 2)
#         f1 = round(f1_score(y_actual, y_pred), 2)
#         mat = confusion_matrix(y_actual, y_pred)
#         true_positives = mat[1][1]
#         false_positives = mat[0][1]
#         true_negatives = mat[0][0]
#         false_negatives = mat[1][0]
#         result = {
#             'Accuracy Score': accuracy, 'Recall Score': recall,
#             'Precision Score': precision, 'F1 Score': f1,
#             'True Positives': true_positives,
#             'False Positives': false_positives,
#             'True Negatives': true_negatives,
#             'False Negatives': false_negatives
#         }
# 
#         print result
#         return result


# Path: cognitive/app/api/results_local.py
from ..models import Experiment, Component
from toposort import toposort_flatten
from ..ml_models import Classifier
from rest_framework import viewsets
from django.http import HttpResponse
from collections import Counter
from pandas import *
import threading
import json

            comp = Component.objects.get(pk=component_id)
            print "Component_id", component_id, " ", comp.operation_type
            op = comp.operation_type

            if op.function_type == 'Create':
                if op.function_arg == 'Table':
                    if op.function_subtype == 'Input':
                        filename = op.function_subtype_arg
                        input_data = read_csv(filename)
                        feature_names = input_data.columns

                # TODO: [refactor] elif?
                if op.function_arg == 'Row':
                    if op.function_subtype == 'Row':
                        row_values = json.loads(op.function_subtype_arg)
                        input_data.loc[len(input_data) + 1] = row_values

                if op.function_arg == 'Model':
                    if op.function_subtype == 'Train-Test':
                        params = json.loads(op.function_subtype_arg)
                        train_data_percentage = int(params["train_data_percentage"])
                        target_column = int(params["target_column"])
                        model_type = op.function_arg_id
                        print model_type, train_data_percentage, target_column
                        target_feature = feature_names[target_column]
                        try:
                            actual_target_column = input_data.columns.get_loc(target_feature)
                            input_feature_columns = range(len(input_data.columns))
                            input_feature_columns.remove(actual_target_column)
                            input_features = input_data.columns[input_feature_columns]

                            classifier = Classifier(