# encoding:utf-8
import csv

import os
full_path = os.path.realpath(__file__)
curdir=os.path.dirname(full_path)
os.chdir(curdir)
import sys
sys.path.append(os.path.join(curdir,'iLearn-master'))
import tensorflow as tf
from sklearn.metrics import roc_curve, auc, precision_recall_curve
from tensorflow.keras import layers,Sequential,optimizers,datasets,metrics
import numpy as np
from datetime import datetime
from RicENN_NW_2_20211021 import RicENNNWModel2
from RicEnnTool import hzXunlianGc, zhuanhuan, canshu, xiangguanTezhenTiqu

if __name__ == '__main__':
    # /home/bioinfo/anaconda3/envs/python36/bin/python3 /home/bioinfo/cyq/RicENN/No1xiugai/RicENNTrain.py
    print("TezhenPintjie----")
    tezhenArray=['DAC','DACC','DCC','TAC','TACC','TCC']


    modelFile='RicENN_NW_2_20211021'
    full_path = os.path.realpath(__file__)
    curdir=os.path.dirname(full_path)
    modelPath=os.path.join(curdir,'model')
    resultPath = os.path.join(curdir, 'result')
    dataPath=os.path.join(curdir, 'data')
    fileTrainName='fileTrain06_1_suojian.fa'
    fileTestName='fileTest06_1_suojian.fa'

    train_x1, train_y = xiangguanTezhenTiqu(os.path.join(dataPath, fileTrainName), tezhenArray)
    test_x1, test_y= xiangguanTezhenTiqu(os.path.join(dataPath,fileTestName), tezhenArray)


    x_train = train_x1
    x_train = x_train.reshape(x_train.shape[0], x_train.shape[1],
                              1)  # keras.preprocessing.sequence.pad_sequences(train_x, maxlen, padding='post')

    x_test = test_x1  # np.array(test_x1);
    x_test = x_test.reshape(x_test.shape[0], x_test.shape[1],
                            1)  # keras.preprocessing.sequence.pad_sequences(test_x, maxlen, padding='post')
    # X = np.expand_dims(x_train, axis=2) #表示是是增加的维度是在第三个维度上
    train_y = np.array(train_y)
    test_y = np.array(test_y)
    tezhen='All'
    EPOCH=10
    BATCH_SIZE=64
    LEARNRATE=0.001
    maxlen=400
    modelName = 'RiceENN' + tezhen + 'M2_ep' + str(EPOCH)  + "_ba" + str(
        BATCH_SIZE) + "_lr" + str(LEARNRATE).split('.')[1]
    modelAliasName = 'RicENN' + tezhen + 'NW2_epoch' + str(EPOCH)  + "_ba" + str(
        BATCH_SIZE) + "_lr" + str(LEARNRATE).split('.')[1]


 

    t1 = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    model = RicENNNWModel2();
    model.build(input_shape=(None, maxlen, 1))
    model.summary()
    model.compile(optimizer=optimizers.Adam(lr=LEARNRATE), loss=tf.losses.BinaryCrossentropy(),
                  metrics=['accuracy'])
    # back = roc_callback(val_data=[X_en_val, y_val], name="onehotmodel")

    checkpointpath =os.path.join(modelPath, modelName + '_val_accuracy')
    if (os.path.exists(checkpointpath) == False):
        os.mkdir(checkpointpath)
    checkpointpath = os.path.join(checkpointpath , "ckpt")
    model_call_back = tf.keras.callbacks.ModelCheckpoint(checkpointpath, save_best_only=True,
                                                         save_weights_only=False,
                                                         monitor='val_accuracy', mode='max')

    history = model.fit(x_train, train_y, validation_split=0.1, epochs=EPOCH, batch_size=BATCH_SIZE,
                        callbacks=[model_call_back])
    model.save(os.path.join(modelPath , modelName))

    score = model.evaluate(x_test, test_y)
    print('\nTest loss:', score[0])
    print('Test accuracy:', score[1])
    t2 = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    print("开始时间:" + t1 + "结束时间：" + t2)
    train_y_f = train_y[:, 0]
    test_y_f = test_y[:, 0]
    predit_train = model.predict(x_train)
    predit_test = model.predict(x_test)
    predit_test = predit_test[:, 0]
    predit_train = predit_train[:, 0]
    train_y_f = np.array(train_y_f)
    test_y_f = np.array(test_y_f)
    # 计算AUROC
    #训练集AUROC
    (fpr_train, tpr_train, thresholds_train) = roc_curve(train_y_f, predit_train, pos_label=[1.0])
    roc_auc_train = auc(fpr_train, tpr_train)# 训练集
    #测试集AUROC
    (fpr_test, tpr_test, thresholds_test) = roc_curve(test_y_f, predit_test, pos_label=[1.0])
    roc_auc_test = auc(fpr_test, tpr_test)# 测试集
    # 计算AUPRC
    # 训练集AUPRC
    precision_train, recall_train, thresholds = precision_recall_curve(train_y_f, predit_train,
                                                                       pos_label=[1.0])
    prc_auc_train = auc(recall_train, precision_train)  # 训练集
    # 测试集AUPRC
    precision_test, recall_test, thresholds = precision_recall_curve(test_y_f, predit_test,
                                                                     pos_label=[1.0])
    prc_auc_test = auc(recall_test, precision_test)  # 测试集
    zhuanhuan(predit_train, 0.5)
    zhuanhuan(predit_test, 0.5)
    canshuReTrain = canshu(train_y_f, predit_train)  # acc, sp, sn, pr, rc,npv 测试集参数
    canshuReTest = canshu(test_y_f, predit_test)#acc, sp, sn, pr, rc,npv 测试集参数
    resultFile = "RicENN2_20211024.csv"
    fileWrite = open(os.path.join(resultPath, resultFile), encoding='utf-8', mode='a')
    csvWriter = csv.writer(fileWrite)
    listRow = ['codefile', 'modelfile', 'fileTrainName', 'fileTestName', 'modelPath', 'modelName', 'maxlen',
               'BATCH_SIZE', 'EPOCH', 'LEARNRATE', 'tezhen','valacc_training', 'valloss_training',
               'train_loss_training','train_acc_training','train_acc_predict', 'train_sp', 'train_sn/rec', 'train_pre','train_npv','train_auroc','train_auprc',
               'test_acc_evaluate','test_acc_predict', 'test_sp', 'test_sn/rec', 'test_pre', 'test_npv','test_auroc','test_auprc','testloss', '开始时间', '结束时间']
    csvWriter.writerow(listRow)
    xunlian = history.history;
    full_path = os.path.realpath(__file__)
    listRow = [full_path, modelFile + ".py", fileTrainName, fileTestName, modelPath, modelName, maxlen,
               BATCH_SIZE, EPOCH,  LEARNRATE, tezhen,xunlian['val_accuracy'][EPOCH - 1],
               xunlian['val_loss'][EPOCH - 1],xunlian['loss'][EPOCH - 1],
               xunlian['accuracy'][EPOCH - 1],canshuReTrain[0],canshuReTrain[1],canshuReTrain[2],canshuReTrain[3],canshuReTrain[4],roc_auc_train,prc_auc_train,
               score[1],canshuReTest[0],canshuReTest[1],canshuReTest[2],canshuReTest[3],canshuReTest[4],roc_auc_test,prc_auc_test, score[0], t1, t2]
    csvWriter.writerow(listRow)
    fileWrite.close()
