Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 4
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!")
Ejemplo n.º 5
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)
    def btnConvert_click(self):
        msgBox = QMessageBox()

        DataFiles = ui.txtDataFiles.toPlainText()
        if not len(DataFiles):
            print("WARNING: Please load data files!")
            msgBox.setText("Please load data files!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        OutDataFormat = ui.txtDIOutDAT.text()
        if not len(OutDataFormat):
            msgBox.setText("Please enter output data format!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        try:
            SubLen = np.int32(ui.txtDISubLen.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:
            ConLen = np.int32(ui.txtDIConLen.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:
            RunLen = np.int32(ui.txtDIRunLen.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 not ui.cbFSubject.isChecked():
            if not ui.cbFTask.isChecked():
                if not ui.cbFCounter.isChecked():
                    msgBox.setText("You must at least select one Fold Level!")
                    msgBox.setIcon(QMessageBox.Critical)
                    msgBox.setStandardButtons(QMessageBox.Ok)
                    msgBox.exec_()
                    return False

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

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

        TrainVal = ui.txtTrain.text()
        if not len(TrainVal):
            msgBox.setText("Please enter train perfix!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        TestVal = ui.txtTest.text()
        if not len(TestVal):
            msgBox.setText("Please enter test perfix!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        # 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

        try:
            InData = io.loadmat(InFile, appendmat=False)
        except:
            print("Cannot load data file!")
            msgBox.setText("Cannot load data file!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        try:
            DataFiles = InData["Integration"][ui.txtData.currentText()][0][0]
        except:
            print("Cannot load data files!")
            msgBox.setText("Cannot load data files!")
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        # 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:
            Subject = InData[ui.txtSubject.currentText()]
        except:
            print("Cannot load Subject ID")
            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:
            Task = InData[ui.txtTask.currentText()]
            TaskIndex = Task.copy()
            TaskList = list()
            for tasindx, tas in enumerate(np.unique(Task)):
                TaskIndex[Task == tas] = tasindx + 1
                TaskList.append([tasindx + 1, tas])
        except:
            print("Cannot load Task ID")
            return

        # 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()]
        except:
            print("Cannot load Run ID")
            return

        # 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:
            Counter = InData[ui.txtCounter.currentText()]
        except:
            print("Cannot load Counter ID")
            return

        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("Checking data files ...")
        DataStream = np.transpose(
            np.concatenate((TaskIndex, Subject, Counter, Run)))
        DataStrUniq = list(
            np.transpose(
                np.array(list(set(tuple(i) for i in DataStream.tolist())))))
        DataTasks = list()
        for taskid in DataStrUniq[0]:
            for taskls in TaskList:
                if taskls[0] == taskid:
                    DataTasks.append(taskls[1])
        DataStrUniq = np.transpose(DataStrUniq)
        DataTasks = np.transpose(DataTasks)
        for datindx, dat in enumerate(DataStrUniq):
            SubID = dat[1]
            CouID = dat[2]
            RunID = dat[3]
            TaskID = DataTasks[0][datindx]
            dfile = setParameters3(OutDataFormat,"",fixstr(SubID,SubLen,ui.txtDISubPer.text()),\
                                   fixstr(RunID,RunLen,ui.txtDIRunPer.text()),TaskID,\
                                   fixstr(CouID,ConLen,ui.txtDIConPer.text()))
            if dfile in DataFiles:
                print(dfile + " is okay.")
            else:
                print(dfile + " is not found!")
                msgBox.setText(dfile + " is not found!")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setStandardButtons(QMessageBox.Ok)
                msgBox.exec_()
                return

        print("Calculating Folds ...")
        GroupFold = np.transpose(DataStrUniq.copy())
        FoldStr = ""
        if not ui.cbFSubject.isChecked():
            GroupFold[1] = -1
            GroupFold[3] = -1
        else:
            if not ui.rbFRun.isChecked():
                GroupFold[3] = -1
                FoldStr = "Subject"
            else:
                FoldStr = "Subject+Run"

        if not ui.cbFTask.isChecked():
            GroupFold[0] = -1
        else:
            FoldStr = FoldStr + "+Task"

        if not ui.cbFCounter.isChecked():
            GroupFold[2] = -1
        else:
            FoldStr = FoldStr + "+Counter"

        GroupFold = np.transpose(GroupFold)
        UniqFold = np.array(list(set(tuple(i) for i in GroupFold.tolist())))

        if len(UniqFold) <= Unit:
            msgBox.setText(
                "Unit for the test set must be smaller than all possible folds! Number of all folds 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 for the test set must be divorceable to all possible folds! Number of all folds is: "
                + str(len(UniqFold)))
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return False

        FoldIDs = np.arange(len(UniqFold)) + 1
        if not Unit == 1:
            FoldIDs = np.int32((FoldIDs - 0.1) / Unit) + 1

        DataStructure = list(InData["Integration"]["DataStructure"][0][0])
        try:
            FoldCounter = np.int32(InData["FoldCounter"][0][0]) + 1
        except:
            FoldCounter = 1

        FoldInfo = dict()
        FoldInfo["Unit"] = Unit
        FoldInfo["Group"] = GroupFold
        FoldInfo["Order"] = FoldStr
        FoldInfo["Unique"] = UniqFold
        FoldInfo["FoldID"] = FoldIDs
        FoldInfo["TrainVal"] = TrainVal
        FoldInfo["TestVal"] = TestVal

        GUFold = np.unique(FoldIDs)
        print("Number of all folds is: " + str(len(UniqFold)))

        for foldID, fold in enumerate(GUFold):
            print("Generating Fold " + str(foldID + 1), " of ",
                  str(len(np.unique(FoldIDs))), " ...")
            Train_Info = UniqFold[FoldIDs != fold]
            Test_Info = UniqFold[FoldIDs == fold]

            currentTrainList = list()
            currentTestList = list()
            if not ui.cbFSubject.isChecked():
                if ui.cbFTask.isChecked() and not ui.cbFCounter.isChecked():
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[0] == datastr[0]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[0] == datastr[0]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])

                elif not ui.cbFTask.isChecked() and ui.cbFCounter.isChecked():
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[2] == datastr[2]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[2] == datastr[2]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                else:
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[0] == datastr[0] and trinf[2] == datastr[
                                    2]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[0] == datastr[0] and teinf[2] == datastr[
                                    2]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])

            elif not ui.rbFRun.isChecked():
                if not ui.cbFTask.isChecked() and not ui.cbFCounter.isChecked(
                ):
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[1] == datastr[1]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[1] == datastr[1]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                elif ui.cbFTask.isChecked() and not ui.cbFCounter.isChecked():
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[0] == datastr[0] and trinf[1] == datastr[
                                    1]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[0] == datastr[0] and teinf[1] == datastr[
                                    1]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                elif not ui.cbFTask.isChecked() and ui.cbFCounter.isChecked():
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[1] == datastr[1] and trinf[2] == datastr[
                                    2]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[1] == datastr[1] and teinf[2] == datastr[
                                    2]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                else:
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[0] == datastr[0] and trinf[1] == datastr[
                                    1] and trinf[2] == datastr[2]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[0] == datastr[0] and teinf[1] == datastr[
                                    1] and teinf[2] == datastr[2]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])
            else:
                if not ui.cbFTask.isChecked() and not ui.cbFCounter.isChecked(
                ):
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[1] == datastr[1] and trinf[3] == datastr[
                                    3]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[1] == datastr[1] and teinf[3] == datastr[
                                    3]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                elif ui.cbFTask.isChecked() and not ui.cbFCounter.isChecked():
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[0] == datastr[0] and trinf[1] == datastr[
                                    1] and trinf[3] == datastr[3]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[0] == datastr[0] and teinf[1] == datastr[
                                    1] and teinf[3] == datastr[3]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])

                elif not ui.cbFTask.isChecked() and ui.cbFCounter.isChecked():
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[1] == datastr[1] and trinf[2] == datastr[
                                    2] and trinf[3] == datastr[3]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[1] == datastr[1] and teinf[2] == datastr[
                                    2] and teinf[3] == datastr[3]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                else:
                    for trinf in Train_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if trinf[0] == datastr[0] and trinf[1] == datastr[
                                    1] and trinf[2] == datastr[2] and trinf[
                                        3] == datastr[3]:
                                currentTrainList.append(
                                    [datastr, DataTasks[0][datastrindx]])
                    for teinf in Test_Info:
                        for datastrindx, datastr in enumerate(DataStrUniq):
                            if teinf[0] == datastr[0] and teinf[1] == datastr[
                                    1] and teinf[2] == datastr[2] and trinf[
                                        3] == datastr[3]:
                                currentTestList.append(
                                    [datastr, DataTasks[0][datastrindx]])

            if not len(DataStrUniq
                       ) == len(currentTestList) + len(currentTrainList):
                print("WARNING: There are some confilcts between test set and train set!", len(DataStrUniq), \
                      " is not ", len(currentTestList), " + ", len(currentTrainList))

            currTrainFiles = list()
            currTestFiles = list()
            for currTrain in currentTrainList:
                dfile = setParameters3(OutDataFormat, "", fixstr(currTrain[0][1], SubLen, ui.txtDISubPer.text()), \
                                       fixstr(currTrain[0][3], RunLen, ui.txtDIRunPer.text()), currTrain[1], \
                                       fixstr(currTrain[0][2], ConLen, ui.txtDIConPer.text()))
                currTrainFiles.append(dfile)

            for currTest in currentTestList:
                dfile = setParameters3(OutDataFormat, "", fixstr(currTest[0][1], SubLen, ui.txtDISubPer.text()), \
                                       fixstr(currTest[0][3], RunLen, ui.txtDIRunPer.text()), currTest[1], \
                                       fixstr(currTest[0][2], ConLen, ui.txtDIConPer.text()))
                currTestFiles.append(dfile)

            currTrainVal = TrainVal.replace("$FOLD$", str(fold))
            currTestVal = TestVal.replace("$FOLD$", str(fold))
            DataStructure.append(currTrainVal)
            DataStructure.append(currTestVal)
            FoldInfo[currTrainVal + "_files"] = np.array(currTrainFiles,
                                                         dtype=object)
            FoldInfo[currTestVal + "_files"] = np.array(currTestFiles,
                                                        dtype=object)

        FoldInfo["DataStructure"] = np.array(DataStructure, dtype=object)
        InData["FoldInfo" + str(FoldCounter)] = FoldInfo
        #InData["DataFold"] = np.array(DataStructure,dtype=object)
        InData["FoldCounter"] = FoldCounter

        print("Saving ...")

        io.savemat(InFile, InData, appendmat=False, do_compression=True)
        print("DONE.")
        print("Cross validation is done.")
        msgBox.setText("Cross validation is done.")
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()
Ejemplo n.º 7
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
Ejemplo n.º 8
0
    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("")
Ejemplo n.º 9
0
    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_()
Ejemplo n.º 10
0
    def run(self, SettingFileName):
        import numpy as np
        import scipy.io as io
        import os

        from Base.utility import fixstr, setParameters3
        from Base.Setting import Setting, strRange, strMultiRange
        setting = Setting()
        setting.Load(SettingFileName)
        if setting.empty:
            print("Error in loading the setting file!")
            return False
        else:
            self.ConditionTitles = []
            Events = []

            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

            # COLECT ALL EVENTS AND CALCULATE THE LIST OF CONDITION
            for si, s in enumerate(Subjects):
                for cnt in Counters[si]:
                    print("Analyzing Subject %d, Counter %d ..." % (s, cnt))
                    for r in Runs[si]:
                        # Event File Check
                        EventAddr = setParameters3(setting.Onset,setting.mainDIR,fixstr(s, setting.SubLen, setting.SubPer)\
                                                      ,fixstr(r, setting.RunLen, setting.RunPer), setting.Task, \
                                                      fixstr(cnt, setting.ConLen, setting.ConPer))
                        EventFolder = 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))
                        #EventFolder = SubDIR + "/func/" + "sub-" + fixstr(s, SubLen, setting.SubPer) + "_task-" + setting.Task + "_run-" + \
                        #fixstr(r, RunLen, setting.RunPer) + "_events/"
                        MatAddr = EventFolder + setting.CondPre + ".mat"
                        if not os.path.isfile(EventAddr):
                            print(EventAddr, " - file not find!")
                            return False
                        else:
                            file = open(EventAddr, "r")
                            lines = file.readlines()
                            file.close()
                            dir = {}
                            dir.clear()

                            for k in range(0, len(lines)):
                                Event = lines[k].rsplit()
                                try:
                                    allvars = dict(locals(), **globals())
                                    exec(setting.EventCodes, allvars, allvars)

                                except Exception as e:
                                    print(
                                        "Event codes generated following error:\n"
                                    )
                                    print(e)
                                    return False

                                try:
                                    RowStartID = allvars['RowStartID']
                                except:
                                    print(
                                        "Cannot find RowStartID variable in event code"
                                    )
                                    return False
                                try:
                                    Condition = allvars['Condition']
                                except:
                                    print(
                                        "Cannot find Condition variable in event code"
                                    )
                                    return False
                                try:
                                    Onset = allvars['Onset']
                                except:
                                    print(
                                        "Cannot find Onset variable in event code"
                                    )
                                    return False
                                try:
                                    Duration = allvars['Duration']
                                except:
                                    print(
                                        "Cannot find Duration variable in event code"
                                    )
                                    return False

                                try:
                                    Skip = int(allvars["Skip"])
                                except:
                                    print(
                                        "Cannot find Skip variable in event code"
                                    )
                                    return False
                                if RowStartID <= k and Skip == 0:
                                    # Create Condition Directory
                                    try:
                                        value = dir[Condition]
                                        value.append(
                                            [float(Onset),
                                             float(Duration)])
                                        dir[Condition] = value
                                    except KeyError:
                                        value = list()
                                        value.append(
                                            [float(Onset),
                                             float(Duration)])
                                        dir[Condition] = value

                            for condinx, cond in enumerate(dir):
                                self.add_condTitle(
                                    title=cond,
                                    ConditionTitles=self.ConditionTitles)

                            Events.append([MatAddr, EventFolder, dir])
                            print(
                                "Subject %d, Counter %d, Run %d is verified." %
                                (s, cnt, r))
            # Create Standard Condition Titles list
            conditions = []
            for cond in self.ConditionTitles:
                conditions.append([
                    setting.CondPre + "_" +
                    str(self.get_condID(cond[0], self.ConditionTitles)),
                    cond[0]
                ])

            conditions = np.array(conditions, dtype=object)

            # Normalized the condition titile for all events
            StandardEvents = []
            for event in Events:
                StandardEvent = dict()
                StandardEvent["Cond"] = conditions
                for cond in event[2]:
                    StandardEvent[setting.CondPre + "_" + str(
                        self.get_condID(
                            cond, self.ConditionTitles))] = event[2][cond]
                # Add list of titles
                StandardEvents.append([event[0], event[1], StandardEvent])
            print("Events were normalized! Generating event files ...")
            # Save Files
            for event in StandardEvents:
                try:
                    os.mkdir(event[1])
                except:
                    pass
                io.savemat(event[0], event[2])
                for tabs in event[2]:
                    if tabs == "Cond":
                        conFile = open(event[1] + tabs + ".txt", "w")
                        for con in event[2][tabs]:
                            conFile.write(
                                str(con[0]) + "\t" + str(con[1]) + "\n")
                        conFile.close()
                    else:
                        tabFile = open(event[1] + tabs + ".tab", "w")
                        for onset in event[2][tabs]:
                            tabFile.write(
                                str(onset[0]) + "\t" + str(onset[1]) + "\t1\n")
                        tabFile.close()
                print("EVENT: " + event[1] + " is generated!")

            # Check Tab File
            for cond in conditions:
                for si, s in enumerate(Subjects):
                    for cnt in Counters[si]:
                        print(
                            "Checking Tab Files: Subject %d, Counter %d ..." %
                            (s, cnt))
                        for r in Runs[si]:
                            EventFolder = 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))
                            fname = EventFolder + cond[0] + '.tab'
                            if os.path.isfile(fname):
                                print(fname + " - is okay.")
                            else:
                                tabfile = open(fname, "w")
                                tabfile.write("0\t0\t0\n")
                                tabfile.close()
                                print(fname + " - is EMPTY!")

            # Report
            print("List of generated conditions:")
            print("Condition ID\tCondition Title")
            for cond in conditions:
                print("\t" + cond[0] + "\t\t\t" + cond[1])
Ejemplo n.º 11
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()
        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
Ejemplo n.º 12
0
    def btnReport_click(self):
        msgBox = QMessageBox()

        # 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

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

        # 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

        # 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

        # 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

        # 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

        print("Loading data ...")
        InData = io.loadmat(InFile)

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

        try:
            Subject = InData[ui.txtSubject.currentText()]
        except:
            print("Cannot load Subject ID")
            return

        try:
            Run = InData[ui.txtRun.currentText()]
        except:
            print("Cannot load Run ID")
            return

        try:
            Counter = InData[ui.txtCounter.currentText()]
        except:
            print("Cannot load Counter ID")
            return

        try:
            Task = InData[ui.txtTask.currentText()]

            TaskIndex = Task.copy()
            for tasindx, tas in enumerate(np.unique(Task)):
                TaskIndex[Task == tas] = tasindx + 1

        except:
            print("Cannot load Subject ID")
            return

        Unit = 1

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

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

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

        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 for the test set must be smaller than all possible folds! Number of all folds 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 for the test set must be divorceable to all possible folds! Number of all folds 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

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

        GUFold = np.unique(UnitFold)

        ui.txtReport.clear()

        print("Number of data in this level is " + str(len(UniqFold)))

        ui.txtReport.append("Number of data in this level is " + str(len(UniqFold)))

        FoldSizeStr = str(len(UniqFold))
        FirstShape = None


        for foldID, fold in enumerate(GUFold):
            Shape = np.shape(X[np.where(UnitFold == fold)])
            str2 = ""
            if FirstShape is None:
                FirstShape = Shape
            elif Shape != FirstShape:
                str2 = " - Problem"
            print("Shape of " +  fixstr(foldID + 1,len(FoldSizeStr)) + "-th data of " + FoldSizeStr + " is " + str(Shape) + str2)
            ui.txtReport.append("Shape of " + fixstr(foldID + 1,len(FoldSizeStr)) + "-th data of " + FoldSizeStr + " is " + str(Shape) + str2)

        ui.tabWidget.setCurrentIndex(2)