#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

from roc_function import *
from funkce2 import *
from sklearn import metrics
from lib.utilities import load_or_get
import csv


"""--------------------
POPIS:
výpočet AUC pro všechny algoritmy ..
výstupem tabulka nebo .csv file ve formátu

číslo pacienta      AUC LL_detect       AUC Hilbert     AUC Matt

výpočet breakpointu
-------------------------------------------------------------------------------------"""

databases = [ 'LL_alg_Fnusa', 'Matt_alg_Fnusa', 'hilbert_alg_v2']

#-----volba parametrů
patients = range(2, 34) #range je bez posledního
#patients = [3, 6, 18]
#patients = [3, 5]

database = databases[2] #volba 0, 1, 2
#-----

fpr = dict()
tpr = dict()
total_count = dict()
doctor = dict()
AUC = dict()
c_min = dict()
c = dict()
fpr_tpr_breakpoint = dict()

for vybrany_pacient in patients:
    try:
        fpr[vybrany_pacient], tpr[vybrany_pacient], total_count[vybrany_pacient], doctor[vybrany_pacient] = load_or_get(roc, database, vybrany_pacient, vybrany_pacient, 'channel_name') #total_count[vybrany_pacient], doctor[vybrany_pacient] NECHCI
        AUC[vybrany_pacient] = round(metrics.auc(fpr[vybrany_pacient], tpr[vybrany_pacient]), 3)

        for i in range(1, len(fpr[vybrany_pacient])):
            c[i] = round(math.sqrt((0-fpr[vybrany_pacient][i])**2 + (1-tpr[vybrany_pacient][i])**2), 3)
            c_min[vybrany_pacient] = c[min(c,key=c.get)]
            fpr_tpr_breakpoint[vybrany_pacient]=[round(fpr[vybrany_pacient][min(c,key=c.get)],3), round(tpr[vybrany_pacient][min(c,key=c.get)],3)]

    except:
        pass

print(repr(AUC))
print('Done :)')


#zápis do .csv
with open('AUC_and_distance_breakpoints_hilbert_alg_v2', 'w') as csvfile:
    fieldnames = ['Patient number','AUC', 'distance', 'fpr_tpr_breakpoint']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    rows = list()
    for key, value in AUC.items() :
        writer.writerow({'Patient number': (key),'AUC': (value)})#, 'distance':  (value)})#, 'last_name': 'Beans'})
        #rows.append([key, value])
    i = 0
    for key, value in c_min.items():
         writer.writerow({'distance':  ([key, value])}) #key nechávám pro kontrolu

    for key, value in fpr_tpr_breakpoint.items():
        writer.writerow({'fpr_tpr_breakpoint': ([key, value])})

'''
#funkční verze-----------------
#zápis do .csv
with open('AUC_and_distance.csv', 'w') as csvfile:
    fieldnames = ['Patient number','AUC', 'distance']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    rows = list()
    for key, value in AUC.items():
        writer.writerow({'Patient number': (key),'AUC': (value)})#, 'distance':  (value)})#, 'last_name': 'Beans'})
        #rows.append([key, value])
    i = 0
    for key, value in c_min.items():
         writer.writerow({'distance':  ([key, value])}) #key nechávám kontrolu
#-------------
'''
