Exemple #1
0
    def loadMMS(self):
        """ chargement de la partie mutation model sequences des préférences
        """
        lines = []
        cfg = self.config
        if cfg.has_key("mutation_s_default_values"):
            try:
                for param in ["MEANMU", "GAMMU", "MEANK1", "GAMK1", "MEANK2", "GAMK2"]:
                    exec(
                        'lines.append("{0} %s[%s,%s,%s,%s]"%(cfg["mutation_s_default_values"]["{0}_law"],cfg["mutation_s_default_values"]["{0}_zero"],cfg["mutation_s_default_values"]["{0}_one"],cfg["mutation_s_default_values"]["{0}_two"],cfg["mutation_s_default_values"]["{0}_three"]))'.format(
                            param
                        )
                    )

                lines.append(
                    "MODEL %s %s %s"
                    % (
                        cfg["mutation_s_default_values"]["MODEL_model"],
                        cfg["mutation_s_default_values"]["MODEL_inv_sites_pc"],
                        cfg["mutation_s_default_values"]["MODEL_gamma_shape"],
                    )
                )
                self.mutmodS.setMutationConf(lines)
            except Exception as e:
                log(3, "Malformed mutation_s_default_values in configuration")
        else:
            log(3, "No MMS conf found")
 def putChoices(self):
     """ met les choix de scenario en place
     """
     bg = QButtonGroup(self)
     left = True
     for i in range(self.nb_sc):
         num = i+1
         if self.analysis.category == "modelChecking":
             check = QRadioButton("Scenario %s"%num,self)
             bg.addButton(check)
         else:
             check = QCheckBox("Scenario %s"%num,self)
         if self.analysis.category == "compare":
             check.setChecked(True)
         self.checklist.append(check)
         if left:
             self.ui.verticalLayout.addWidget(check)
         else:
             self.ui.verticalLayout_2.addWidget(check)
         left = not left
     # les deux cas où on a pas le choix des scenarios parce qu'ils sont trop peu
     if self.nb_sc == 1:
         self.checklist[0].setChecked(True)
         self.checklist[0].setDisabled(True)
         self.next_widget.ui.redefButton.hide()
     log(4,"type of next widget : %s"%type(self.next_widget))
     if self.nb_sc == 2 and "Comparison" in str(type(self.next_widget)):
         self.checklist[0].setChecked(True)
         self.checklist[0].setDisabled(True)
         self.checklist[1].setChecked(True)
         self.checklist[1].setDisabled(True)
         self.next_widget.ui.redefButton.hide()
Exemple #3
0
    def save(self):
        """ sauvegarde du projet -> mainconf, histconf, genconf, theadconf
        Si le gen et hist sont valides, on génère le header
        """
        log(2,"Saving project '%s'"%self.dir)
        self.parent.showStatus("Saving project %s"%self.name)

        if self.dir != None and self.dataFileName != "":
            # save meta project
            if os.path.exists((u"%s/%s"%(self.dir,self.parent.main_conf_name)).encode(self.fsCoding)):
                os.remove((u"%s/%s"%(self.dir,self.parent.main_conf_name)).encode(self.fsCoding))

            f = codecs.open((u"%s/%s"%(self.dir,self.parent.main_conf_name)).encode(self.fsCoding),'w',"utf-8")
            f.write("%s\n"%self.dataFileName)
            # recup du nombre de params (depuis historical model et les mutational qui varient)
            nb_param = self.hist_model_win.getNbParam()
            f.write("%s parameters and %s summary statistics\n\n"%(nb_param,self.getNbSumStats()))
            f.close()

            # save hist conf
            self.hist_model_win.writeHistoricalConfFromGui()
            # save gen conf
            self.writeGeneticConfFromGui()
            # save th conf et production du reftable header
            if self.gen_state_valid and self.hist_state_valid:
                self.writeThConf()
                self.writeAscertConf()
                self.writeRefTableHeader()
            self.saveAnalysis()
            self.parent.clearStatus()
            self.parent.showStatus("Project %s successfully saved"%self.name,2000)
        else:
            output.notify(self,"Saving is impossible","Project %s is not yet completly created"%self.name)
            self.parent.clearStatus()
    def drawAll(self):
        """ dessine les graphes de tous les paramètres
        """
        # nettoyage
        for fr in self.findChildren(QFrame,"frameDraw"):
            self.ui.horizontalLayout_2.removeWidget(fr)
            fr.hide()
            del fr
        for fr in self.findChildren(QFrame,"frameValues"):
            self.ui.horizontalLayout_3.removeWidget(fr)
            fr.hide()
            del fr
        self.dicoPlot = {}

        if os.path.exists((u"%s/analysis/%s/paramstatdens%s.txt"%(self.parent.dir,self.directory,self.file_subname)).encode(self.fsCoding)):
            f = codecs.open((u"%s/analysis/%s/paramstatdens%s.txt"%(self.parent.dir,self.directory,self.file_subname)).encode(self.fsCoding),"rU","utf-8")
            lines = f.readlines()
            f.close()
            dico_info_draw = {}
            l = 0
            orderedNames = []
            while l < (len(lines) - 1):
                name = lines[l].strip()
                values = lines[l+1]
                absv = lines[l+3]
                ordpr = lines[l+4]
                ordpo = lines[l+5]
                dico_info_draw[name] = [values,absv,ordpr,ordpo]
                orderedNames.append(name)
                l += 6
            for name in orderedNames:
                self.addDraw(name,dico_info_draw[name][0],dico_info_draw[name][1],dico_info_draw[name][2],dico_info_draw[name][3])
        else:
            log(3, "paramstatdens%s.txt not found for analysis %s"%(self.file_subname,self.analysis.name))
Exemple #5
0
 def loadFromDir(self):
     """ charge les infos à partir du répertoire self.dir
     """
     log(2,"Launching load procedures")
     # GUI
     self.ui.dirEdit.setText(self.dir)
     self.ui.browseDataFileButton.setDisabled(True)
     self.ui.browseDataFileButton.hide()
     self.ui.groupBox_6.show()
     self.ui.groupBox_7.show()
     self.ui.groupBox_8.show()
     self.ui.setHistoricalButton.setDisabled(False)
     self.ui.setGeneticButton.setDisabled(False)
     try:
         self.loadMyConf()
         # lecture de conf.hist.tmp
         self.hist_model_win.loadHistoricalConf()
         self.ascert_frame.loadAscertConf()
         self.loadSumStatsConf()
         self.sum_stat_wins.lockLociSelection()
         self.loadAnalysis()
     except Exception as e:
         log(1, traceback.format_exc())
         raise Exception("Impossible to read the project configuration\n\n%s"%e)
         output.notify(self,"Load error","Impossible to read the project configuration\n\n%s"%e)
Exemple #6
0
    def addRow(self,name="locus",type="M"):
        """ ajoute un locus à la liste principale (de locus)
        """
        self.ui.tableWidget.insertRow(self.ui.tableWidget.rowCount())
        #self.ui.tableWidget.setCellWidget(self.ui.tableWidget.rowCount()-1,i,QPushButton("View"))
        self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,0,QTableWidgetItem("%s"%(name)))
        self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,1,QTableWidgetItem("%s"%type))
        self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,0).setFlags(self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,0).flags() & ~Qt.ItemIsEditable)
        self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,1).setFlags(self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,1).flags() & ~Qt.ItemIsEditable)
        if type == "M":
            #self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,2,QTableWidgetItem("2"))
            #self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,3,QTableWidgetItem("40"))
            #self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,2).setTextAlignment(Qt.AlignRight)
            #self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,3).setTextAlignment(Qt.AlignRight)

            dos = QTableWidgetItem("2")
            tres = QTableWidgetItem("40")
            dos.setTextAlignment(Qt.AlignRight|Qt.AlignTop)
            tres.setTextAlignment(Qt.AlignRight|Qt.AlignTop)
            self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,2,dos)
            self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,3,tres)
            log(3,"Adding a locus (%s)"%tres.textAlignment())
        else:
            self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,2,QTableWidgetItem(" "))
            self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount()-1,3,QTableWidgetItem(" "))
            self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,2).setFlags(self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,2).flags() & ~Qt.ItemIsEditable)
            self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,3).setFlags(self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,3).flags() & ~Qt.ItemIsEditable)
Exemple #7
0
 def setGenetic(self):
     """ passe sur l'onglet correspondant
     """
     log(1, "Entering in Genetic Data Setting")
     self.ui.refTableStack.addWidget(self.gen_data_win)
     self.ui.refTableStack.setCurrentWidget(self.gen_data_win)
     self.setGenValid(False)
Exemple #8
0
 def hideFixedParams(self):
     fixed_params_list = self.parents.hist_model_win.getFixedParamList()
     for box in self.paramList:
         name = str(box.findChild(QLabel,"paramNameLabel").text())
         if name in fixed_params_list:
             box.hide()
             log(3,"Hiding parameter %s because its value is fixed"%name)
Exemple #9
0
    def setScenarios(self,scList):
        """ écrit la liste des scenarios à estimer
        """
        sumRec = 0
        plur= ""
        if len(scList)>1:
            plur = "s"

        lstxt=""
        self.scNumList = []
        for i in scList:
            lstxt+="%s, "%i
            sumRec+=self.parent.parent.readNbRecordsOfScenario(int(i))
            log(3,"Sum of scenarios records : %s"%sumRec)
            self.scNumList.append(i)
        lstxt = lstxt[:-2]

        txt = "Chosen scenario%s : %s"%(plur,lstxt)
        self.ui.scenariosLabel.setText(txt)
        self.ui.totNumSimLabel.setText(str(sumRec))
        # on le fait seulement si on n'est pas en édition
        if self.analysis.computationParameters == "":
            self.ui.cnosdEdit.setText(str(sumRec))
            nosdDefault = sumRec/100
            if nosdDefault < 1000:
                nosdDefault = 1000
            self.ui.nosdEdit.setText(str(nosdDefault))
Exemple #10
0
 def clearHistoricalModel(self):
     """ détruit le modèle historique et en instancie un nouveau
     """
     log(1,"Clearing historical model")
     self.ui.refTableStack.removeWidget(self.hist_model_win)
     self.hist_model_win = SetHistoricalModel(self)
     self.ui.refTableStack.insertWidget(0,self.hist_model_win)
     self.ui.refTableStack.setCurrentWidget(self.hist_model_win)
Exemple #11
0
 def setHistorical(self):
     """ passe sur l'onglet correspondant
     """
     log(1,"Entering in Historical Model Setting")
     ## nécéssaire seulement sous windows
     ## on dirait que sous linux, le simple setCurrentWidget rend l'onglet enabled
     self.ui.refTableStack.addWidget(self.hist_model_win)
     self.ui.refTableStack.setCurrentWidget(self.hist_model_win)
     self.setHistValid(False)
Exemple #12
0
 def loadRecent(self):
     recent_list = []
     if self.config.has_key("recent") and self.config["recent"].has_key("projectPathList"):
         log(3, "Loading recent list")
         for rec in self.config["recent"]["projectPathList"].split("\n"):
             if len(rec) > 0 and rec.strip() != "":
                 recent_list.append(rec.strip())
                 log(4, "Loading recent : %s" % rec.strip())
         self.parent.setRecent(recent_list)
Exemple #13
0
 def setGenetic(self):
     """ initie la définition des summary statistics
     """
     log(1,"Entering in Summary statistics")
     #ty = str(self.typeCombo.currentText())
     self.ui.refTableStack.addWidget(self.sum_stat_wins)
     self.ui.refTableStack.setCurrentWidget(self.sum_stat_wins)
     self.setGenValid(False)
     self.sum_stat_wins.lockLociSelection()
Exemple #14
0
 def run(self):
     self.ui.runReftableButton.setText("Pre-processing of the observed dataset : please wait")
     check = self.__check()
     if check == True :
         if "pre-processing" in str(self.ui.runReftableButton.text()).lower() :
             self.ui.runReftableButton.setText("Running ...")
     else :
         log(1, "checkFileExistThread could not find %s" % self.file)
     self.terminate()
     del self
Exemple #15
0
    def loadDataFile(self,name):
        """ Charge le fichier de données passé en paramètre. Cette fonction est appelée lors
        de l'ouverture d'un projet existant et lors du choix du fichier de données pour un nouveau projet
        """
        log(2,"Loading datafile '%s'"%name)
        ## conversion de dos à unix
        #if not isUnixText(name):
        #    dos2unix(name)
        buttonPreviousText = self.runReftableButton.text()
        self.runReftableButton.setText("Checking data file format : please wait")
        try:
            self.data = DataSnp(name)
            typestr = ""
            for ty in self.typesOrdered :
                if ty in self.data.ntypeloc.keys():
                    typestr += " %s : %s,"%(ty,self.data.ntypeloc[ty])
            typestr = typestr[:-1]
            if str(self.data.commentValuesDict['maf']).lower() == "hudson" :
                if self.data.nloctot != self.data.nloc :
                    output.notify(self,"Monomorphic Loci warning","Your dataset includes a fraction of monomorphic loci :\n\nONLY POLYMORPHIC LOCI WILL BE CONSIDERED AFTERWARDS.")
                self.ui.dataFileInfoLabel.setText("MAF = hudson   : %s polymorphic loci  + %s monomorphic loci\n%s individuals in %s samples\n%s" % \
                                                (self.data.nloc,(self.data.nloctot-self.data.nloc),self.data.nindtot,self.data.nsample,typestr))
            else :
                self.ui.dataFileInfoLabel.setText("MAF = %s  : %s loci fitting the  MAF (over %s)\n%s individuals in %s samples\n%s" % \
                                                (self.data.commentValuesDict['maf'], self.data.nloc,self.data.nloctot,self.data.nindtot,self.data.nsample,typestr))
            self.ui.dataFileEdit.setText(name)
            self.dataFileSource = name

        except Exception as e:
            log(1, traceback.format_exc())
            keep = ""
            if self.ui.dataFileEdit.text() != "":
                keep = "\n\nThe file was not loaded, nothing was changed"
            output.notify(self,"Data file error","%s%s"%(e,keep))
            self.runReftableButton.setText(buttonPreviousText)
            return False



        # on declare les sumstats apres avoir chargé le datafile car c'est nécessaire
        # feinte pour que le parent.parent renvoie au projet
        self.dummy = QFrame()
        self.dummy.parent = self
        self.clearSummaryStats()

        # selection du type de snp pour sumstats kkpz a retirer
        #self.typeCombo = QComboBox(self)
        #for ty in self.typesOrdered:
        #    if ty in self.data.ntypeloc.keys():
        #        self.typeCombo.addItem(ty)
        #self.ui.horizontalLayout_6.addWidget(QLabel("for locus type :"))
        #self.ui.horizontalLayout_6.addWidget(self.typeCombo)
        self.runReftableButton.setText(buttonPreviousText)
        return True
Exemple #16
0
 def checkAll(self):
     """ vérification du modèle historique et mutationnel
     cette fonction est appelée au chargement du projet pour restituer l'etat du projet
     """
     log(2, "Checking validity of Historical Model and Genetic Data")
     # historical model :
     self.hist_model_win.definePriors(silent=True)
     if self.hist_model_win.checkAll(silent=True):
         self.setHistValid(True)
         self.hist_model_win.majProjectGui()
     # mutation model : plus facile d'utiliser directement la validation
     self.gen_data_win.validate(silent=True)
Exemple #17
0
 def writeThConf(self):
     """ ecrit le header du tableau de resultat qui sera produit par les calculs
     il contient, les paramètres historicaux,  les summary stats
     """
     log(2,"Writing last part of the header (the parameter table header) in %s"%self.parent.table_header_conf_name)
     hist_params_txt = self.hist_model_win.getParamTableHeader()
     sum_stats_txt = self.getSumStatsTableHeader()
     if os.path.exists((u"%s/%s"%(self.dir,self.parent.table_header_conf_name)).encode(self.fsCoding)):
         os.remove((u"%s/%s"%(self.dir,self.parent.table_header_conf_name)).encode(self.fsCoding))
     f = codecs.open((u"%s/%s"%(self.dir,self.parent.table_header_conf_name)).encode(self.fsCoding),'w',"utf-8")
     f.write("scenario%s%s"%(hist_params_txt,sum_stats_txt))
     f.close()
Exemple #18
0
 def saveRecent(self):
     log(3, "Saving recent list")
     if not self.config.has_key("recent"):
         self.config["recent"] = {}
     recList = self.parent.getRecent()
     cfgRecentIndex = 0
     rec_cfg = ""
     for rec in recList:
         log(4, "Saving into recent list : %s" % rec)
         rec_cfg += "{0}\n".format(rec)
     # delete last '\n'
     rec_cfg = rec_cfg[:-1]
     self.config["recent"]["projectPathList"] = rec_cfg
Exemple #19
0
    def saveFile(self):
        fname = str(QFileDialog.getSaveFileName(self,"Save log file","","(logfile) *.log"))
        if fname != "":
            if not fname.endswith(".log"):
                fname = "%s.log"%fname
            sf=open(fname.encode(self.fsCoding),'w')

            lf=open(self.parent.logfile.encode(self.fsCoding),'r')
            text=lf.read()
            lf.close()

            sf.write(text)
            sf.close()
            log(1,"Saving logfile into %s"%fname)
Exemple #20
0
 def loadMyConf(self):
     """ lit le fichier conf.tmp pour charger le fichier de données
     """
     log(2, "Reading '%s' to load datafile" % self.parent.main_conf_name)
     if os.path.exists((u"%s/%s" % (self.ui.dirEdit.text(), self.parent.main_conf_name)).encode(self.fsCoding)):
         f = open((u"%s/%s" % (self.dir, self.parent.main_conf_name)).encode(self.fsCoding), "rU")
         lines = f.readlines()
         self.dataFileName = lines[0].strip()
         self.ui.dataFileEdit.setText(self.dataFileName)
         # lecture du dataFile pour les infos de Gui Projet
         if os.path.exists((u"%s/%s" % (self.dir, self.dataFileName)).encode(self.fsCoding)):
             if self.loadDataFile((u"%s/%s" % (self.dir, self.dataFileName)).encode(self.fsCoding)):
                 # comme on a lu le datafile, on peut remplir le tableau de locus dans setGeneticData
                 self.gen_data_win.fillLocusTableFromData()
             else:
                 log(1, traceback.format_exc())
                 raise Exception(
                     "Impossible to load the datafile (%s) which is possibly malformed" % self.dataFileName
                 )
         else:
             log(1, traceback.format_exc())
             raise Exception("Datafile doesn't exist (%s)" % self.dataFileName)
     else:
         log(1, traceback.format_exc())
         raise Exception("Main conf file not found (%s)" % self.parent.main_conf_name)
Exemple #21
0
    def loadHM(self):
        """ chargement de la partie historical model des préférences
        """
        cfg = self.config
        if cfg.has_key("hist_model_default_values"):
            dico_val = {}
            pairs = cfg["hist_model_default_values"].items()
            for p in pairs:
                dico_val[p[0]] = p[1]

            try:
                for key in [
                    "nmin",
                    "nmax",
                    "nmean",
                    "nstdev",
                    "tmin",
                    "tmax",
                    "tmean",
                    "tstdev",
                    "amin",
                    "amax",
                    "amean",
                    "astdev",
                ]:
                    editname = key[0].upper() + key[1:]
                    exec('self.hist_model.%sEdit.setText(str(dico_val["%s"]))' % (editname, key))
                for pair in [
                    ("nlaw", "UN"),
                    ("nlaw", "LN"),
                    ("nlaw", "NO"),
                    ("nlaw", "LU"),
                    ("alaw", "UN"),
                    ("alaw", "LN"),
                    ("alaw", "NO"),
                    ("alaw", "LU"),
                    ("tlaw", "UN"),
                    ("tlaw", "LN"),
                    ("tlaw", "NO"),
                    ("tlaw", "LU"),
                ]:
                    exec(
                        'if dico_val["%s"] == "%s": self.hist_model.%sRadio.setChecked(True)'
                        % (pair[0], pair[1], pair[0][0].upper() + pair[1])
                    )
            except Exception as e:
                log(3, "Malformed hist_model_default_values section in configuration\n\n%s" % e)
        else:
            log(3, "No hist conf found")
    def viewMmmq(self):
        """ clic sur le bouton view numerical
        """
        if os.path.exists((u"%s/analysis/%s/mmmq%s.txt"%(self.parent.dir,self.directory,self.file_subname)).encode(self.fsCoding)):
            f = open((u"%s/analysis/%s/mmmq%s.txt"%(self.parent.dir,self.directory,self.file_subname)).encode(self.fsCoding),'r')
            data = f.read()
            f.close()

            self.parent.drawAnalysisFrame = ViewTextFile(data,self.returnToMe,self.parent)
            self.parent.drawAnalysisFrame.choiceFrame.hide()

            self.parent.ui.analysisStack.addWidget(self.parent.drawAnalysisFrame)
            self.parent.ui.analysisStack.setCurrentWidget(self.parent.drawAnalysisFrame)
        else:
            log(3, "mmmq%s.txt not found for analysis %s"%(self.file_subname,self.analysis.name))
    def drawAll(self):
        """ dessine les graphes de tous les paramètres
        """
        if os.path.exists((u"%s/analysis/%s/compdirect.txt"%(self.parent.dir,self.directory)).encode(self.fsCoding)):
            (first_line_tab,dico_coord) = self.getCoord("%s/analysis/%s/compdirect.txt"%(self.parent.dir,self.directory))
            self.addDraw(first_line_tab,dico_coord,True)
        else:
            log(3, "compdirect.txt not found")

        if self.analysis.logreg==True :
            if os.path.exists((u"%s/analysis/%s/complogreg.txt"%(self.parent.dir,self.directory)).encode(self.fsCoding)):
                (first_line_tab,dico_coord) = self.getCoord("%s/analysis/%s/complogreg.txt"%(self.parent.dir,self.directory))
                self.addDraw(first_line_tab,dico_coord,False)
            else:
                log(3, "complogreg.txt not found")
Exemple #24
0
    def writeAscertConf(self):
        log(2,"Writing ascertainment in %s"%self.parent.ascertainment_conf_name)

        ascert_string = u""
        if self.ascert_frame.ascYesRadio.isChecked():
            ascert_string += "%s\n"%str(self.ascert_frame.asc1ValEdit.text()).strip()
            ascert_string += "%s\n"%str(self.ascert_frame.asc2ValEdit.text()).strip()
            ascert_string += "%s\n"%str(self.ascert_frame.asc3ValEdit.text()).strip()
        else:
            ascert_string = u"\n"


        if os.path.exists((u"%s/%s"%(self.dir,self.parent.ascertainment_conf_name)).encode(self.fsCoding)):
            os.remove((u"%s/%s"%(self.dir,self.parent.ascertainment_conf_name)).encode(self.fsCoding))
        f = codecs.open((u"%s/%s"%(self.dir,self.parent.ascertainment_conf_name)).encode(self.fsCoding),'w',"utf-8")
        f.write("%s"%(ascert_string))
        f.close()
Exemple #25
0
    def initialize(self):
        app = QApplication(sys.argv)

        dd = datetime.now()
        logfile = os.path.expanduser("~/.diyabc/logs/test_%02d_%02d_%s-%02dh_%02dm-%s.log"%(dd.day,dd.month,dd.year,dd.hour,dd.minute,os.getpid()))
        diyabc = Diyabc(app,logfile=logfile)
        diyabc.show()
        # pour le dragNdrop des dossier projet
        diyabc.setAcceptDrops(True)
        # pour les logs dans un fichier et sur le terminal
        # chaque TeeLogger remplace une sortie et écrit dans
        # le fichier qu'on lui donne
        myOut = TeeLogger(logfile,True,diyabc.showLog)
        myErr = TeeLogger(logfile,False,diyabc.showLog)
        sys.stdout = myOut
        sys.stderr = myErr
        log(1,"\033[5;36m DIYABC launched \033[00m")
        return diyabc
Exemple #26
0
 def validate(self):
     """ clic sur le bouton validate
     verifie la validité de tous les groupes (mutmodel valide && nbsumstats > 0 && nblocus > 0)
     si valide : sort , maj de l'icone de validité et sauve
     si non valide : informe et sauve
     """
     log(3,"Validation of Genetic Data of analysis")
     #print self.group_info_dico
     #print self.dico_num_and_numgroup_locus
     mutconf_list = []
     problem = u""
     for i,box in enumerate(self.groupList):
         title = str(box.title())
         if "Microsatellites" in title:
             mutconf_list.append(self.setMutation_dico[box].getMutationConf())
             if box not in self.setMutationValid_dico.keys() or not self.setMutationValid_dico[box]:
                 problem += u"Mutation model of group %s is not considered as valid\n"%(i+1)
         elif "Sequences" in title:
             mutconf_list.append(self.setMutationSeq_dico[box].getMutationConf())
             if box not in self.setMutationSeqValid_dico.keys() or not self.setMutationSeqValid_dico[box]:
                 problem += u"Mutation model of group %s is not considered as valid\n"%(i+1)
         else:
             problem += u"Group %s is empty\n"%(i+1)
     if problem != u"":
         QMessageBox.information(self,"Impossible to validate the genetic data",problem)
         self.parents.setGenValid(False)
     else:
         # c'est valide, on passe à la dernière phase de paramètrage
         if self.analysis.drawn:
             self.analysis.mutationModelDrawn = mutconf_list
         else:
             self.analysis.mutationModelFixed = mutconf_list
         if self.analysis.category == "bias":
             #next_title = "bias and precision"
             last_parametrisation = SetupEstimationBias(self.analysis,self)
         else:
             #next_title = "evaluate confidence"
             last_parametrisation = SetupComparisonConfidence(self.analysis,self)
         #self.parent.addTab(last_parametrisation,next_title)
         #self.parent.removeTab(self.parent.indexOf(self))
         #self.parent.setCurrentWidget(last_parametrisation)
         self.ui.parents.analysisStack.addWidget(last_parametrisation)
         self.ui.parents.analysisStack.removeWidget(self)
         self.ui.parents.analysisStack.setCurrentWidget(last_parametrisation)
Exemple #27
0
 def freezeGenData(self,yesno=True):
     try:
         g = self.sum_stat_wins
         for e in g.findChildren(QLineEdit):
             e.setDisabled(yesno)
         for e in g.findChildren(QPushButton):
             e.setDisabled(yesno)
         for e in g.findChildren(QCheckBox):
             e.setDisabled(yesno)
         g.ui.clearButton.setDisabled(yesno)
         g.ui.exitButton.setDisabled(yesno)
         g.ui.okButton.setDisabled(False)
         g.ui.addAdmixButton.setDisabled(yesno)
         if yesno:
             self.ui.setGeneticButton.setText("            View")
         else:
             self.ui.setGeneticButton.setText("            Set")
     except AttributeError as e:
         log(4,"Fail to freeze gen data")
Exemple #28
0
    def loadMMM(self):
        """ chargement de la partie mutation model microsats des préférences
        """
        lines = []
        dico = {}
        cfg = self.config
        if cfg.has_key("mutation_m_default_values"):
            try:
                for param in ["MEANMU", "GAMMU", "MEANP", "GAMP", "MEANSNI", "GAMSNI"]:
                    exec(
                        'lines.append("{0} %s[%s,%s,%s,%s]"%(cfg["mutation_m_default_values"]["{0}_law"],cfg["mutation_m_default_values"]["{0}_zero"],cfg["mutation_m_default_values"]["{0}_one"],cfg["mutation_m_default_values"]["{0}_two"],cfg["mutation_m_default_values"]["{0}_three"]))'.format(
                            param
                        )
                    )
                self.mutmodM.setMutationConf(lines)
            except Exception as e:
                log(3, "Malformed mutation_m_default_values in configuration")

        else:
            log(3, "No MMM conf found")
Exemple #29
0
    def writeRefTableHeader(self):
        """ écriture du header.txt à partir des conf
        """
        super(ProjectSnp,self).writeRefTableHeader()

        if os.path.exists((u"%s/%s"%(self.dir,self.parent.ascertainment_conf_name)).encode(self.fsCoding)):
            f = codecs.open((u"%s/%s"%(self.dir,self.parent.ascertainment_conf_name)).encode(self.fsCoding),"rU","utf-8")
            ascert_string = f.read()
            f.close()
        else:
            output.notify(self,"Header generation problem","Impossible to add ascertainment part to header : ascertainment file doesn't exist")
            return

        if os.path.exists((u"%s/%s"%(self.dir,self.parent.reftableheader_name)).encode(self.fsCoding)):
            log(2,"Adding ascertainment part to header")

            fdest = codecs.open((u"%s/%s"%(self.dir,self.parent.reftableheader_name)).encode(self.fsCoding),"a","utf-8")
            fdest.write("\n\n%s"%ascert_string)
            fdest.close()
        else:
            output.notify(self,"Header generation problem","Impossible to add ascertainment part to header : header doesn't exist")
Exemple #30
0
 def launchReftableGeneration(self):
     # SNP Tests remove bin and bin.txt if no reftable was generated + check if MAF was modified
     dataFile = str(self.ui.dataFileEdit.text())
     if int(self.ui.nbSetsDoneEdit.text() )< 1 or not os.path.exists((u"%s/reftable.bin"%self.dir).encode(self.fsCoding)):
         log(3,"No reftable.bin found, try to remove %s and %s"%(dataFile+".bin", dataFile+"bin.txt"))
         if os.path.exists((dataFile+".bin").encode(self.fsCoding)) :
             os.remove((dataFile+".bin").encode(self.fsCoding))
             log(3, "%s removed" % (dataFile+".bin"))
         if os.path.exists((dataFile+"bin.txt").encode(self.fsCoding)) :
             os.remove((dataFile+"bin.txt").encode(self.fsCoding))
             log(3, "%s removed" % (dataFile+"bin.txt"))
     else :
         f=open(dataFile.encode(self.fsCoding),'r')
         words = f.readline().strip().split()
         f.close()
         commentWordsDict = DataAbstract.getParseCommentWordsDict(words)
         f=open((os.path.join(str(self.dir),"maf.txt")).encode(self.fsCoding),'r')
         maf = f.readline().strip().lower()
         f.close()
         if "hudson" in maf :
             maf = "hudson"
         else :
             maf = str(float(maf))
             commentWordsDict["maf"] = str(float(commentWordsDict["maf"]))
         if str(commentWordsDict["maf"]) != maf :
             output.notify(self,"MAF value error","The actual reftable was generated with <MAF=%s> but your data file %s says <MAF=%s> !\nRemove your reftable.bin file or fix your maf data file" % (maf, dataFile ,commentWordsDict["maf"]))
             return
     if not os.path.exists((dataFile+".bin").encode(self.fsCoding)) :
         if self.checkSNPbin == None :
             self.checkSNPbin = checkFileExistThread(file=dataFile+".bin", ui=self)
         self.checkSNPbin.start()
     #checkSNPbin.updateInterfaceForSnpBin()
     super(ProjectSnp, self).launchReftableGeneration()