def __init__(self, parent=None, setting=None):
        super(frmSelectSession, self).__init__(parent)
        # inputs
        self.SubRange = strRange(setting.SubRange, Unique=True)
        if self.SubRange is None:
            print("Subject Range is wrong!")
            return
        self.SubSize = len(self.SubRange)
        self.ConRange = strMultiRange(setting.ConRange, self.SubSize)
        if self.ConRange is None:
            print("Counter Range is wrong!")
            return

        self.RunRange = strMultiRange(setting.RunRange, self.SubSize)
        if self.RunRange is None:
            print("Run Range is wrong!")
            return

        # outputs
        self.SubID = None
        self.RunID = None
        self.ConID = None
        self.PASS = False

        layout = QFormLayout()

        self.lblSub = QLabel("Subject: ")
        self.txtSub = QComboBox()
        self.txtSub.addItem("", None)
        for subindx, sub in enumerate(self.SubRange):
            self.txtSub.addItem(str(sub), subindx)
        self.txtSub.currentIndexChanged.connect(self.txtSub_isChenged)
        layout.addRow(self.lblSub, self.txtSub)

        self.lblRun = QLabel("Run: ")
        self.txtRun = QComboBox()
        layout.addRow(self.lblRun, self.txtRun)

        self.lblCon = QLabel("Counter: ")
        self.txtCon = QComboBox()
        layout.addRow(self.lblCon, self.txtCon)

        self.lblTask = QLabel()
        self.lblTask.setText("Task:")
        self.txtTask = QLineEdit()
        self.txtTask.setText(setting.Task)
        self.txtTask.setReadOnly(True)
        layout.addRow(self.lblTask, self.txtTask)

        self.btnOK = QPushButton("OK")
        self.btnOK.clicked.connect(self.btnOK_onclick)

        self.btnCan = QPushButton("Cancel")
        self.btnCan.clicked.connect(self.btnCan_onclick)
        layout.addRow(self.btnCan, self.btnOK)

        self.setLayout(layout)
        self.setWindowTitle("Session Selector")
        self.exec_()
Exemple #2
0
    def Check(self,
              SettingFileName,
              isOne=False,
              SubID=None,
              RunID=None,
              ConID=None):
        import numpy as np
        import os
        from Base.utility import fixstr, setParameters3, strRange, strMultiRange
        from Base.Setting import Setting
        setting = Setting()
        setting.Load(SettingFileName)
        if setting.empty:
            print("Error in loading the setting file!")
            return False
        else:
            if isOne:
                Subjects = [SubID]
                Counters = [[ConID]]
                Runs = [[RunID]]
            else:
                Subjects = strRange(setting.SubRange, Unique=True)
                if Subjects is None:
                    print("Cannot load Subject Range!")
                    return False
                SubSize = len(Subjects)

                Counters = strMultiRange(setting.ConRange, SubSize)
                if Counters is None:
                    print("Cannot load Counter Range!")
                    return False

                Runs = strMultiRange(setting.RunRange, SubSize)
                if Runs is None:
                    print("Cannot load Run Range!")
                    return False

            for si, s in enumerate(Subjects):
                for cnt in Counters[si]:
                    print("Checking script for Subject %d ..." % (s))
                    for r in Runs[si]:
                        ScriptAddr = setParameters3(setting.Script, setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),\
                                fixstr(r, setting.RunLen, setting.RunPer), setting.Task, \
                                fixstr(cnt, setting.ConLen, setting.ConPer))

                        if os.path.isfile(ScriptAddr):
                            print("CHECK: " + ScriptAddr + " - checked!")
                        else:
                            print("CHECK: " + ScriptAddr + " - not found!")
                            return False
        return True
    def btnConvert_click(self):
        msgBox = QMessageBox()
        tStart = time.time()
        Activation = ui.cbActivation.currentData()
        LossNorm = ui.cbLossNorm.currentData()
        LossType = ui.cbType.currentData()
        try:
            Layers = strRange(ui.txtLayers.text(), Unique=False)
            if Layers is None:
                raise Exception('')

        except:
            msgBox.setText("Layers is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            Alpha = np.float32(ui.txtAlpha.text())
            if Alpha < 0:
                raise Exception
        except:
            msgBox.setText("Alpha is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            Iter = np.int32(ui.txtIter.text())
        except:
            msgBox.setText("Number of iteration is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            BatchSize = np.int32(ui.txtBatch.text())
        except:
            msgBox.setText("Number of batch is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            ReportStep = np.int32(ui.txtReportStep.text())
        except:
            msgBox.setText("Number of Report Step is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            LearningRate = np.float32(ui.txtRate.text())
        except:
            msgBox.setText("Number of Report Step is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if not ui.cbCov.isChecked() and not ui.cbCorr.isChecked():
            msgBox.setText("At least, you must select one metric!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Filter
        try:
            Filter = ui.txtFilter.text()
            if not len(Filter):
                Filter = None
            else:
                Filter = Filter.replace("\'", " ").replace(",", " ").replace(
                    "[", "").replace("]", "").split()
                Filter = np.int32(Filter)
        except:
            print("Filter is wrong!")
            return

        # OutFile
        OutFile = ui.txtOutFile.text()
        if not len(OutFile):
            msgBox.setText("Please enter out file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        OutData = dict()

        # InFile
        InFile = ui.txtInFile.text()
        if not len(InFile):
            msgBox.setText("Please enter input file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if not os.path.isfile(InFile):
            msgBox.setText("Input file not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Loading ...")
        InData = io.loadmat(InFile)

        # Data
        if not len(ui.txtData.currentText()):
            msgBox.setText("Please enter Input Data variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Label
        if not len(ui.txtLabel.currentText()):
            msgBox.setText("Please enter Train Label variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Design
        if not len(ui.txtDesign.currentText()):
            msgBox.setText("Please enter Input Design variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            Design = InData[ui.txtDesign.currentText()]
        except:
            msgBox.setText("Design value is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            X = InData[ui.txtData.currentText()]
            L = InData[ui.txtLabel.currentText()][0]
        except:
            print("Cannot load data or label")
            return

        # Task
        if not len(ui.txtTask.currentText()):
            msgBox.setText("Please enter Task variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        # Task Val
        if not len(ui.txtTaskVal.currentText()):
            msgBox.setText("Please enter Task value!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            TaskIDTitle = ui.txtTaskVal.currentText()
        except:
            msgBox.setText("Task value is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            TaskTitle = InData[ui.txtTask.currentText()][0]
        except:
            msgBox.setText("Task variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        TaskTitleUnique = np.unique(TaskTitle)
        Task = np.zeros(np.shape(TaskTitle))

        for ttinx, tt in enumerate(TaskTitle):
            for ttlinx, ttl in enumerate(TaskTitleUnique):
                if tt[0] == ttl:
                    Task[ttinx] = ttlinx + 1
                    break

        for ttlinx, ttl in enumerate(TaskTitleUnique):
            if TaskIDTitle == ttl:
                TaskID = ttlinx + 1
                break

        OutData["Task"] = TaskIDTitle

        # Subject
        if not len(ui.txtSubject.currentText()):
            msgBox.setText("Please enter Subject variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        # Subject Val
        if not len(ui.txtSubjectVal.currentText()):
            msgBox.setText("Please enter Subject value!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            SubID = np.int32(ui.txtSubjectVal.currentText())
        except:
            msgBox.setText("Subject value is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            Sub = InData[ui.txtSubject.currentText()][0]
        except:
            msgBox.setText("Subject variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        OutData["SubjectID"] = SubID

        # Run
        if not len(ui.txtRun.currentText()):
            msgBox.setText("Please enter Run variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        # Run Val
        if not len(ui.txtRunVal.currentText()):
            msgBox.setText("Please enter Run value!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            RunID = np.int32(ui.txtRunVal.currentText())
        except:
            msgBox.setText("Run value is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            Run = InData[ui.txtRun.currentText()][0]
        except:
            msgBox.setText("Run variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        OutData["RunID"] = RunID

        # Counter
        if not len(ui.txtCounter.currentText()):
            msgBox.setText("Please enter Counter variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        # Counter Val
        if not len(ui.txtCounterVal.currentText()):
            msgBox.setText("Please enter Counter value!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            ConID = np.int32(ui.txtCounterVal.currentText())
        except:
            msgBox.setText("Counter value is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            Con = InData[ui.txtCounter.currentText()][0]
        except:
            msgBox.setText("Counter variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        OutData["CounterID"] = ConID

        if Filter is not None:
            for fil in Filter:
                # Remove Training Set
                labelIndx = np.where(L == fil)[0]
                Design = np.delete(Design, labelIndx, axis=0)
                X = np.delete(X, labelIndx, axis=0)
                L = np.delete(L, labelIndx, axis=0)
                Task = np.delete(Task, labelIndx, axis=0)
                Sub = np.delete(Sub, labelIndx, axis=0)
                Run = np.delete(Run, labelIndx, axis=0)
                Con = np.delete(Con, labelIndx, axis=0)
                print("Class ID = " + str(fil) + " is removed from data.")

        # Select Task
        TaskIndex = np.where(Task == TaskID)
        Design = Design[TaskIndex, :][0]
        X = X[TaskIndex, :][0]
        L = L[TaskIndex]
        Sub = Sub[TaskIndex]
        Run = Run[TaskIndex]
        Con = Con[TaskIndex]
        # Select Subject
        SubIndex = np.where(Sub == SubID)
        Design = Design[SubIndex, :][0]
        X = X[SubIndex, :][0]
        L = L[SubIndex]
        Run = Run[SubIndex]
        Con = Con[SubIndex]
        # Select Counter
        ConIndex = np.where(Con == ConID)
        Design = Design[ConIndex, :][0]
        X = X[ConIndex, :][0]
        L = L[ConIndex]
        Run = Run[ConIndex]
        # Select Run
        RunIndex = np.where(Run == RunID)
        Design = Design[RunIndex, :][0]
        X = X[RunIndex, :][0]
        L = L[RunIndex]  # This will only use in supervised methods
        LUnique = np.unique(L)
        LNum = np.shape(LUnique)[0]
        OutData["Label"] = LUnique
        OutData["ModelAnalysis"] = "Tensorflow.Session.Deep.RSA"

        if np.shape(X)[0] == 0:
            msgBox.setText("The selected data is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.cbScale.isChecked():
            X = preprocessing.scale(X)
            print("Data is scaled to N(0,1).")
        print("Running Deep RSA ...")
        # RSA Method
        OutData['Method'] = dict()
        OutData['Method']['Layers'] = ui.txtLayers.text()
        OutData['Method']['Alpha'] = Alpha
        OutData['Method']['Activation'] = Activation
        OutData['Method']['LossNorm'] = LossNorm
        OutData['Method']['LearningRate'] = LearningRate
        OutData['Method']['NumIter'] = Iter
        OutData['Method']['BatchSize'] = BatchSize
        OutData['Method']['ReportStep'] = ReportStep
        OutData['Method']['Verbose'] = ui.cbVerbose.isChecked()

        rsa = DeepRSA(layers=Layers, n_iter=Iter, learning_rate=LearningRate,loss_norm=LossNorm,activation=Activation,\
                      batch_size=BatchSize,report_step=ReportStep,verbose=ui.cbVerbose.isChecked(),\
                      CPU=ui.cbDevice.currentData(), alpha=Alpha, loss_type=LossType)
        Betas, Weights, Biases, loss_vec, MSE, Performance = rsa.fit(
            data_vals=X, design_vals=Design)

        OutData["LossVec"] = loss_vec
        OutData["MSE"] = MSE
        OutData["Performance"] = Performance

        print("MSE: %f" % (MSE))

        if ui.cbBeta.isChecked():
            OutData["Betas"] = Betas
            OutData["Weights"] = Weights
            OutData["Biases"] = Biases

        # Calculate Results
        if ui.cbCorr.isChecked():
            print("Calculating Correlation ...")
            Corr = np.corrcoef(Betas)
            corClass = SimilarityMatrixBetweenClass(Corr)
            OutData["Correlation"] = Corr
            OutData["Correlation_min"] = corClass.min()
            OutData["Correlation_max"] = corClass.max()
            OutData["Correlation_std"] = corClass.std()
            OutData["Correlation_mean"] = corClass.mean()
            print("Correlation: min: {:3.10f}, max: {:3.10f}, mean: {:3.10f}, std: {:3.10f}".format(corClass.min(), \
                    corClass.max(), corClass.mean(), corClass.std()))

        if ui.cbCov.isChecked():
            print("Calculating Covariance ...")
            Cov = np.cov(Betas)
            covClass = SimilarityMatrixBetweenClass(Cov)
            OutData["Covariance"] = Cov
            OutData["Covariance_min"] = covClass.min()
            OutData["Covariance_max"] = covClass.max()
            OutData["Covariance_std"] = covClass.std()
            OutData["Covariance_mean"] = covClass.mean()
            print("Covariance: min: {:3.10f}, max: {:3.10f}, mean: {:3.10f}, std: {:3.10f}".format(covClass.min(), \
                    covClass.max(), covClass.mean(), covClass.std()))

        OutData["RunTime"] = time.time() - tStart
        print("Runtime (s): %f" % (OutData["RunTime"]))
        print("Saving results ...")
        io.savemat(OutFile, mdict=OutData, do_compression=True)
        print("Output is saved.")

        if ui.cbDiagram.isChecked():
            if ui.cbCorr.isChecked():
                fig1 = plt.figure(num=None, figsize=(5, 5), dpi=100)
                plt.pcolor(Corr, vmin=-0.1, vmax=1)
                plt.xlim([0, LNum])
                plt.ylim([0, LNum])
                plt.colorbar()
                ax = plt.gca()
                ax.set_aspect(1)
                plt.title(
                    'DeepRSA: Correlation\nTask: %s\nSub: %d, Counter: %d, Run: %d'
                    % (TaskIDTitle, SubID, ConID, RunID))
                plt.show()

            if ui.cbCov.isChecked():
                fig2 = plt.figure(num=None, figsize=(5, 5), dpi=100)
                plt.pcolor(Cov)
                plt.xlim([0, LNum])
                plt.ylim([0, LNum])
                plt.colorbar()
                ax = plt.gca()
                ax.set_aspect(1)
                plt.title(
                    'DeepRSA: Covariance\nTask: %s\nSub: %d, Counter: %d, Run: %d'
                    % (TaskIDTitle, SubID, ConID, RunID))
                plt.show()
        print("DONE.")
        msgBox.setText(
            "Gradient Representational Similarity Analysis (RSA) is done.")
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()
Exemple #4
0
    def checkValue(self, ui, checkFiles=True, checkGeneratedFiles=False):
        self.empty = True
        msgBox = QMessageBox()

        FSLDIR = ui.txtFSLDIR.text()
        if (os.path.isfile(ui.txtMNI.currentText()) == False):
            msgBox = QMessageBox()
            msgBox.setText("Cannot find MNI file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if (os.path.isfile(FSLDIR + ui.txtFeat.text()) == False):
            msgBox = QMessageBox()
            msgBox.setText("Cannot find feat cmd!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if (os.path.isfile(FSLDIR + ui.txtFeat_gui.text()) == False):
            msgBox = QMessageBox()
            msgBox.setText("Cannot find Feat_gui cmd!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        mainDIR = ui.txtDIR.text()
        if not len(mainDIR):
            msgBox.setText("There is no main directory")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if not os.path.isdir(mainDIR):
            msgBox.setText("Main directory doesn't exist")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Main directory is okay.")

        Task = ui.txtTask.currentText()
        if not len(Task):
            msgBox.setText("There is no task title")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            SubRange = strRange(ui.txtSubRange.text(), Unique=True)
            if SubRange is None:
                raise Exception
            SubSize = len(SubRange)
        except:
            msgBox.setText("Subject Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Range of subjects is okay!")
        try:
            SubLen = np.int32(ui.txtSubLen.text())
            1 / SubLen
        except:
            msgBox.setText("Length of subjects must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of subjects is okay!")

        try:
            ConRange = strMultiRange(ui.txtConRange.text(), SubSize)
            if ConRange is None:
                raise Exception
            if not (len(ConRange) == SubSize):
                msgBox.setText("Counter Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Counter Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Counter Range is okay!")
        try:
            ConLen = np.int32(ui.txtConLen.text())
            1 / ConLen
        except:
            msgBox.setText("Length of counter must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of Counter is okay!")

        try:
            RunRange = strMultiRange(ui.txtRunRange.text(), SubSize)
            if RunRange is None:
                raise Exception
            if not (len(RunRange) == SubSize):
                msgBox.setText("Run Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Run Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Run Range is okay!")
        try:
            RunLen = np.int32(ui.txtRunLen.value())
            1 / RunLen
        except:
            msgBox.setText("Length of runs must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of runs is valid")

        # Check fMRI Images
        try:
            TR = np.double(ui.txtTR.text())
            1 / TR
        except:
            msgBox.setText("TR must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if TR <= 0:
            msgBox.setText("TR must be a positive number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("TR is okay")

        try:
            FWHM = np.double(ui.txtFWHM.text())
            1 / FWHM
        except:
            msgBox.setText("FWHM must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if FWHM <= 0:
            msgBox.setText("FWHM must be a positive number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("FWHM is okay")

        try:
            TotalVol = np.int32(ui.txtTotalVol.value())
        except:
            msgBox.setText("Total Volumn must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if TotalVol < 0:
            msgBox.setText("Total Volumn must be a positive number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Total Volumn is okay")

        try:
            DeleteVol = np.int32(ui.txtDeleteVol.value())
        except:
            msgBox.setText("Delete Volumn must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if DeleteVol < 0:
            msgBox.setText("Delete Volumn must be a positive number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Delete Volumn is okay")

        try:
            HighPass = np.double(ui.txtHighPass.text())
        except:
            msgBox.setText("High Pass cutoff must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if HighPass <= 0:
            msgBox.setText("High Pass cutoff must be a positive number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("High Pass cutoff is okay")

        try:
            DENL = np.double(ui.txtDENL.text())
        except:
            msgBox.setText("Noise level must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Noise level is okay")

        try:
            DETS = np.double(ui.txtDETS.text())
        except:
            msgBox.setText("Temporal smoothness must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Temporal smoothness is okay")

        try:
            DEZT = np.double(ui.txtDEZT.text())
        except:
            msgBox.setText(
                "Z threshold in the design efficiency must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Z threshold in the design efficiency is okay")

        try:
            CTZT = np.double(ui.txtCTZT.text())
        except:
            msgBox.setText("Z threshold in the clustering must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Z threshold in the clustering is okay")

        try:
            CTPT = np.double(ui.txtCTPT.text())
        except:
            msgBox.setText("Clustering P threshold must be a number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Clustering P threshold is okay")

        if ui.txtBOLD.text() == "":
            msgBox.setText("Structure of the BOLD files is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtScript.text() == "":
            msgBox.setText("Structure of the script files is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtAnat.text() == "":
            msgBox.setText("Structure of the Anatomical files is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtOnset.text() == "":
            msgBox.setText("Structure of the BOLD files is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtBET.text() == "":
            msgBox.setText("Structure of the BET files is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtBETPDF.text() == "":
            msgBox.setText("Structure of the BET report (PDF) is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtAnalysis.text() == "":
            msgBox.setText("Structure of the analysis folder is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtEventDIR.text() == "":
            msgBox.setText("Structure of the event folders is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtCondPre.text() == "":
            msgBox.setText("The prefix of condition files is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        ECodes = ui.txtEvents.toPlainText()
        if ECodes == "":
            msgBox.setText("Event code is empty")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Event codes are okay")

        if checkFiles:
            print("Validating files ...")
            for si, s in enumerate(SubRange):
                for c in ConRange[si]:
                    print("Analyzing Subject %d, Counter %d ..." % (s, c))
                    # checking anat file
                    addr =  setParameters3(ui.txtAnat.text(),mainDIR, fixstr(s, SubLen, ui.txtSubPer.text()), "",\
                                           ui.txtTask.currentText(),fixstr(c, ConLen, ui.txtConPer.text()))
                    if os.path.isfile(addr):
                        print(addr, " - OKAY.")
                    else:
                        print(addr, " - file not find!")
                        return False
                    if checkGeneratedFiles and ui.cbRegAnat.isChecked():
                        # BET Files
                        addr = setParameters3(
                            ui.txtBET.text(), mainDIR,
                            fixstr(s, SubLen, ui.txtSubPer.text()), "",
                            ui.txtTask.currentText(),
                            fixstr(c, ConLen, ui.txtConPer.text()))
                        if os.path.isfile(addr):
                            print(addr, " - OKAY.")
                        else:
                            print(addr, " - file not find!")
                            return False

                    for r in RunRange[si]:

                        # BOLD File Check
                        addr = setParameters3(ui.txtBOLD.text(),mainDIR, fixstr(s, SubLen, ui.txtSubPer.text()), \
                                                 fixstr(r,RunLen,ui.txtRunPer.text()), ui.txtTask.currentText(),fixstr(c, ConLen, ui.txtConPer.text()))
                        if os.path.isfile(addr):
                            print(addr, " - OKAY.")
                        else:
                            print(addr, " - file not find!")
                            return False

                        # Event File Check
                        if ui.cbMode.currentIndex() == 0:
                            addr = setParameters3(ui.txtOnset.text(), mainDIR, fixstr(s, SubLen, ui.txtSubPer.text()), \
                                                     fixstr(r,RunLen,ui.txtRunPer.text()), ui.txtTask.currentText(),fixstr(c, ConLen, ui.txtConPer.text()))
                            if os.path.isfile(addr):
                                print(addr, " - OKAY.")
                            else:
                                print(addr, " - file not find!")
                                return False

                        if checkGeneratedFiles and ui.cbMode.currentIndex(
                        ) == 0:
                            addr = setParameters3(ui.txtEventDIR.text(),mainDIR, fixstr(s, SubLen, ui.txtSubPer.text()), \
                                                 fixstr(r,RunLen,ui.txtRunPer.text()), ui.txtTask.currentText(),fixstr(c, ConLen, ui.txtConPer.text()))
                            if os.path.isdir(addr):
                                print(addr, " - OKAY.")
                                try:
                                    Cond = io.loadmat(addr +
                                                      ui.txtCondPre.text() +
                                                      ".mat")
                                    for fileID in range(
                                            1, Cond["Cond"].shape[0] + 1):
                                        if os.path.isfile(
                                                addr + ui.txtCondPre.text() +
                                                "_" + str(fileID) + ".tab"):
                                            print(addr + ui.txtCondPre.text() +
                                                  "_" + str(fileID) +
                                                  ".tab - OKAY.")
                                        else:
                                            print(addr + ui.txtCondPre.text() +
                                                  "_" + str(fileID) +
                                                  ".tab - file not find!")
                                            return False
                                except:
                                    print(addr + ui.txtCondPre.text() +
                                          ".mat - loading error!")
                                    return False
                            else:
                                print(addr + ui.txtCondPre.text() +
                                      ".mat - file not find!")
                                return False

        self.Version = getSettingVersion()
        self.Mode = ui.cbMode.currentIndex()
        self.mainDIR = mainDIR
        self.MNISpace = ui.txtMNI.currentText()
        self.SubRange = ui.txtSubRange.text()
        self.SubLen = SubLen
        self.SubPer = ui.txtSubPer.text()
        self.ConRange = ui.txtConRange.text()
        self.ConLen = ConLen
        self.ConPer = ui.txtConPer.text()
        self.Task = str(Task)
        self.RunRange = ui.txtRunRange.text()
        self.RunLen = str(RunLen)
        self.RunPer = ui.txtRunPer.text()
        self.BOLD = ui.txtBOLD.text()
        self.Onset = ui.txtOnset.text()
        self.AnatDIR = ui.txtAnat.text()
        self.BET = ui.txtBET.text()
        self.BETPDF = ui.txtBETPDF.text()
        self.Analysis = ui.txtAnalysis.text()
        self.Script = ui.txtScript.text()
        self.EventFolder = ui.txtEventDIR.text()
        self.EventCodes = ui.txtEvents.toPlainText()
        self.CondPre = ui.txtCondPre.text()
        self.TR = TR
        self.FWHM = FWHM
        self.DeleteVol = DeleteVol
        self.TotalVol = TotalVol
        self.HighPass = HighPass
        self.DENL = DENL
        self.DETS = DETS
        self.DEZT = DEZT
        self.CTZT = CTZT
        self.CTPT = CTPT

        TimeSlice = getTimeSliceID(ui.cbSliceTime.currentText())
        if TimeSlice is None:
            print("Error in Slice Time!")
            return False
        self.TimeSlice = np.int32(TimeSlice)
        self.Motion = ui.cbMotionCorrection.isChecked()
        self.Anat = ui.cbRegAnat.isChecked()
        self.empty = False
        return True
Exemple #5
0
    def run(self,SettingFileName, betcmd=None):
        import os

        from Base.utility import fixstr,setParameters3, strRange, strMultiRange
        from Base.Setting import Setting

        if betcmd is None:
            print("Cannot find bet cmd")
            return

        if not os.path.isfile(betcmd):
            print("Cannot find bet cmd")
            return

        setting = Setting()
        setting.Load(SettingFileName)
        if (setting.empty) or (setting.Anat == False) :
            if setting.empty:
                print("Error in loading the setting file!")
            if not setting.Anat:
                print("This feature is disable for in setting file. Please turn it on from Advance menu!")
            return False
        else:

            Subjects = strRange(setting.SubRange,Unique=True)
            if Subjects is None:
                print("Cannot load Subject Range!")
                return False
            SubSize = len(Subjects)

            Counters = strMultiRange(setting.ConRange,SubSize)
            if Counters is None:
                print("Cannot load Counter Range!")
                return False

            Runs = strMultiRange(setting.RunRange,SubSize)
            if Runs is None:
                print("Cannot load Run Range!")
                return False

            Jobs = list()
            for sindx, s in enumerate(Subjects):
                  for cnt in Counters[sindx]:
                        print("Analyzing Subject %d, Counter %d ..." % (s, cnt))
                        InAddr = setParameters3(setting.AnatDIR,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),"", setting.Task,
                                                   fixstr(cnt, setting.ConLen, setting.ConPer))
                        InFile = setParameters3(setting.AnatDIR,"", fixstr(s, setting.SubLen, setting.SubPer),"", setting.Task,
                                                   fixstr(cnt, setting.ConLen, setting.ConPer))
                        OutAddr = setParameters3(setting.BET,setting.mainDIR,fixstr(s, setting.SubLen, setting.SubPer),"", setting.Task,
                                                    fixstr(cnt, setting.ConLen, setting.ConPer))
                        PDFAddr = setParameters3(setting.BETPDF,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),"", setting.Task,
                                                    fixstr(cnt, setting.ConLen, setting.ConPer))
                        if not os.path.isfile(InAddr):
                            print(InAddr, " - file not find!")
                            return False
                        else:
                            files = [OutAddr, PDFAddr]
                            thread = BrainExtractorThread(bet=betcmd, InAddr=InAddr, OutAddr=OutAddr, PDFAddr=PDFAddr,\
                                                          InFile=InFile, files=files)
                            Jobs.append(["BrainExtractor", InFile, thread])
                            print("Job: Anatomical Brain Extractor for Subject %d, Counter %d is created." % (s, cnt))
            return True, Jobs
Exemple #6
0
    def run(self,SettingFileName):

        from Base.utility import fixstr,setParameters3, strRange, strMultiRange
        from Base.Setting import Setting
        setting = Setting()
        setting.Load(SettingFileName)
        if setting.empty:
            print("Error in loading the setting file!")
            return False
        else:
            Subjects = strRange(setting.SubRange,Unique=True)
            if Subjects is None:
                print("Cannot load Subject Range!")
                return False
            SubSize = len(Subjects)

            Counters = strMultiRange(setting.ConRange,SubSize)
            if Counters is None:
                print("Cannot load Counter Range!")
                return False

            Runs = strMultiRange(setting.RunRange,SubSize)
            if Runs is None:
                print("Cannot load Run Range!")
                return False

            for si, s in enumerate(Subjects):
                  for cnt in Counters[si]:
                        print("Analyzing Subject %d, Counter %d ..." % (s, cnt))
                        for r in Runs[si]:
                            ScriptAddr = setParameters3(setting.Script,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),\
                                                           fixstr(r, setting.RunLen, setting.RunPer), setting.Task,\
                                                           fixstr(cnt, setting.ConLen, setting.ConPer))


                            ScriptOutputAddr = setParameters3(setting.Analysis,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),\
                                                               fixstr(r, setting.RunLen, setting.RunPer), setting.Task,\
                                                           fixstr(cnt, setting.ConLen, setting.ConPer))

                            BOLDaddr = setParameters3(setting.BOLD,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),\
                                                        fixstr(r, setting.RunLen, setting.RunPer), setting.Task,\
                                                           fixstr(cnt, setting.ConLen, setting.ConPer))

                            MRIFile = nb.load(BOLDaddr)

                            # Generate Script
                            scriptFile = open(ScriptAddr,"w")
                            scriptFile.write("\n# FEAT version number\nset fmri(version) 6.00\n\n# Are we in MELODIC?\nset fmri(inmelodic) 0\n\n")
                            scriptFile.write("# Analysis level\n# 1 : First-level analysis\n# 2 : Higher-level analysis\nset fmri(level) 1\n\n")
                            scriptFile.write("# Which stages to run\n# 0 : No first-level analysis (registration and/or group stats only)\n")
                            scriptFile.write("# 7 : Full first-level analysis\n# 1 : Pre-processing\n# 2 : Statistics\nset fmri(analysis) 7\n\n")
                            scriptFile.write("# Use relative filenames\nset fmri(relative_yn) 0\n\n")
                            scriptFile.write("# Balloon help\nset fmri(help_yn) 1\n\n")
                            scriptFile.write("# Run Featwatcher\nset fmri(featwatcher_yn) 0\n\n")
                            scriptFile.write("# Cleanup first-level standard-space images\nset fmri(sscleanup_yn) 0\n\n")
                            scriptFile.write("# Output directory\nset fmri(outputdir) \"" + ScriptOutputAddr + "\"\n\n")
                            # TR
                            scriptFile.write("# TR(s)\nset fmri(tr) %0.6f \n\n" % setting.TR)
                            # Total Volumes
                            if setting.TotalVol == 0:
                                print("Auto Detect Total Volumes = " + str(get_mri_shape(MRIFile)[3]) + ", File: " + BOLDaddr)
                                scriptFile.write("# Total volumes\nset fmri(npts) " + str(get_mri_shape(MRIFile)[3]) + "\n\n")
                            else:
                                scriptFile.write("# Total volumes\nset fmri(npts) " + str(setting.TotalVol) + "\n\n")
                            # Delete Volumes
                            scriptFile.write("# Delete volumes\nset fmri(ndelete) " + str(setting.DeleteVol) + "\n\n")

                            scriptFile.write("# Perfusion tag/control order\nset fmri(tagfirst) 1\n\n")
                            scriptFile.write("# Number of first-level analyses\nset fmri(multiple) 1\n\n")
                            scriptFile.write("# Higher-level input type\n# 1 : Inputs are lower-level FEAT directories\n# 2 : Inputs are cope images from FEAT directories\nset fmri(inputtype) 2\n\n")
                            scriptFile.write("# Carry out pre-stats processing?\nset fmri(filtering_yn) 1\n\n")
                            scriptFile.write("# Brain/background threshold, %\nset fmri(brain_thresfh) 10\n\n")
                            scriptFile.write("# Critical z for design efficiency calculation\nset fmri(critical_z) " + str(setting.DEZT) + "\n\n")
                            scriptFile.write("# Noise level\nset fmri(noise) " + str(setting.DENL) + "\n\n# Noise AR(1)\nset fmri(noisear) " + str(setting.DETS) + "\n\n")
                            # Motion Correction: ALWAYS ON
                            scriptFile.write("# Motion correction\n# 0 : None\n# 1 : MCFLIRT\nset fmri(mc) 1\n\n")

                            scriptFile.write("# Spin-history (currently obsolete)\nset fmri(sh_yn) 0\n\n")
                            scriptFile.write("# B0 fieldmap unwarping?\nset fmri(regunwarp_yn) 0\n\n")
                            scriptFile.write("# EPI dwell time (ms)\nset fmri(dwell) 0.7\n\n")
                            scriptFile.write("# EPI TE (ms)\nset fmri(te) 35\n\n")
                            scriptFile.write("# % Signal loss threshold\nset fmri(signallossthresh) 10\n\n")
                            scriptFile.write("# Unwarp direction\nset fmri(unwarp_dir) y-\n\n")
                            scriptFile.write("# Slice timing correction\n# 0 : None\n# 1 : Regular up (0, 1, 2, 3, ...)\n# 2 : Regular down\n")
                            scriptFile.write("# 3 : Use slice order file\n# 4 : Use slice timings file\n# 5 : Interleaved (0, 2, 4 ... 1, 3, 5 ... )\n")
                            # Slice Timing
                            scriptFile.write("set fmri(st) " + str(setting.TimeSlice) + "\n\n")

                            scriptFile.write("# Slice timings file\nset fmri(st_file) \"\"\n\n")
                            scriptFile.write("# BET brain extraction\nset fmri(bet_yn) 1\n\n")
                            # FWHM
                            scriptFile.write("# Spatial smoothing FWHM (mm)\nset fmri(smooth) " + str(setting.FWHM) + "\n\n")

                            scriptFile.write("# Intensity normalization\nset fmri(norm_yn) 0\n\n")
                            scriptFile.write("# Perfusion subtraction\nset fmri(perfsub_yn) 0\n\n")
                            scriptFile.write("# Highpass temporal filtering\nset fmri(temphp_yn) 1\n\n")
                            scriptFile.write("# Lowpass temporal filtering\nset fmri(templp_yn) 0\n\n")
                            scriptFile.write("# MELODIC ICA data exploration\nset fmri(melodic_yn) 0\n\n")
                            scriptFile.write("# Carry out main stats?\nset fmri(stats_yn) 1\n\n")
                            scriptFile.write("# Carry out prewhitening?\nset fmri(prewhiten_yn) 1\n\n")
                            scriptFile.write("# Add motion parameters to model\n# 0 : No\n# 1 : Yes\nset fmri(motionevs) 1\nset fmri(motionevsbeta) \"\"\nset fmri(scriptevsbeta) \"\"\n\n")
                            scriptFile.write("# Robust outlier detection in FLAME?\nset fmri(robust_yn) 0\n\n")
                            scriptFile.write("# Higher-level modelling\n# 3 : Fixed effects\n# 0 : Mixed Effects: Simple OLS\n# 2 : Mixed Effects: FLAME 1\n# 1 : Mixed Effects: FLAME 1+2\nset fmri(mixed_yn) 2\n\n")
                            # Conditions
                            ConditionFile =  setParameters3(setting.EventFolder,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),\
                                                        fixstr(r, setting.RunLen, setting.RunPer), setting.Task, fixstr(cnt, setting.ConLen, setting.ConPer)) + setting.CondPre + ".mat"

                            Cond = io.loadmat(ConditionFile)
                            Conditions = Cond["Cond"]
                            CondLen = len(Conditions)
                            scriptFile.write("# Number of EVs\nset fmri(evs_orig) "+str(CondLen)+"\nset fmri(evs_real) "+str(CondLen)+"\nset fmri(evs_vox) 0\n\n")
                            scriptFile.write("# Number of contrasts\nset fmri(ncon_orig) "+str(CondLen)+"\nset fmri(ncon_real) "+str(CondLen)+"\n\n")

                            scriptFile.write("# Number of F-tests\nset fmri(nftests_orig) 0\nset fmri(nftests_real) 0\n\n")
                            scriptFile.write("# Add constant column to design matrix? (obsolete)\nset fmri(constcol) 0\n\n")
                            scriptFile.write("# Carry out post-stats steps?\nset fmri(poststats_yn) 1\n\n")
                            scriptFile.write("# Pre-threshold masking?\nset fmri(threshmask) \"\"\n\n")

                            # Clustering
                            scriptFile.write("# Thresholding\n# 0 : None\n# 1 : Uncorrected\n# 2 : Voxel\n# 3 : Cluster\nset fmri(thresh) 3\n\n")
                            scriptFile.write("# P threshold\nset fmri(prob_thresh) " + str(setting.CTPT) + "\n\n")

                            scriptFile.write("# Z threshold\nset fmri(z_thresh) " + str(setting.CTZT) + "\n\n")
                            scriptFile.write("# Z min/max for colour rendering\n# 0 : Use actual Z min/max\n# 1 : Use preset Z min/max\nset fmri(zdisplay) 0\n\n")
                            scriptFile.write("# Z min in colour rendering\nset fmri(zmin) 2\n\n")
                            scriptFile.write("# Z max in colour rendering\nset fmri(zmax) 8\n\n")
                            scriptFile.write("# Colour rendering type\n# 0 : Solid blobs\n# 1 : Transparent blobs\nset fmri(rendertype) 1\n\n")
                            scriptFile.write("# Background image for higher-level stats overlays\n# 1 : Mean highres\n# 2 : First highres\n# 3 : Mean functional\n# 4 : First functional\n# 5 : Standard space template\nset fmri(bgimage) 1\n\n")
                            scriptFile.write("# Create time series plots\nset fmri(tsplot_yn) 1\n\n")
                            scriptFile.write("# Registration to initial structural\nset fmri(reginitial_highres_yn) 0\n\n")
                            scriptFile.write("# Search space for registration to initial structural\n# 0   : No search\n# 90  : Normal search\n# 180 : Full search\nset fmri(reginitial_highres_search) 90\n\n")
                            scriptFile.write("# Degrees of Freedom for registration to initial structural\nset fmri(reginitial_highres_dof) 3\n\n")

                            # Anat
                            if setting.Anat:
                                scriptFile.write("# Registration to main structural\nset fmri(reghighres_yn) 1\n\n")
                                scriptFile.write("# Search space for registration to main structural\n# 0   : No search\n# 90  : Normal search\n# 180 : Full search\nset fmri(reghighres_search) 90\n\n")
                                scriptFile.write("# Degrees of Freedom for registration to main structural\nset fmri(reghighres_dof) 12\n\n")

                            else:
                                scriptFile.write("# Registration to main structural\nset fmri(reghighres_yn) 0\n\n")
                                scriptFile.write("# Search space for registration to main structural\n# 0   : No search\n# 90  : Normal search\n# 180 : Full search\nset fmri(reghighres_search) 90\n\n")
                                scriptFile.write("# Degrees of Freedom for registration to main structural\nset fmri(reghighres_dof) BBR\n\n")

                            # Standard Space
                            scriptFile.write("# Registration to standard image?\nset fmri(regstandard_yn) 1\n\n")
                            scriptFile.write("# Use alternate reference images?\nset fmri(alternateReference_yn) 0\n\n")

                            # Get {FSLDIR}
                            #StandardTemp = os.path.dirname(os.path.realpath(__file__)) + "/MNI152_T1_2mm_brain"
                            scriptFile.write("# Standard image\nset fmri(regstandard) \"" + setting.MNISpace + "\"\n\n")

                            scriptFile.write("# Search space for registration to standard space\n# 0   : No search\n# 90  : Normal search\n# 180 : Full search\nset fmri(regstandard_search) 90\n\n")
                            scriptFile.write("# Degrees of Freedom for registration to standard space\nset fmri(regstandard_dof) 12\n\n")
                            scriptFile.write("# Do nonlinear registration from structural to standard space?\nset fmri(regstandard_nonlinear_yn) 0\n\n")
                            scriptFile.write("# Control nonlinear warp field resolution\nset fmri(regstandard_nonlinear_warpres) 10 \n\n")

                            # High Pass
                            scriptFile.write("# High pass filter cutoff\nset fmri(paradigm_hp) %d\n\n" % setting.HighPass)


                            # Total Voxel
                            TotalVoxel = get_mri_shape(MRIFile)[0] * get_mri_shape(MRIFile)[1] * get_mri_shape(MRIFile)[2] * get_mri_shape(MRIFile)[3]
                            scriptFile.write("# Total voxels\nset fmri(totalVoxels) " + str(TotalVoxel) + "\n\n\n")

                            scriptFile.write("# Number of lower-level copes feeding into higher-level analysis\nset fmri(ncopeinputs) 0\n\n")
                            scriptFile.write("# 4D AVW data or FEAT directory (1)\nset feat_files(1) \"" + BOLDaddr + "\"\n\n")
                            scriptFile.write("# Add confound EVs text file\nset fmri(confoundevs) 0\n\n")
                            # Align to structural MRI
                            if setting.Anat:
                                AnatAddr = setParameters3(setting.BET,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer),"",setting.Task,\
                                                           fixstr(cnt, setting.ConLen, setting.ConPer))

                                scriptFile.write("# Subject's structural image for analysis 1\nset highres_files(1) \"" + AnatAddr + "\"\n\n")

                            # Condition Files
                            for cond in range(1,CondLen + 1):
                                scriptFile.write("# EV " + str(cond) + " title\nset fmri(evtitle"+str(cond)+") \""+Conditions[cond-1][1][0]+"\"\n\n")
                                scriptFile.write("# Basic waveform shape (EV " + str(cond) + ")\n# 0 : Square\n# 1 : Sinusoid\n# 2 : Custom (1 entry per volume)\n# 3 : Custom (3 column format)\n# 4 : Interaction\n# 10 : Empty (all zeros)\nset fmri(shape" + str(cond) + ") 3\n\n")
                                scriptFile.write("# Convolution (EV " + str(cond) + ")\n# 0 : None\n# 1 : Gaussian\n# 2 : Gamma\n# 3 : Double-Gamma HRF\n# 4 : Gamma basis functions\n# 5 : Sine basis functions\n# 6 : FIR basis functions\nset fmri(convolve" + str(cond) + ") 2\n\n")
                                scriptFile.write("# Convolve phase (EV " + str(cond) + ")\nset fmri(convolve_phase" + str(cond) + ") 0\n\n")
                                scriptFile.write("# Apply temporal filtering (EV " + str(cond) + ")\nset fmri(tempfilt_yn" + str(cond) + ") 1\n\n")
                                scriptFile.write("# Add temporal derivative (EV " + str(cond) + ")\nset fmri(deriv_yn" + str(cond) + ") 0\n\n")
                                ConditionFile =  setParameters3(setting.EventFolder,setting.mainDIR, fixstr(s, setting.SubLen,setting.SubPer), \
                                                                                fixstr(r, setting.RunLen, setting.RunPer), setting.Task,\
                                                           fixstr(cnt, setting.ConLen, setting.ConPer)) + setting.CondPre + "_" +  str(cond) + ".tab"
                                scriptFile.write("# Custom EV file (EV " + str(cond) + ")\nset fmri(custom" + str(cond) + ") \"" + ConditionFile + "\"\n\n")
                                scriptFile.write("# Gamma sigma (EV " + str(cond) + ")\nset fmri(gammasigma" + str(cond) + ") 3\n\n")
                                scriptFile.write("# Gamma delay (EV " + str(cond) + ")\nset fmri(gammadelay" + str(cond) + ") 6\n\n")
                                for ev in range(0,CondLen + 1):
                                    scriptFile.write("# Orthogonalise EV " + str(cond) + " wrt EV " + str(ev) + "\nset fmri(ortho" + str(cond) + "." + str(ev) + ") 0\n\n")

                            scriptFile.write("# Contrast & F-tests mode\n# real : control real EVs\n# orig : control original EVs\nset fmri(con_mode_old) orig\nset fmri(con_mode) orig\n\n")
                            # Contrast & F-tests mode
                            for cond in range(1,CondLen + 1):
                                scriptFile.write("# Display images for contrast_real " + str(cond) + "\nset fmri(conpic_real." + str(cond) + ") 1\n\n")
                                scriptFile.write("# Title for contrast_real " + str(cond) + "\nset fmri(conname_real." + str(cond) + ") \"" + Conditions[cond-1][1][0] + "\"\n\n")
                                for ev in range(1, CondLen + 1):
                                    if ev == cond:
                                        scriptFile.write("# Real contrast_real vector " + str(cond) + " element " + str(ev) + "\nset fmri(con_real" + str(cond) + "." + str(ev) + ") " + str(CondLen) + "\n\n")
                                    else:
                                        scriptFile.write("# Real contrast_real vector " + str(cond) + " element " + str(ev) + "\nset fmri(con_real" + str(cond) + "." + str(ev) + ") -1\n\n")

                            for cond in range(1,CondLen + 1):
                                scriptFile.write("# Display images for contrast_orig " + str(cond) + "\nset fmri(conpic_orig." + str(cond) + ") 1\n\n")
                                scriptFile.write("# Title for contrast_orig " + str(cond) + "\nset fmri(conname_orig." + str(cond) + ") \"" + Conditions[cond-1][1][0] + "\"\n\n")
                                for ev in range(1, CondLen + 1):
                                    if ev == cond:
                                        scriptFile.write("# Real contrast_orig vector " + str(cond) + " element " + str(ev) + "\nset fmri(con_orig" + str(cond) + "." + str(ev) + ") " + str(CondLen) + "\n\n")
                                    else:
                                        scriptFile.write("# Real contrast_orig vector " + str(cond) + " element " + str(ev) + "\nset fmri(con_orig" + str(cond) + "." + str(ev) + ") -1\n\n")

                            scriptFile.write("# Contrast masking - use >0 instead of thresholding?\nset fmri(conmask_zerothresh_yn) 0\n\n")
                            scriptFile.write("")

                            for cond in range(1,CondLen + 1):
                                for ev in range(1,CondLen + 1):
                                    if cond != ev:
                                        scriptFile.write("# Mask real contrast/F-test " + str(cond) + " with real contrast/F-test " + str(ev) + "?\nset fmri(conmask" + str(cond) + "_" + str(ev) + ") 0\n\n")

                            scriptFile.write("# Do contrast masking at all?\nset fmri(conmask1_1) 0\n\n")
                            scriptFile.write("##########################################################\n# Now options that don't appear in the GUI\n\n")
                            scriptFile.write("# Alternative (to BETting) mask image\nset fmri(alternative_mask) \"\"\n\n")
                            scriptFile.write("# Initial structural space registration initialisation transform\nset fmri(init_initial_highres) \"\"\n\n")
                            scriptFile.write("# Structural space registration initialisation transform\nset fmri(init_highres) \"\"\n\n")
                            scriptFile.write("# Standard space registration initialisation transform\nset fmri(init_standard) \"\"\n\n")
                            scriptFile.write("# For full FEAT analysis: overwrite existing .feat output dir?\nset fmri(overwrite_yn) 0")

                            scriptFile.close()
                            print("SCRIPT: " + ScriptAddr + " is generated!")
Exemple #7
0
    def btnRun_onclick(self):
        from Base.utility import strRange, strMultiRange

        global ui
        msgBox = QMessageBox()

        SubPer = ui.txtSubPer.text()
        RunPer = ui.txtRunPer.text()
        ConPer = ui.txtConPer.text()
        Input = ui.txtInput.text()
        Output = ui.txtOutput.text()
        Task = ui.txtTask.text()
        DIR = ui.txtDIR.text()

        try:
            SubRange = strRange(ui.txtSubRange.text(), Unique=True)
            if SubRange is None:
                raise Exception
            SubSize = len(SubRange)
        except:
            msgBox.setText("Subject Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Range of subjects is okay!")
        try:
            SubLen = np.int32(ui.txtSubLen.text())
            1 / SubLen
        except:
            msgBox.setText("Length of subjects must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of subjects is okay!")

        try:
            ConRange = strMultiRange(ui.txtConRange.text(), SubSize)
            if ConRange is None:
                raise Exception
            if not (len(ConRange) == SubSize):
                msgBox.setText("Counter Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Counter Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Counter Range is okay!")
        try:
            ConLen = np.int32(ui.txtConLen.text())
            1 / ConLen
        except:
            msgBox.setText("Length of counter must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of Counter is okay!")

        try:
            RunRange = strMultiRange(ui.txtRunRange.text(), SubSize)
            if RunRange is None:
                raise Exception
            if not (len(RunRange) == SubSize):
                msgBox.setText("Run Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Run Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Run Range is okay!")
        try:
            RunLen = np.int32(ui.txtRunLen.value())
            1 / RunLen
        except:
            msgBox.setText("Length of runs must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of runs is valid")

        if Input == "":
            msgBox = QMessageBox()
            msgBox.setText("There is no input structure")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if Output == "":
            msgBox = QMessageBox()
            msgBox.setText("There is no output structure")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if Task == "":
            msgBox = QMessageBox()
            msgBox.setText("There is no Task name")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if DIR == "":
            msgBox = QMessageBox()
            msgBox.setText("Please select the main directory")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if not os.path.isdir(DIR):
            msgBox = QMessageBox()
            msgBox.setText("Cannot find the main directory")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        for si, s in enumerate(SubRange):
            for c in ConRange[si]:
                for r in RunRange[si]:
                    InAdd = setParameters3(Input,DIR, fixstr(s,SubLen,SubPer),\
                                               fixstr(r,RunLen,RunPer),Task,\
                                               fixstr(c,ConLen,ConPer))
                    OutAdd = setParameters3(Output,DIR,fixstr(s,SubLen,SubPer),\
                                               fixstr(r,RunLen,RunPer),Task,\
                                               fixstr(c,ConLen,ConPer))
                    try:
                        if not os.path.isfile(InAdd):
                            print(InAdd + " - not found!")
                        else:
                            print("MOVE: " + InAdd + " - running ...")
                            os.rename(InAdd, OutAdd)
                            print("TO: " + OutAdd + " - DONE!")
                    except Exception as e:
                        print(e)
Exemple #8
0
    def btnConvert_click(self):
        msgBox = QMessageBox()

        # OutFile
        OutFile = ui.txtOutFile.text()
        if not len(OutFile):
            msgBox.setText("Please enter out file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        ThresholdType = ui.cbThType.currentData()
        MinTh = None
        MaxTh = None

        if (ThresholdType == "min") or (ThresholdType == "ext"):
            try:
                MinTh = np.double(ui.txtThMin.text())
            except:
                msgBox.setText("Min Threshold must be a number")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
            print("Min Threshold is valid")

        if (ThresholdType == "max") or (ThresholdType == "ext"):
            try:
                MaxTh = np.double(ui.txtThMax.text())
            except:
                msgBox.setText("Max Threshold must be a number")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
            print("Max Threshold is valid")

        # OutFile
        AFNI = ui.txtAFNI.text()
        if not len(AFNI):
            AFNI = None
        else:
            CopyFile = ui.txtFAFNI.text()
            if not len(CopyFile):
                msgBox.setText("Please select 3dcopy command!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return
            if not os.path.isfile(CopyFile):
                msgBox.setText("Please select 3dcopy command!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return

            RefitFile = ui.txtFSUMA.text()
            if not len(RefitFile):
                msgBox.setText("Please select 3drefit command!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return
            if not os.path.isfile(RefitFile):
                msgBox.setText("Please select 3drefit command!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return

        # InFile
        InFile = ui.txtInFile.text()
        if not len(InFile):
            msgBox.setText("Please enter input file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return
        if not os.path.isfile(InFile):
            msgBox.setText("Input file not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if not len(ui.txtMatrix.currentText()):
            msgBox.setText("Matrix name not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if not len(ui.txtCoord.currentText()):
            msgBox.setText("Coordinate name not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if not len(ui.txtTime.text()):
            msgBox.setText("Time points not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        AffineFile = ui.txtSSSpace.currentText()
        if not len(AffineFile):
            msgBox.setText("Please enter affine reference!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return
        if not os.path.isfile(AffineFile):
            msgBox.setText("Affine reference not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return
        AffineHDR = nb.load(AffineFile)
        Affine = AffineHDR.affine

        Time = strRange(ui.txtTime.text())
        if Time is None:
            msgBox.setText("Time points is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        try:
            InData = mainIO_load(InFile)
            Mat = InData[ui.txtMatrix.currentText()]
            Coord = InData[ui.txtCoord.currentText()]
            imgShape = InData["imgShape"][0]

        except:
            print("Cannot load data!")
            msgBox.setText("Cannot load data!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        ImgData = None
        # Filter Mat
        for t in Time:
            vox = Mat[t, :]
            if ui.cbScale.isChecked():
                vox = preprocessing.scale(vox)
                print("Time Point: " + str(t) + " is normalized.")

            if MinTh is not None:
                vox[np.where(vox < MinTh)] = 0
                print("Time Point: " + str(t) +
                      ", Lower band thresholding is done!")

            if MaxTh is not None:
                vox[np.where(vox > MaxTh)] = 0
                print("Time Point: " + str(t) +
                      ", Upper band thresholding is done!")

            img = np.zeros([imgShape[0], imgShape[1], imgShape[2], 1])
            for coIndx, _ in enumerate(Coord[0]):
                img[Coord[0][coIndx], Coord[1][coIndx], Coord[2][coIndx],
                    0] = vox[coIndx]
            ImgData = img if ImgData is None else np.concatenate(
                (ImgData, img), axis=3)
            print("Time point: " + str(t) + " is done.")

        print("Saving image ...")
        NIF = nb.Nifti1Image(ImgData, Affine)
        nb.save(NIF, OutFile)
        if AFNI is not None:
            cmd = CopyFile + " " + OutFile + " " + AFNI
            print("Running: " + cmd)
            os.system(cmd)
            cmd = RefitFile + "  -view tlrc -space MNI " + AFNI + " " + AFNI + "+tlrc."
            print("Running: " + cmd)
            os.system(cmd)
        print("DONE!")
        msgBox.setText("Image file is generated.")
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()
Exemple #9
0
    def Run(self,
            SettingFileName,
            isOne=False,
            Remove=True,
            feat=None,
            SubID=None,
            RunID=None,
            ConID=None):
        import numpy as np
        import os, subprocess
        from Base.utility import fixstr, setParameters3, strRange, strMultiRange
        from Base.Setting import Setting

        if (feat == None) or (os.path.isfile(feat) == False):
            print("Cannot find feat cmd!")
            return False, None

        Jobs = list()
        setting = Setting()
        setting.Load(SettingFileName)
        if setting.empty:
            print("Error in loading the setting file!")
            return False, None
        else:
            if isOne:
                Subjects = [SubID]
                Counters = [[ConID]]
                Runs = [[RunID]]
            else:
                Subjects = strRange(setting.SubRange, Unique=True)
                if Subjects is None:
                    print("Cannot load Subject Range!")
                    return False, None
                SubSize = len(Subjects)

                Counters = strMultiRange(setting.ConRange, SubSize)
                if Counters is None:
                    print("Cannot load Counter Range!")
                    return False, None

                Runs = strMultiRange(setting.RunRange, SubSize)
                if Runs is None:
                    print("Cannot load Run Range!")
                    return False, None

            for si, s in enumerate(Subjects):
                for cnt in Counters[si]:
                    print("Run script for Subject %d ..." % (s))
                    for r in Runs[si]:
                        ScriptAddr = setParameters3(setting.Script,setting.mainDIR, fixstr(s, setting.SubLen, setting.SubPer), \
                                                    fixstr(r, setting.RunLen, setting.RunPer), setting.Task, \
                                                    fixstr(cnt, setting.ConLen, setting.ConPer))
                        ScriptTitle = setParameters3(setting.Script, "", fixstr(s, setting.SubLen, setting.SubPer), \
                                                    fixstr(r, setting.RunLen, setting.RunPer), setting.Task, \
                                                    fixstr(cnt, setting.ConLen, setting.ConPer))
                        ScriptOutputAddr = setParameters3(setting.Analysis, setting.mainDIR,
                                                          fixstr(s, setting.SubLen, setting.SubPer), \
                                                          fixstr(r, setting.RunLen, setting.RunPer), setting.Task, \
                                                          fixstr(cnt, setting.ConLen, setting.ConPer)) + ".feat"
                        files  = [ScriptOutputAddr + "/filtered_func_data.nii.gz", ScriptOutputAddr + \
                                  "/mask.nii.gz", ScriptOutputAddr + "/cluster_mask_zstat1.nii.gz"]
                        cmd = ScriptAddr
                        report = ScriptOutputAddr + "/report_log.html"
                        thread = PreprocessThread(feat=feat, cmd=cmd, report=report, files=files, \
                                                  remove=Remove, removefile=ScriptOutputAddr)
                        Jobs.append(["Preprocess", ScriptTitle, thread])
                        print("Job for " + ScriptAddr + " - is created!")
            return True, Jobs
    def btnLoadEvent_click(self):
        global ui, dialog

        msgBox = QMessageBox()

        mainDIR = ui.txtSSDIR.text()
        Task = ui.txtSSTask.text()
        # Check Directory
        if not len(mainDIR):
            msgBox.setText("There is no main directory")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if not os.path.isdir(mainDIR):
            msgBox.setText("Main directory doesn't exist")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Main directory is okay.")
        if not len(Task):
            msgBox.setText("There is no task title")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            SubRange = strRange(ui.txtSSSubRange.text(),Unique=True)
            if SubRange is None:
                raise Exception
            SubSize = len(SubRange)
        except:
            msgBox.setText("Subject Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Range of subjects is okay!")
        try:
            SubLen = np.int32(ui.txtSSSubLen.text())
            1 / SubLen
        except:
            msgBox.setText("Length of subjects must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of subjects is okay!")


        try:
            ConRange = strMultiRange(ui.txtSSConRange.text(),SubSize)
            if ConRange is None:
                raise Exception
            if not (len(ConRange) == SubSize):
                msgBox.setText("Counter Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Counter Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Counter Range is okay!")
        try:
            ConLen = np.int32(ui.txtSSConLen.text())
            1 / ConLen
        except:
            msgBox.setText("Length of counter must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of Counter is okay!")


        try:
            RunRange = strMultiRange(ui.txtSSRunRange.text(),SubSize)
            if RunRange is None:
                raise Exception
            if not (len(RunRange) == SubSize):
                msgBox.setText("Run Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Run Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Run Range is okay!")
        try:
            RunLen = np.int32(ui.txtSSRunLen.value())
            1 / RunLen
        except:
            msgBox.setText("Length of runs must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of runs is valid")


        if ui.txtEventDIR.text() == "":
            msgBox.setText("Structure of the event folders is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if ui.txtCondPre.text() == "":
            msgBox.setText("The prefix of condition files is empty!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        setting         = Setting()

        setting.mainDIR = mainDIR
        setting.Task    = Task

        setting.SubRange= ui.txtSSSubRange.text()
        setting.SubLen  = np.int32(SubLen)
        setting.SubPer  = ui.txtSSSubPer.text()

        setting.ConRange= ui.txtSSConRange.text()
        setting.ConLen  = np.int32(ConLen)
        setting.ConPer  = ui.txtSSConPer.text()

        setting.RunRange= ui.txtSSRunRange.text()
        setting.RunLen  = np.int32(RunLen)
        setting.RunPer  = ui.txtSSRunPer.text()

        sSess = frmSelectSession(None, setting=setting)
        if not sSess.PASS:
            return

        EventFolder = setParameters3(ui.txtEventDIR.text(), mainDIR, fixstr(int(sSess.SubID), setting.SubLen, setting.SubPer), \
                                               fixstr(int(sSess.RunID), int(setting.RunLen), setting.RunPer), setting.Task, \
                                               fixstr(sSess.ConID, int(setting.ConLen), setting.ConPer))

        CondFile = EventFolder + ui.txtCondPre.text() + ".mat"

        if not os.path.isfile(CondFile):
            print("Cannot find condition mat file!")
            return
        try:
            conditions = io.loadmat(CondFile)
        except:
            print("Cannot load condition mat file!")
            return

        NumCond = len(conditions["Cond"])
        ui.txtSSCondFrom.setValue(1)
        ui.txtSSCondTo.setValue(NumCond)
        ui.txtSSCondLen.setValue(len(str(NumCond)))
        ui.txtSSCondPer.setText("")
    def btnRUN_click(self):
        global ui
        msgBox = QMessageBox()

        mainDIR = ui.txtSSDIR.text()
        Task = ui.txtSSTask.text()
        # Check Directory
        if not len(mainDIR):
            msgBox.setText("There is no main directory")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if not os.path.isdir(mainDIR):
            msgBox.setText("Main directory doesn't exist")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Main directory is okay.")
        if not len(Task):
            msgBox.setText("There is no task title")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            SubRange = strRange(ui.txtSSSubRange.text(),Unique=True)
            if SubRange is None:
                raise Exception
            SubSize = len(SubRange)
        except:
            msgBox.setText("Subject Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Range of subjects is okay!")
        try:
            SubLen = np.int32(ui.txtSSSubLen.text())
            1 / SubLen
        except:
            msgBox.setText("Length of subjects must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of subjects is okay!")


        try:
            ConRange = strMultiRange(ui.txtSSConRange.text(),SubSize)
            if ConRange is None:
                raise Exception
            if not (len(ConRange) == SubSize):
                msgBox.setText("Counter Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Counter Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Counter Range is okay!")
        try:
            ConLen = np.int32(ui.txtSSConLen.text())
            1 / ConLen
        except:
            msgBox.setText("Length of counter must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of Counter is okay!")


        try:
            RunRange = strMultiRange(ui.txtSSRunRange.text(),SubSize)
            if RunRange is None:
                raise Exception
            if not (len(RunRange) == SubSize):
                msgBox.setText("Run Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Run Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Run Range is okay!")
        try:
            RunLen = np.int32(ui.txtSSRunLen.value())
            1 / RunLen
        except:
            msgBox.setText("Length of runs must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of runs is valid")

        try:
            CondFrom = np.int32(ui.txtSSCondFrom.value())
            1 / CondFrom
        except:
            msgBox.setText("Condition From must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            CondTo = np.int32(ui.txtSSCondTo.value())
            1 / CondTo
        except:
            msgBox.setText("Condition To must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if CondTo < CondFrom:
            msgBox.setText("Condition To is smaller then Subject From!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Counter is valid")
        try:
            CondLen = np.int32(ui.txtSSCondLen.text())
            1 / CondLen
        except:
            msgBox.setText("Length of condition must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of condition is valid")


        Space = ui.txtSSSpace.currentText()
        if not len(Space):
            msgBox.setText("Please enter a affine file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if not Space == DefaultSpace():
            if not os.path.isfile(Space):
                msgBox = QMessageBox()
                msgBox.setText("Affine file not found!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return
        print("Affine file is okay.")

        In = ui.txtSSInFile.currentText()
        if not len(In):
            msgBox.setText("Please enter input file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        Out = ui.txtOutROI.text()
        if not len(Out):
            msgBox.setText("Please enter output file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        ThresholdType = ui.cbThType.currentData()

        if (ThresholdType == "min") or (ThresholdType == "ext"):
                try:
                    MinTh = np.double(ui.txtThMin.text())
                except:
                    msgBox.setText("Min Threshold must be a number")
                    msgBox.setIcon(QMessageBox.Critical)
                    msgBox.setStandardButtons(QMessageBox.Ok)
                    msgBox.exec_()
                    return False
                print("Min Threshold is valid")

        if (ThresholdType == "max") or (ThresholdType == "ext"):
                try:
                    MaxTh = np.double(ui.txtThMax.text())
                except:
                    msgBox.setText("Max Threshold must be a number")
                    msgBox.setIcon(QMessageBox.Critical)
                    msgBox.setStandardButtons(QMessageBox.Ok)
                    msgBox.exec_()
                    return False
                print("Max Threshold is valid")

        print("Checking files ...")
        for si, s in enumerate(SubRange):
            for cnt in ConRange[si]:
                print("Analyzing Subject %d, Counter %d ..." % (s,cnt))
                # SubDIR = setting.mainDIR + "/" + "sub-" + fixstr(s, SubLen, setting.SubPer)
                for r in RunRange[si]:
                    for cnd in range(CondFrom, CondTo + 1):

                        InFile = setParameters3(In, mainDIR, fixstr(s, SubLen, ui.txtSSSubPer.text()),\
                                    fixstr(r, RunLen, ui.txtSSRunPer.text()), ui.txtSSTask.text(),\
                                    fixstr(cnt, ConLen, ui.txtSSConPer.text()), fixstr(cnd, CondLen, ui.txtSSCondPer.text()))
                        if os.path.isfile(InFile):
                            print(InFile + " - is OKAY.")
                        else:
                            print(InFile + " - not found!")
                            return

        if ui.cbMetric.currentData() == "inter":
            print("Calculating ROI ...")

            ROIData = None
            for si, s in enumerate(SubRange):
                for cnt in ConRange[si]:
                    print("Analyzing Subject %d, Counter %d ..." % (s,cnt))
                    for r in RunRange[si]:
                        for cnd in range(CondFrom, CondTo + 1):
                            InFile = setParameters3(In, mainDIR, fixstr(s, SubLen, ui.txtSSSubPer.text()), \
                                                    fixstr(r, RunLen, ui.txtSSRunPer.text()), ui.txtSSTask.text(), \
                                                    fixstr(cnt, ConLen, ui.txtSSConPer.text()),
                                                    fixstr(cnd, CondLen, ui.txtSSCondPer.text()))

                            MaskHDR = nb.load(InFile)
                            MaskData = MaskHDR.get_data()
                            if ThresholdType == "no":
                                MaskData[np.where(MaskData != 0)] = 1
                            elif ThresholdType == "min":
                                MaskData[np.where(MaskData < MinTh)] = 0
                                MaskData[np.where(MaskData != 0)] = 1
                            elif ThresholdType == "max":
                                MaskData[np.where(MaskData > MaxTh)] = 0
                                MaskData[np.where(MaskData != 0)] = 1
                            elif ThresholdType == "ext":
                                MaskData[np.where(MaskData > MaxTh)] = 0
                                MaskData[np.where(MaskData < MinTh)] = 0
                                MaskData[np.where(MaskData != 0)] = 1

                            if ROIData is None:
                                if Space == DefaultSpace():
                                    affineHDR = nb.load(InFile)
                                else:
                                    affineHDR = nb.load(Space)

                                ROIData = MaskData.copy()
                            else:
                                if not np.shape(ROIData) == np.shape(MaskData):
                                    print("All mask must include the same size data (tensor)")
                                    return
                                else:
                                    ROIData = ROIData + MaskData
                                    ROIData[np.where(ROIData != 0)] = 1

                            print(InFile + " - is calculated!")
            NumVoxels = np.shape(ROIData)
            NumVoxels = NumVoxels[0] * NumVoxels[1] * NumVoxels[2]
            print("Number of all voxels: %d " % NumVoxels)
            NumROIVoxel = len(ROIData[np.where(ROIData != 0)])
            print("Number of selected voxles in ROI: %d" % NumROIVoxel)
            ROIHDR = nb.Nifti1Image(ROIData, affineHDR.affine)
            nb.save(ROIHDR,Out)
            print("ROI is generated!")

            msgBox.setText("ROI is generated!\nNumber of all voxels: " + str(NumVoxels) + \
                           "\nNumber of selected voxles in ROI: " + str(NumROIVoxel))
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
    def btnRun_onclick(self):
        from Base.utility import strRange, strMultiRange

        global ui
        msgBox = QMessageBox()

        SubPer = ui.txtSubPer.text()
        RunPer = ui.txtRunPer.text()
        ConPer = ui.txtConPer.text()
        Input = ui.txtInput.text()
        Output = ui.txtOutput.text()
        Task = ui.txtTask.text()
        DIR = ui.txtDIR.text()
        Script = ui.txtScript.text()

        try:
            SubRange = strRange(ui.txtSubRange.text(), Unique=True)
            if SubRange is None:
                raise Exception
            SubSize = len(SubRange)
        except:
            msgBox.setText("Subject Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Range of subjects is okay!")
        try:
            SubLen = np.int32(ui.txtSubLen.text())
            1 / SubLen
        except:
            msgBox.setText("Length of subjects must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of subjects is okay!")

        try:
            ConRange = strMultiRange(ui.txtConRange.text(), SubSize)
            if ConRange is None:
                raise Exception
            if not (len(ConRange) == SubSize):
                msgBox.setText("Counter Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Counter Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Counter Range is okay!")
        try:
            ConLen = np.int32(ui.txtConLen.text())
            1 / ConLen
        except:
            msgBox.setText("Length of counter must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of Counter is okay!")

        try:
            RunRange = strMultiRange(ui.txtRunRange.text(), SubSize)
            if RunRange is None:
                raise Exception
            if not (len(RunRange) == SubSize):
                msgBox.setText("Run Size must be equal to Subject Size!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
        except:
            msgBox.setText("Run Range is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Run Range is okay!")
        try:
            RunLen = np.int32(ui.txtRunLen.value())
            1 / RunLen
        except:
            msgBox.setText("Length of runs must be an integer number")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Length of runs is valid")

        if Input == "":
            msgBox = QMessageBox()
            msgBox.setText("There is no input structure")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if Task == "":
            msgBox = QMessageBox()
            msgBox.setText("There is no Task name")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if DIR == "":
            msgBox = QMessageBox()
            msgBox.setText("Please select the main directory")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if Script == "":
            msgBox = QMessageBox()
            msgBox.setText("Script structure is not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        if not os.path.isdir(DIR):
            msgBox = QMessageBox()
            msgBox.setText("Cannot find the main directory")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        RepCount = 0
        for si, s in enumerate(SubRange):
            for c in ConRange[si]:
                for r in RunRange[si]:
                    SFile   =  setParameters3(Script, DIR, fixstr(s,SubLen,SubPer),\
                                               fixstr(r,RunLen,RunPer),Task,\
                                               fixstr(c,ConLen,ConPer))
                    if ui.cbInDynamic.isChecked():
                        InValue = setParameters3(Input,DIR, fixstr(s,SubLen,SubPer),\
                                               fixstr(r,RunLen,RunPer),Task,\
                                               fixstr(c,ConLen,ConPer))
                    else:
                        InValue = Input

                    if ui.cbOutDynamic.isChecked():
                        OutValue = setParameters3(Output,DIR, fixstr(s,SubLen,SubPer),\
                                               fixstr(r,RunLen,RunPer),Task,\
                                               fixstr(c,ConLen,ConPer))
                    else:
                        OutValue = Output

                    CountCurrRep = RepCount
                    print("SCRIPT: " + SFile)
                    print("Replacing " + InValue + " to " + OutValue + "...")
                    try:
                        if not os.path.isfile(SFile):
                            print(SFile + " - not found!")
                        else:
                            scriptFile = open(SFile, "r")
                            scriptContent = scriptFile.read()
                            scriptFile.close()
                            while scriptContent.find(InValue) != -1:

                                scriptContent = scriptContent.replace(
                                    InValue, OutValue, 1)
                                RepCount = RepCount + 1
                    except Exception as e:
                        print(e)
                    CountCurrRep = RepCount - CountCurrRep

                    if not ui.cbDEMO.isChecked():
                        scriptFile = open(SFile, "w")
                        scriptFile.write(scriptContent)
                        scriptFile.close()
                        print(str(CountCurrRep) + " is replaced!")
                    else:
                        print("DEMO: " + str(CountCurrRep) + " is found!")

        if ui.cbDEMO.isChecked():
            msgBox.setText(str(RepCount) + " items are found!")
        else:
            msgBox.setText(str(RepCount) + " items are replaced!")
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()
        pass
    def btnConvert_click(self):
        msgBox = QMessageBox()
        tStart = time.time()
        Activation = ui.cbActivation.currentData()
        LossNorm = ui.cbLossNorm.currentData()
        try:
            Layers = strRange(ui.txtLayers.text(), Unique=False)
            if Layers is None:
                raise Exception('')

        except:
            msgBox.setText("Layers is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            KIter = np.int32(ui.txtKIter.text())
        except:
            msgBox.setText("Number of iteration is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            RIter = np.int32(ui.txtRIter.text())
        except:
            msgBox.setText("Number of iteration is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            BatchSize = np.int32(ui.txtBatch.text())
        except:
            msgBox.setText("Number of batch is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            ReportStep = np.int32(ui.txtReportStep.text())
        except:
            msgBox.setText("Number of Report Step is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            LearningRate = np.float32(ui.txtRate.text())
        except:
            msgBox.setText("Number of Report Step is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if not ui.cbCov.isChecked() and not ui.cbCorr.isChecked():
            msgBox.setText("At least, you must select one metric!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Filter
        try:
            Filter = ui.txtFilter.text()
            if not len(Filter):
                Filter = None
            else:
                Filter = Filter.replace("\'", " ").replace(",", " ").replace(
                    "[", "").replace("]", "").split()
                Filter = np.int32(Filter)
        except:
            print("Filter is wrong!")
            return

        # OutFile
        OutFile = ui.txtOutFile.text()
        if not len(OutFile):
            msgBox.setText("Please enter out file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        OutData = dict()

        # InFile
        InFile = ui.txtInFile.text()
        if not len(InFile):
            msgBox.setText("Please enter input file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        if not os.path.isfile(InFile):
            msgBox.setText("Input file not found!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        print("Loading ...")
        InData = io.loadmat(InFile)

        # Data
        if not len(ui.txtData.currentText()):
            msgBox.setText("Please enter Input Data variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Label
        if not len(ui.txtLabel.currentText()):
            msgBox.setText("Please enter Train Label variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Design
        if not len(ui.txtDesign.currentText()):
            msgBox.setText("Please enter Input Design variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            Design = InData[ui.txtDesign.currentText()]
        except:
            msgBox.setText("Design value is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            X = InData[ui.txtData.currentText()]
            L = InData[ui.txtLabel.currentText()][0]
            if ui.cbScale.isChecked() and not ui.rbScale.isChecked():
                X = preprocessing.scale(X)
                print("Whole of data is scaled X~N(0,1).")

        except:
            print("Cannot load data or label")
            return

        # Task
        if not len(ui.txtTask.currentText()):
            msgBox.setText("Please enter Task variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            TaskTitle = InData[ui.txtTask.currentText()][0]
        except:
            msgBox.setText("Task variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        TaskTitleUnique = np.unique(TaskTitle)
        Task = np.zeros(np.shape(TaskTitle))

        for ttinx, tt in enumerate(TaskTitle):
            for ttlinx, ttl in enumerate(TaskTitleUnique):
                if tt[0] == ttl:
                    Task[ttinx] = ttlinx + 1
                    break

        # Subject
        if not len(ui.txtSubject.currentText()):
            msgBox.setText("Please enter Subject variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            Sub = InData[ui.txtSubject.currentText()][0]
        except:
            msgBox.setText("Subject variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Run
        if not len(ui.txtRun.currentText()):
            msgBox.setText("Please enter Run variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        try:
            Run = InData[ui.txtRun.currentText()][0]
        except:
            msgBox.setText("Run variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # Counter
        if not len(ui.txtCounter.currentText()):
            msgBox.setText("Please enter Counter variable name!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False
        try:
            Con = InData[ui.txtCounter.currentText()][0]
        except:
            msgBox.setText("Counter variable name is wrong!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if Filter is not None:
            for fil in Filter:
                # Remove Training Set
                labelIndx = np.where(L == fil)[0]
                Design = np.delete(Design, labelIndx, axis=0)
                X = np.delete(X, labelIndx, axis=0)
                L = np.delete(L, labelIndx, axis=0)
                Task = np.delete(Task, labelIndx, axis=0)
                Sub = np.delete(Sub, labelIndx, axis=0)
                Run = np.delete(Run, labelIndx, axis=0)
                Con = np.delete(Con, labelIndx, axis=0)
                print("Class ID = " + str(fil) + " is removed from data.")

        try:
            Unit = np.int32(ui.txtUnit.text())
        except:
            msgBox.setText("Unit for the test set must be a number!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        if Unit < 1:
            msgBox.setText("Unit for the test set must be greater than zero!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        print("Calculating Levels ...")
        GroupFold = None
        FoldStr = ""
        if ui.cbFSubject.isChecked():
            if not ui.rbFRun.isChecked():
                GroupFold = [Sub]
                FoldStr = "Subject"
            else:
                GroupFold = np.concatenate(([Sub], [Run]))
                FoldStr = "Subject+Run"

        if ui.cbFTask.isChecked():
            GroupFold = np.concatenate(
                (GroupFold, [Task])) if GroupFold is not None else [Task]
            FoldStr = FoldStr + "+Task"

        if ui.cbFCounter.isChecked():
            GroupFold = np.concatenate(
                (GroupFold, [Con])) if GroupFold is not None else [Con]
            FoldStr = FoldStr + "+Counter"

        if FoldStr == "":
            FoldStr = "Whole-Data"
            GUFold = [1]
            ListFold = [1]
            UniqFold = [1]
            GroupFold = [1]
            UnitFold = np.ones((1, np.shape(X)[0]))
        else:
            GroupFold = np.transpose(GroupFold)
            UniqFold = np.array(list(set(tuple(i)
                                         for i in GroupFold.tolist())))
            FoldIDs = np.arange(len(UniqFold)) + 1

            if len(UniqFold) <= Unit:
                msgBox.setText(
                    "Unit must be smaller than all possible levels! Number of all levels is: "
                    + str(len(UniqFold)))
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False

            if np.mod(len(UniqFold), Unit):
                msgBox.setText(
                    "Unit must be divorceable to all possible levels! Number of all levels is: "
                    + str(len(UniqFold)))
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return False
            ListFold = list()
            for gfold in GroupFold:
                for ufoldindx, ufold in enumerate(UniqFold):
                    if (ufold == gfold).all():
                        currentID = FoldIDs[ufoldindx]
                        break
                ListFold.append(currentID)

            ListFold = np.int32(ListFold)
            if Unit == 1:
                UnitFold = np.int32(ListFold)
            else:
                UnitFold = np.int32((ListFold - 0.1) / Unit) + 1

            GUFold = np.unique(UnitFold)

        FoldInfo = dict()
        FoldInfo["Unit"] = Unit
        FoldInfo["Group"] = GroupFold
        FoldInfo["Order"] = FoldStr
        FoldInfo["List"] = ListFold
        FoldInfo["Unique"] = UniqFold
        FoldInfo["Folds"] = UnitFold

        OutData["FoldInfo"] = FoldInfo
        OutData["ModelAnalysis"] = "Tensorflow.Group.Single-Deep-Kernel.RSA"

        print("Number of all levels is: " + str(len(UniqFold)))

        # RSA Method
        OutData['Method'] = dict()
        OutData['Method']['Layers'] = ui.txtLayers.text()
        OutData['Method']['Activation'] = Activation
        OutData['Method']['LossNorm'] = LossNorm
        OutData['Method']['LearningRate'] = LearningRate
        OutData['Method']['KernelIter'] = KIter
        OutData['Method']['RSAIter'] = RIter
        OutData['Method']['BatchSize'] = BatchSize
        OutData['Method']['ReportStep'] = ReportStep
        OutData['Method']['Verbose'] = ui.cbVerbose.isChecked()
        TData = list()
        TReg = list()
        print("Reshaping Data ...")
        for foldID, fold in enumerate(GUFold):
            print("Reshaping level " + str(foldID + 1), " of ",
                  str(len(UniqFold)), " ...")
            Index = np.where(UnitFold == fold)
            # Whole-Data
            if FoldStr == "Whole-Data" and np.shape(Index)[0]:
                Index = [Index[1]]
            XLi = X[Index]
            RegLi = Design[Index]
            if ui.cbScale.isChecked() and ui.rbScale.isChecked():
                XLi = preprocessing.scale(XLi)
                print("Whole of data is scaled X%d~N(0,1)." % (foldID + 1))

            TData.append(XLi)
            TReg.append(RegLi)

        print("Running Deep Group RSA ...")
        rsa = DeepGroupRSA(layers=Layers, kernel_iter = KIter, rsa_iter = RIter, learning_rate=LearningRate,
                           loss_norm=LossNorm, activation=Activation, \
                          batch_size=BatchSize, report_step=ReportStep, verbose=ui.cbVerbose.isChecked(), \
                           NCat=np.shape(Design)[1], NVoxel=np.shape(X)[1], CPU=ui.cbDevice.currentData())
        Betas, Eps, Weights, Bias, MSE, loss_mat = rsa.fit(data_vals=TData,
                                                           design_vals=TReg)

        OutData["Weight"] = Weights
        OutData["Bias"] = Bias
        OutData["Perfromance"] = MSE
        OutData["Perfromance_Average"] = rsa.AMSE
        OutData["Perfromance_std"] = np.std(rsa.AMSE)
        OutData["LossMat"] = loss_mat
        print("Average Performance: %f" % (OutData["Perfromance"]))

        print("Calculating cov & corr ... ")
        AvgCov = None
        AvgCorr = None
        for beta_id, beta in enumerate(Betas):
            OutData["BetaL" + str(beta_id)] = beta
            if ui.cbCov.isChecked():
                co = np.cov(beta)
                OutData["Cov" + str(beta_id)] = co
                AvgCov = co if AvgCov is None else AvgCov + co

            if ui.cbCorr.isChecked():
                cr = np.corrcoef(beta)
                OutData["Corr" + str(beta_id)] = cr
                AvgCorr = cr if AvgCorr is None else AvgCorr + cr
        for eps_id, ep in enumerate(Eps):
            OutData["EpsL" + str(eps_id)] = ep

        if ui.cbCov.isChecked():
            AvgCov = AvgCov / len(TData)
            covClass = SimilarityMatrixBetweenClass(AvgCov)
            OutData["Covariance"] = AvgCov
            OutData["Covariance_min"] = covClass.min()
            OutData["Covariance_max"] = covClass.max()
            OutData["Covariance_mean"] = covClass.mean()
            OutData["Covariance_std"] = covClass.std()

        if ui.cbCorr.isChecked():
            AvgCorr = AvgCorr / len(TData)
            corClass = SimilarityMatrixBetweenClass(AvgCorr)
            OutData["Correlation"] = AvgCorr
            OutData["Correlation_min"] = corClass.min()
            OutData["Correlation_max"] = corClass.max()
            OutData["Correlation_mean"] = corClass.mean()
            OutData["Correlation_std"] = corClass.std()

        OutData["RunTime"] = time.time() - tStart
        print("Runtime (s): %f" % (OutData["RunTime"]))
        print("Saving results ...")
        io.savemat(OutFile, mdict=OutData, do_compression=True)
        print("Output is saved.")

        if ui.cbDiagram.isChecked():
            if ui.cbCorr.isChecked():
                fig1 = plt.figure(num=None, figsize=(5, 5), dpi=100)
                plt.pcolor(AvgCorr, vmin=-0.1, vmax=1)
                plt.xlim([0, np.shape(AvgCorr)[0]])
                plt.ylim([0, np.shape(AvgCorr)[0]])
                plt.colorbar()
                ax = plt.gca()
                ax.set_aspect(1)
                plt.title('Deep Group RSA: Correlation\nLevel: ' + FoldStr)
                plt.show()

            if ui.cbCov.isChecked():
                fig2 = plt.figure(num=None, figsize=(5, 5), dpi=100)
                plt.pcolor(AvgCov)
                plt.xlim([0, np.shape(AvgCov)[0]])
                plt.ylim([0, np.shape(AvgCov)[0]])
                plt.colorbar()
                ax = plt.gca()
                ax.set_aspect(1)
                plt.title('Deep Group RSA: Covariance\nLevel: ' + FoldStr)
                plt.show()
        print("DONE.")
        msgBox.setText(
            "Group Level Single-Deep-Kernel Representational Similarity Analysis is done."
        )
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()