# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
import os
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsScene, QMessageBox
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras import models
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPool2D
from keras.models import Sequential
import csv
import pandas as pd


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(568, 588)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Ignored)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.listWidget.sizePolicy().hasHeightForWidth())
        self.listWidget.setSizePolicy(sizePolicy)
        self.listWidget.setObjectName("listWidget")
        self.horizontalLayout.addWidget(self.listWidget)
        self.verticalLayout_5.addLayout(self.horizontalLayout)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setObjectName("label_7")
        self.verticalLayout_2.addWidget(self.label_7)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setBaseSize(QtCore.QSize(0, 0))
        self.label.setObjectName("label")
        self.horizontalLayout_2.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout_2.addWidget(self.lineEdit)
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setBaseSize(QtCore.QSize(0, 0))
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_2.addWidget(self.label_2)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout_2.addWidget(self.lineEdit_2)
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setBaseSize(QtCore.QSize(0, 0))
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_2.addWidget(self.label_3)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.horizontalLayout_2.addWidget(self.lineEdit_3)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setBaseSize(QtCore.QSize(0, 0))
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_3.addWidget(self.label_4)
        self.lineEdit_4 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.horizontalLayout_3.addWidget(self.lineEdit_4)
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setBaseSize(QtCore.QSize(0, 0))
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_3.addWidget(self.label_6)
        self.lineEdit_5 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_5.setObjectName("lineEdit_5")
        self.horizontalLayout_3.addWidget(self.lineEdit_5)
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setBaseSize(QtCore.QSize(0, 0))
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_3.addWidget(self.label_5)
        self.lineEdit_6 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.horizontalLayout_3.addWidget(self.lineEdit_6)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_5.addLayout(self.verticalLayout_2)
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(2)
        sizePolicy.setVerticalStretch(2)
        sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
        self.pushButton_2.setSizePolicy(sizePolicy)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_8.addWidget(self.pushButton_2)
        self.verticalLayout_5.addLayout(self.horizontalLayout_8)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setObjectName("graphicsView")
        self.horizontalLayout_4.addWidget(self.graphicsView)
        self.graphicsView_2 = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView_2.setObjectName("graphicsView_2")
        self.horizontalLayout_4.addWidget(self.graphicsView_2)
        self.graphicsView_3 = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView_3.setObjectName("graphicsView_3")
        self.horizontalLayout_4.addWidget(self.graphicsView_3)
        self.verticalLayout_4.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.graphicsView_4 = QtWidgets.QGraphicsView(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(self.graphicsView_4.sizePolicy().hasHeightForWidth())
        self.graphicsView_4.setSizePolicy(sizePolicy)
        self.graphicsView_4.setObjectName("graphicsView_4")
        self.horizontalLayout_5.addWidget(self.graphicsView_4)
        self.graphicsView_5 = QtWidgets.QGraphicsView(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(self.graphicsView_5.sizePolicy().hasHeightForWidth())
        self.graphicsView_5.setSizePolicy(sizePolicy)
        self.graphicsView_5.setObjectName("graphicsView_5")
        self.horizontalLayout_5.addWidget(self.graphicsView_5)
        self.horizontalLayout_6.addLayout(self.horizontalLayout_5)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
        self.pushButton_3.setSizePolicy(sizePolicy)
        self.pushButton_3.setObjectName("pushButton_3")
        self.verticalLayout_3.addWidget(self.pushButton_3)
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
        self.pushButton_4.setSizePolicy(sizePolicy)
        self.pushButton_4.setObjectName("pushButton_4")
        self.verticalLayout_3.addWidget(self.pushButton_4)
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_5.sizePolicy().hasHeightForWidth())
        self.pushButton_5.setSizePolicy(sizePolicy)
        self.pushButton_5.setObjectName("pushButton_5")
        self.verticalLayout_3.addWidget(self.pushButton_5)
        self.horizontalLayout_6.addLayout(self.verticalLayout_3)
        self.verticalLayout_4.addLayout(self.horizontalLayout_6)
        self.verticalLayout_5.addLayout(self.verticalLayout_4)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 568, 22))
        self.menuBar.setObjectName("menuBar")
        self.menuHelp = QtWidgets.QMenu(self.menuBar)
        self.menuHelp.setObjectName("menuHelp")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)
        self.actionInput = QtWidgets.QAction(MainWindow)
        self.actionInput.setObjectName("actionInput")
        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionAbout_FFI_Net = QtWidgets.QAction(MainWindow)
        self.actionAbout_FFI_Net.setObjectName("actionAbout_FFI_Net")
        self.menuHelp.addAction(self.actionAbout_FFI_Net)
        self.menuBar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.pushButton.clicked.connect(self.bindList)
        self.pushButton_2.clicked.connect(self.Preprocess)
        self.pushButton_3.clicked.connect(self.Run)
        self.pushButton_4.clicked.connect(self.Clean)
        self.pushButton_5.clicked.connect(QCoreApplication.instance().quit)
        self.pushButton_5.clicked.connect(self.Clean)

    def bindList(self):
        from PyQt5.QtWidgets import QFileDialog
        import openpyxl
        dir = QFileDialog()
        dir.setFileMode(QFileDialog.ExistingFiles)
        dir.setDirectory('C:\\')
        dir.setNameFilter('Excel(*.xlsx *.xls)')
        if dir.exec_():
            filenames = dir.selectedFiles()
            self.listWidget.addItems(dir.selectedFiles())
            f = openpyxl.load_workbook(filenames[0])
            self.sheet1 = f["Sheet1"]
            f.close()
        self.pushButton.setEnabled(False)
        self.pushButton_4.setEnabled(True)

    def Preprocess(self):
        import csv
        import pandas as pd
        import numpy as np

        # input your 3D-EEM data format (Lower boundary, upper boundary and interval for Ex and Em)
        ExL = int(self.lineEdit.text())
        ExU = int(self.lineEdit_2.text())
        ExI = int(self.lineEdit_3.text())
        EmL = int(self.lineEdit_4.text())
        EmU = int(self.lineEdit_5.text())
        EmI = int(self.lineEdit_6.text())
        # Target Ex and Em format
        TExL = 200
        TExU = 450
        TExI = 5
        TEmL = 250
        TEmU = 500
        TEmI = 5

        for m in range(int((TEmL - EmL) / EmI + 1), int((TEmU - EmL) / EmI + TEmI / EmI + 1), int(TEmI / EmI)):
            for n in range(int((TExL - ExL) / ExI + 1), int((TExU - ExL) / ExI + TExI / ExI + 1), int(TExI / ExI)):
                cell = self.sheet1.cell(row=m, column=n).value
                p = open('./Preprocess/column data.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p)
                csv_writer.writerow([cell])
                p.close()

        # Transpose the column data to row data for CNN
        df = pd.read_csv('./Preprocess/column data.csv', header=None)
        data = np.array(df)
        data = list(map(list, zip(*data)))
        data = pd.DataFrame(data)
        data.to_csv('./Preprocess/row data.csv', header=0, index=0, mode='a',float_format='%.3f')
        self.pushButton_2.setEnabled(False)

    def Run(self):
        def build_model():
            model = models.Sequential()
            model.add(Conv2D(filters=32, kernel_size=(4, 4),
                             activation='relu', input_shape=(51, 51, 1)))
            model.add(MaxPool2D(pool_size=(2, 2)))
            model.add(Conv2D(64, (3, 3), activation='relu'))
            model.add(MaxPool2D(pool_size=(2, 2)))
            model.add(Flatten())
            model.add(Dense(64, activation='relu'))
            model.add(Dropout(0.5))
            model.add(Dense(128, activation='relu'))
            model.add(Dense(3, activation='softmax'))
            model.compile(loss=keras.losses.categorical_crossentropy,
                          optimizer=keras.optimizers.Adadelta(),
                          metrics=['accuracy'])
            model.summary()
            return model

        model = build_model()
        model.load_weights('./Weights/NCNN_weight_2021_03_18.h5')

        dataset = np.loadtxt('./Preprocess/row data.csv', delimiter=',')
        originx = dataset[0:2601]
        originx = originx / 9999
        testx = originx.reshape(-1, 51, 51, 1)
        test_predict = model.predict(testx, batch_size=1)
        print(test_predict[:, 0], test_predict[:, 1], test_predict[:, 2])

        if (test_predict[:, 0] >= test_predict[:, 1]) and (test_predict[:, 0] >= test_predict[:, 2]):
            input_shape=(51, 51, 1)

            # model structure
            model1 = Sequential()
            model1.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model1.add(MaxPool2D(pool_size=(2, 2)))

            model1.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model1.add(MaxPool2D(pool_size=(2, 2)))

            model1.add(Flatten())
            model1.add(Dense(128, activation='relu'))
            model1.add(Dropout(0.5))
            model1.add(Dense(256, activation='relu'))
            model1.add(Dense(2601))
            model1.summary()

            model1.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model2 = Sequential()
            model2.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model2.add(MaxPool2D(pool_size=(2, 2)))

            model2.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model2.add(MaxPool2D(pool_size=(2, 2)))

            model2.add(Flatten())
            model2.add(Dense(128, activation='relu'))
            model2.add(Dropout(0.5))
            model2.add(Dense(256, activation='relu'))
            model2.add(Dense(2601))
            model2.summary()

            model2.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model3 = Sequential()
            model3.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model3.add(MaxPool2D(pool_size=(2, 2)))

            model3.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model3.add(MaxPool2D(pool_size=(2, 2)))

            model3.add(Flatten())
            model3.add(Dense(128, activation='relu'))
            model3.add(Dropout(0.5))
            model3.add(Dense(256, activation='relu'))
            model3.add(Dense(2601))
            model3.summary()

            model3.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])
            model1.load_weights('./Weights/MCNN3_1_weight_2021_03_18.h5')
            model2.load_weights('./Weights/MCNN3_2_weight_2021_03_18.h5')
            model3.load_weights('./Weights/MCNN3_3_weight_2021_03_18.h5')

            dataset = np.loadtxt('./Preprocess/row data.csv', delimiter=',')
            originx = dataset[0:2601]
            originx = originx / 9999
            testx = originx.reshape(-1, 51, 51, 1)
            test1_predict = model1.predict(testx, batch_size=1)
            Component1_predict = test1_predict.reshape(-1, 51, 51, 1)
            test2_predict = model2.predict(testx, batch_size=1)
            Component2_predict = test2_predict.reshape(-1, 51, 51, 1)
            test3_predict = model3.predict(testx, batch_size=1)
            Component3_predict = test3_predict.reshape(-1, 51, 51, 1)

            plt.imshow(Component1_predict[0],cmap = 'rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC1.tif')
            plt.close()
            plt.imshow(Component2_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC2.tif')
            plt.close()
            plt.imshow(Component3_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC3.tif')
            plt.close()

            for i in range(2601):
                p1 = open('./Results/test1_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p1)
                csv_writer.writerow(test1_predict[:, i])
                p1.close()
            df = pd.read_csv('./Results/test1_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test1_predictT.csv', header=0)
            # Transform the row data to matrix data for PARAFAC
            df2 = pd.read_csv('./Results/test1_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component1.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p2 = open('./Results/test2_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p2)
                csv_writer.writerow(test2_predict[:, i])
                p2.close()
            df = pd.read_csv('./Results/test2_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test2_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test2_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component2.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p3 = open('./Results/test3_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p3)
                csv_writer.writerow(test3_predict[:, i])
                p3.close()
            df = pd.read_csv('./Results/test3_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test3_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test3_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component3.csv', header=0, index=0, mode='a')

            showImage1 = QtGui.QImage('./Results/PC1.tif')
            PC1 = QtGui.QPixmap.fromImage(showImage1)
            self.item1 = QGraphicsPixmapItem(PC1)
            self.scene1 = QGraphicsScene()
            self.scene1.addItem(self.item1)
            showImage2 = QtGui.QImage('./Results/PC2.tif')
            PC2 = QtGui.QPixmap.fromImage(showImage2)
            self.item2 = QGraphicsPixmapItem(PC2)
            self.scene2 = QGraphicsScene()
            self.scene2.addItem(self.item2)
            showImage3 = QtGui.QImage('./Results/PC3.tif')
            PC3 = QtGui.QPixmap.fromImage(showImage3)
            self.item3 = QGraphicsPixmapItem(PC3)
            self.scene3 = QGraphicsScene()
            self.scene3.addItem(self.item3)
            self.graphicsView.setScene(self.scene1)
            self.graphicsView.fitInView(QGraphicsPixmapItem(QPixmap(showImage1)))
            self.graphicsView_2.setScene(self.scene2)
            self.graphicsView_2.fitInView(QGraphicsPixmapItem(QPixmap(showImage2)))
            self.graphicsView_3.setScene(self.scene3)
            self.graphicsView_3.fitInView(QGraphicsPixmapItem(QPixmap(showImage3)))

        elif (test_predict[:, 1] >= test_predict[:, 0]) and (test_predict[:, 1] >= test_predict[:, 2]):
            input_shape = (51,51,1)
            model1 = Sequential()
            model1.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model1.add(MaxPool2D(pool_size=(2, 2)))

            model1.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model1.add(MaxPool2D(pool_size=(2, 2)))

            model1.add(Flatten())
            model1.add(Dense(1024, activation='relu'))
            model1.add(Dropout(0.5))
            model1.add(Dense(2048, activation='relu'))
            model1.add(Dense(2601))
            model1.summary()

            model1.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model2 = Sequential()
            model2.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model2.add(MaxPool2D(pool_size=(2, 2)))

            model2.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model2.add(MaxPool2D(pool_size=(2, 2)))

            model2.add(Flatten())
            model2.add(Dense(1024, activation='relu'))
            model2.add(Dropout(0.5))
            model2.add(Dense(2048, activation='relu'))
            model2.add(Dense(2601))
            model2.summary()

            model2.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model3 = Sequential()
            model3.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model3.add(MaxPool2D(pool_size=(2, 2)))

            model3.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model3.add(MaxPool2D(pool_size=(2, 2)))

            model3.add(Flatten())
            model3.add(Dense(1024, activation='relu'))
            model3.add(Dropout(0.5))
            model3.add(Dense(2048, activation='relu'))
            model3.add(Dense(2601))
            model3.summary()

            model3.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model4 = Sequential()
            model4.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model4.add(MaxPool2D(pool_size=(2, 2)))

            model4.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model4.add(MaxPool2D(pool_size=(2, 2)))

            model4.add(Flatten())
            model4.add(Dense(1024, activation='relu'))
            model4.add(Dropout(0.5))
            model4.add(Dense(2048, activation='relu'))
            model4.add(Dense(2601))
            model4.summary()

            model4.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])
            model1.load_weights('./Weights/MCNN4_1_weight_2021_03_18.h5')
            model2.load_weights('./Weights/MCNN4_2_weight_2021_03_18.h5')
            model3.load_weights('./Weights/MCNN4_3_weight_2021_03_18.h5')
            model4.load_weights('./Weights/MCNN4_4_weight_2021_03_18.h5')

            dataset = np.loadtxt('./Preprocess/row data.csv', delimiter=',')
            originx = dataset[0:2601]
            originx = originx / 9999
            testx = originx.reshape(-1, 51, 51, 1)
            test1_predict = model1.predict(testx, batch_size=1)
            Component1_predict = test1_predict.reshape(-1, 51, 51, 1)
            test2_predict = model2.predict(testx, batch_size=1)
            Component2_predict = test2_predict.reshape(-1, 51, 51, 1)
            test3_predict = model3.predict(testx, batch_size=1)
            Component3_predict = test3_predict.reshape(-1, 51, 51, 1)
            test4_predict = model4.predict(testx, batch_size=1)
            Component4_predict = test4_predict.reshape(-1, 51, 51, 1)

            plt.imshow(Component1_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC1.tif')
            plt.close()
            plt.imshow(Component2_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC2.tif')
            plt.close()
            plt.imshow(Component3_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC3.tif')
            plt.close()
            plt.imshow(Component4_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC4.tif')
            plt.close()

            for i in range(2601):
                p1 = open('./Results/test1_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p1)
                csv_writer.writerow(test1_predict[:, i])
                p1.close()
            df = pd.read_csv('./Results/test1_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test1_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test1_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component1.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p2 = open('./Results/test2_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p2)
                csv_writer.writerow(test2_predict[:, i])
                p2.close()
            df = pd.read_csv('./Results/test2_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test2_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test2_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component2.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p3 = open('./Results/test3_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p3)
                csv_writer.writerow(test3_predict[:, i])
                p3.close()
            df = pd.read_csv('./Results/test3_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test3_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test3_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component3.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p4 = open('./Results/test4_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p4)
                csv_writer.writerow(test4_predict[:, i])
                p4.close()
            df = pd.read_csv('./Results/test4_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test4_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test4_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component4.csv', header=0, index=0, mode='a')

            showImage1 = QtGui.QImage('./Results/PC1.tif')
            PC1 = QtGui.QPixmap.fromImage(showImage1)
            self.item1 = QGraphicsPixmapItem(PC1)
            self.scene1 = QGraphicsScene()
            self.scene1.addItem(self.item1)
            showImage2 = QtGui.QImage('./Results/PC2.tif')
            PC2 = QtGui.QPixmap.fromImage(showImage2)
            self.item2 = QGraphicsPixmapItem(PC2)
            self.scene2 = QGraphicsScene()
            self.scene2.addItem(self.item2)
            showImage3 = QtGui.QImage('./Results/PC3.tif')
            PC3 = QtGui.QPixmap.fromImage(showImage3)
            self.item3 = QGraphicsPixmapItem(PC3)
            self.scene3 = QGraphicsScene()
            self.scene3.addItem(self.item3)
            showImage4 = QtGui.QImage('./Results/PC4.tif')
            PC4 = QtGui.QPixmap.fromImage(showImage4)
            self.item4 = QGraphicsPixmapItem(PC4)
            self.scene4 = QGraphicsScene()
            self.scene4.addItem(self.item4)

            self.graphicsView.setScene(self.scene1)
            self.graphicsView.fitInView(QGraphicsPixmapItem(QPixmap(showImage1)))
            self.graphicsView_2.setScene(self.scene2)
            self.graphicsView_2.fitInView(QGraphicsPixmapItem(QPixmap(showImage2)))
            self.graphicsView_3.setScene(self.scene3)
            self.graphicsView_3.fitInView(QGraphicsPixmapItem(QPixmap(showImage3)))
            self.graphicsView_4.setScene(self.scene4)
            self.graphicsView_4.fitInView(QGraphicsPixmapItem(QPixmap(showImage4)))
        else:
            input_shape=(51,51,1)
            model1 = Sequential()
            model1.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model1.add(MaxPool2D(pool_size=(2, 2)))

            model1.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model1.add(MaxPool2D(pool_size=(2, 2)))

            model1.add(Flatten())
            model1.add(Dense(1024, activation='relu'))
            model1.add(Dropout(0.5))
            model1.add(Dense(2048, activation='relu'))
            model1.add(Dense(2601))
            model1.summary()

            model1.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model2 = Sequential()
            model2.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model2.add(MaxPool2D(pool_size=(2, 2)))

            model2.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model2.add(MaxPool2D(pool_size=(2, 2)))

            model2.add(Flatten())
            model2.add(Dense(1024, activation='relu'))
            model2.add(Dropout(0.5))
            model2.add(Dense(2048, activation='relu'))
            model2.add(Dense(2601))
            model2.summary()

            model2.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model3 = Sequential()
            model3.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model3.add(MaxPool2D(pool_size=(2, 2)))

            model3.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model3.add(MaxPool2D(pool_size=(2, 2)))

            model3.add(Flatten())
            model3.add(Dense(1024, activation='relu'))
            model3.add(Dropout(0.5))
            model3.add(Dense(2048, activation='relu'))
            model3.add(Dense(2601))
            model3.summary()

            model3.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model4 = Sequential()
            model4.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model4.add(MaxPool2D(pool_size=(2, 2)))

            model4.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model4.add(MaxPool2D(pool_size=(2, 2)))

            model4.add(Flatten())
            model4.add(Dense(1024, activation='relu'))
            model4.add(Dropout(0.5))
            model4.add(Dense(2048, activation='relu'))
            model4.add(Dense(2601))
            model4.summary()

            model4.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])

            model5 = Sequential()
            model5.add(Conv2D(filters=32, kernel_size=(4, 4),
                              activation='relu', input_shape=input_shape))
            model5.add(MaxPool2D(pool_size=(2, 2)))

            model5.add(Conv2D(filters=64, kernel_size=(3, 3),
                              activation='relu'))
            model5.add(MaxPool2D(pool_size=(2, 2)))

            model5.add(Flatten())
            model5.add(Dense(1024, activation='relu'))
            model5.add(Dropout(0.5))
            model5.add(Dense(2048, activation='relu'))
            model5.add(Dense(2601))
            model5.summary()
            model1.load_weights('./Weights/MCNN5_1_weight_2021_03_18.h5')
            model2.load_weights('./Weights/MCNN5_2_weight_2021_03_18.h5')
            model3.load_weights('./Weights/MCNN5_3_weight_2021_03_18.h5')
            model4.load_weights('./Weights/MCNN5_4_weight_2021_03_18.h5')
            model5.load_weights('./Weights/MCNN5_5_weight_2021_03_18.h5')

            model5.compile(loss='mse',
                           optimizer='adam',
                           metrics=['mae'])
            dataset = np.loadtxt('./Preprocess/row data.csv',delimiter=',')
            originx = dataset[0:2601]
            originx = originx / 9999
            testx = originx.reshape(-1, 51, 51, 1)
            test1_predict = model1.predict(testx, batch_size=1)
            Component1_predict = test1_predict.reshape(-1, 51, 51, 1)
            test2_predict = model2.predict(testx, batch_size=1)
            Component2_predict = test2_predict.reshape(-1, 51, 51, 1)
            test3_predict = model3.predict(testx, batch_size=1)
            Component3_predict = test3_predict.reshape(-1, 51, 51, 1)
            test4_predict = model4.predict(testx, batch_size=1)
            Component4_predict = test4_predict.reshape(-1, 51, 51, 1)
            test5_predict = model5.predict(testx, batch_size=1)
            Component5_predict = test5_predict.reshape(-1, 51, 51, 1)

            plt.imshow(Component1_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC1.tif')
            plt.close()
            plt.imshow(Component2_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC2.tif')
            plt.close()
            plt.imshow(Component3_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC3.tif')
            plt.close()
            plt.imshow(Component4_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC4.tif')
            plt.close()
            plt.imshow(Component5_predict[0], cmap='rainbow')
            plt.colorbar()
            plt.savefig('./Results/PC5.tif')
            plt.close()

            for i in range(2601):
                p1 = open('./Results/test1_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p1)
                csv_writer.writerow(test1_predict[:, i])
                p1.close()
            df = pd.read_csv('./Results/test1_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test1_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test1_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component1.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p2 = open('./Results/test2_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p2)
                csv_writer.writerow(test2_predict[:, i])
                p2.close()
            df = pd.read_csv('./Results/test2_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test2_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test2_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component2.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p3 = open('./Results/test3_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p3)
                csv_writer.writerow(test3_predict[:, i])
                p3.close()
            df = pd.read_csv('./Results/test3_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test3_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test3_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component3.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p4 = open('./Results/test4_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p4)
                csv_writer.writerow(test4_predict[:, i])
                p4.close()
            df = pd.read_csv('./Results/test4_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test4_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test4_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component4.csv', header=0, index=0, mode='a')

            for i in range(2601):
                p5 = open('./Results/test5_predict.csv', 'a', encoding='utf-8', newline='')
                csv_writer = csv.writer(p5)
                csv_writer.writerow(test5_predict[:, i])
                p5.close()
            df = pd.read_csv('./Results/test5_predict.csv')
            data = df.values
            index1 = list(df.keys())
            data = list(map(list, zip(*data)))
            data = pd.DataFrame(data, index=index1)
            data.to_csv('./Results/test5_predictT.csv', header=0)
            df2 = pd.read_csv('./Results/test5_predictT.csv', header=None)
            x = np.array(df2)
            x = np.reshape(x, (-1, 51))
            x = pd.DataFrame(x)
            x.to_csv('./Results/Component5.csv', header=0, index=0, mode='a')

            showImage1 = QtGui.QImage('./Results/PC1.tif')
            PC1 = QtGui.QPixmap.fromImage(showImage1)
            self.item1 = QGraphicsPixmapItem(PC1)
            self.scene1 = QGraphicsScene()
            self.scene1.addItem(self.item1)
            showImage2 = QtGui.QImage('./Results/PC2.tif')
            PC2 = QtGui.QPixmap.fromImage(showImage2)
            self.item2 = QGraphicsPixmapItem(PC2)
            self.scene2 = QGraphicsScene()
            self.scene2.addItem(self.item2)
            showImage3 = QtGui.QImage('./Results/PC3.tif')
            PC3 = QtGui.QPixmap.fromImage(showImage3)
            self.item3 = QGraphicsPixmapItem(PC3)
            self.scene3 = QGraphicsScene()
            self.scene3.addItem(self.item3)
            showImage4 = QtGui.QImage('./Results/PC4.tif')
            PC4 = QtGui.QPixmap.fromImage(showImage4)
            self.item4 = QGraphicsPixmapItem(PC4)
            self.scene4 = QGraphicsScene()
            self.scene4.addItem(self.item4)
            showImage5 = QtGui.QImage('./Results/PC5.tif')
            PC5 = QtGui.QPixmap.fromImage(showImage5)
            self.item5 = QGraphicsPixmapItem(PC5)
            self.scene5 = QGraphicsScene()
            self.scene5.addItem(self.item5)

            self.graphicsView.setScene(self.scene1)
            self.graphicsView.fitInView(QGraphicsPixmapItem(QPixmap(showImage1)))
            self.graphicsView_2.setScene(self.scene2)
            self.graphicsView_2.fitInView(QGraphicsPixmapItem(QPixmap(showImage2)))
            self.graphicsView_3.setScene(self.scene3)
            self.graphicsView_3.fitInView(QGraphicsPixmapItem(QPixmap(showImage3)))
            self.graphicsView_4.setScene(self.scene4)
            self.graphicsView_4.fitInView(QGraphicsPixmapItem(QPixmap(showImage4)))
            self.graphicsView_5.setScene(self.scene5)
            self.graphicsView_5.fitInView(QGraphicsPixmapItem(QPixmap(showImage5)))
        self.pushButton_3.setEnabled(False)


    def Clean(self):
        filelist1 = []
        filelist2 = []
        rootdir1 = r'./Preprocess'
        filelist1 = os.listdir(rootdir1)
        for f in filelist1:
            filepath1 = os.path.join(rootdir1, f)
            if os.path.isfile(filepath1):
                os.remove(filepath1)
        rootdir2 = r'./Results'
        filelist2 = os.listdir(rootdir2)
        for f in filelist2:
            filepath2 = os.path.join(rootdir2, f)
            if os.path.isfile(filepath2):
                os.remove(filepath2)

        self.pushButton_4.setEnabled(False)
        self.pushButton.setEnabled(True)
        self.pushButton_2.setEnabled(True)
        self.pushButton_3.setEnabled(True)
        self.listWidget.clear()
        showImageblank = QtGui.QImage('./blank.png')
        blank= QtGui.QPixmap.fromImage(showImageblank)
        self.itemblank = QGraphicsPixmapItem(blank)
        self.blank = QGraphicsScene()
        self.blank.addItem(self.itemblank)

        self.graphicsView.setScene(self.blank)
        self.graphicsView.fitInView(QGraphicsPixmapItem(QPixmap(showImageblank)))
        self.graphicsView_2.setScene(self.blank)
        self.graphicsView_2.fitInView(QGraphicsPixmapItem(QPixmap(showImageblank)))
        self.graphicsView_3.setScene(self.blank)
        self.graphicsView_3.fitInView(QGraphicsPixmapItem(QPixmap(showImageblank)))
        self.graphicsView_4.setScene(self.blank)
        self.graphicsView_4.fitInView(QGraphicsPixmapItem(QPixmap(showImageblank)))
        self.graphicsView_5.setScene(self.blank)
        self.graphicsView_5.fitInView(QGraphicsPixmapItem(QPixmap(showImageblank)))
        self.lineEdit.clear()
        self.lineEdit_2.clear()
        self.lineEdit_3.clear()
        self.lineEdit_4.clear()
        self.lineEdit_5.clear()
        self.lineEdit_6.clear()

    def about(self):
        QMessageBox.information(None, 'About FFI-Net','FFI-Net\n'
                                                      'Fast fluorescent identification network\n'
                                                      'Version 1.0\n'
                                                      'Runze Xu\n'
                                                      'Environmental College\n'
                                                      'Hohai University\n'
                                                      'China\n'
                                                      'Contact Person: Runze Xu\n'
                                                      'Email: runzexu@hhu.edu.cn')


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "FFI-Net V1.0"))
        self.pushButton.setText(_translate("MainWindow", "Input"))
        self.label_7.setText(_translate("MainWindow", "Structure of Input data"))
        self.label.setText(_translate("MainWindow", "ExL:"))
        self.label_2.setText(_translate("MainWindow", "ExU:"))
        self.label_3.setText(_translate("MainWindow", "ExI:"))
        self.label_4.setText(_translate("MainWindow", "EmL:"))
        self.label_6.setText(_translate("MainWindow", "EmU:"))
        self.label_5.setText(_translate("MainWindow", "EmI:"))
        self.pushButton_2.setText(_translate("MainWindow", "Preprocess"))
        self.pushButton_3.setText(_translate("MainWindow", "Run"))
        self.pushButton_4.setText(_translate("MainWindow", "Clean"))
        self.pushButton_5.setText(_translate("MainWindow", "Exit"))
        self.menuHelp.setTitle(_translate("MainWindow", "Help"))
        self.actionInput.setText(_translate("MainWindow", "Input"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))
        self.actionAbout_FFI_Net.setText(_translate("MainWindow", "About FFI-Net"))
        self.actionAbout_FFI_Net.triggered.connect(self.about)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)  
    MainWindow.show()
    sys.exit(app.exec_())

