def __init__(self,nb_sc,label,next_widget,next_title,nb_min_sel,analysis,parent): super(GenericScenarioSelection,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.nb_sc = nb_sc self.nb_min_sel = nb_min_sel self.next_widget = next_widget self.next_title = next_title self.checklist = [] self.createWidgets() self.ui.selectionLabel.setText(label) self.ui.analysisTypeLabel.setText(self.next_title) self.ui.projectDirEdit.setText(self.parents.dir) self.putChoices() self.ui.verticalLayout_3.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_3.setAlignment(Qt.AlignTop) self.ui.verticalLayout_2.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_2.setAlignment(Qt.AlignTop) self.ui.verticalLayout.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout.setAlignment(Qt.AlignTop) self.restoreAnalysisValues()
def __init__(self,nb_sc,analysis,parent=None): super(ConfidenceTypeSelection,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.nb_sc = nb_sc self.createWidgets() self.restoreAnalysisValues()
def __init__(self,analysis,parent=None): super(SetupComparisonConfidence,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.scNumList = [] self.dico_values = {} self.createWidgets() self.ui.verticalLayout_2.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_2.setAlignment(Qt.AlignTop) self.restoreAnalysisValues() self.parents.updateDoc(self)
def __init__(self,analysis,parent=None): super(HistFixed,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.sc_to_show = self.analysis.chosenSc self.list_selected_evaluate_sc = self.analysis.candidateScList self.paramList = [] self.condList = [] self.param_info_dico = {} self.createWidgets() self.addTheSc() self.addTheParams() self.restoreAnalysisValues()
def __init__(self,nb_sc,analysis,parent=None): super(BiasNConfidenceScenarioSelection,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.nb_sc = nb_sc self.checklist = [] self.radiolist = [] self.createWidgets() self.putChoices() self.ui.verticalLayout_3.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_3.setAlignment(Qt.AlignTop) self.ui.verticalLayout_2.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_2.setAlignment(Qt.AlignTop) self.ui.verticalLayout.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout.setAlignment(Qt.AlignTop) self.restoreAnalysisValues()
def __init__(self,parent=None): super(SetGeneticData,self).__init__(parent) self.parent=parent self.parents=Parents(self.parent) # liste des box self.groupList = [] # dicos de frames indexé par les box self.setMutation_dico = {} self.setMutationSeq_dico = {} self.setSum_dico = {} self.setSumSeq_dico = {} # dicos de booleens indexé par les box self.setMutationValid_dico = {} self.setMutationSeqValid_dico = {} # dico indexé par la box du groupe self.group_info_dico = {} self.nbLocusGui = 0 # dico indexé par les noms de locus, qui donne le numero du locus et le groupe du locus self.dico_num_and_numgroup_locus = {} self.createWidgets()
class SetGeneticData(formGenData,baseGenData): """ Frame qui est créée pour faire des groupes de locus, déterminer leur modèle mutationnel et leur summary statistics """ def __init__(self,parent=None): super(SetGeneticData,self).__init__(parent) self.parent=parent self.parents=Parents(self.parent) # liste des box self.groupList = [] # dicos de frames indexé par les box self.setMutation_dico = {} self.setMutationSeq_dico = {} self.setSum_dico = {} self.setSumSeq_dico = {} # dicos de booleens indexé par les box self.setMutationValid_dico = {} self.setMutationSeqValid_dico = {} # dico indexé par la box du groupe self.group_info_dico = {} self.nbLocusGui = 0 # dico indexé par les noms de locus, qui donne le numero du locus et le groupe du locus self.dico_num_and_numgroup_locus = {} self.createWidgets() def createWidgets(self): #self.ui = Ui_Frame() self.ui = self self.ui.setupUi(self) self.ui.verticalLayout_3.setAlignment(QtCore.Qt.AlignTop) self.ui.tableWidget.setColumnWidth(0,230) self.ui.tableWidget.setColumnWidth(1,60) self.ui.tableWidget.setColumnWidth(2,60) self.ui.tableWidget.setColumnWidth(3,60) QObject.connect(self.ui.addGroupButton,SIGNAL("clicked()"),self.addGroup) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.validate) QObject.connect(self.ui.exitButton,SIGNAL("clicked()"),self.exit) QObject.connect(self.ui.clearButton,SIGNAL("clicked()"),self.clear) self.ui.analysisFrame.hide() self.ui.autoGroupButton.hide() def updateDoc(self,obj=None): """ Met à jour la doc uniquement pour les fils de l'objet obj. Fonctionne tant que les instances de SetGeneticData ont pour parent.parent l'objet Diyabc """ self.parents.updateDoc(obj) def fillLocusTableFromData(self): """ rempli le tableau des locus en consultant l'instance de Data On ne peut pas le faire à l'instanciation de l'objet SetGeneticData car on a pas encore lu le fichier de conf dans le cas d'un load project """ data = self.parents.data nb_m = 0 nb_s = 0 for i in range(data.nloc): if data.locuslist[i].type > 4: self.addRow(name=data.locuslist[i].name,type="S") nb_s += 1 else: self.addRow(name=data.locuslist[i].name,type="M") nb_m += 1 self.dico_num_and_numgroup_locus[data.locuslist[i].name] = [i+1,0] self.nbLocusGui+=1 # affichage du bon nombre de locus dans l'onglet principal du projet self.majProjectGui(m=nb_m,s=nb_s) 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) def addGroup(self): """ dessine un nouveau groupe vide """ groupBox = QtGui.QGroupBox("Group %i"%(len(self.groupList)+1),self.ui.scrollAreaWidgetContents) groupBox.setMinimumSize(QtCore.QSize(0, 200)) groupBox.setMaximumSize(QtCore.QSize(16777215, 200)) groupBox.setObjectName("groupBox") horizontalLayout = QtGui.QHBoxLayout(groupBox) horizontalLayout.setObjectName("horizontalLayout") verticalLayout = QtGui.QVBoxLayout() verticalLayout.setObjectName("verticalLayout") addToButton = QtGui.QPushButton(">>",groupBox) addToButton.setObjectName("addToGroupButton") verticalLayout.addWidget(addToButton) rmFromButton = QtGui.QPushButton("<<",groupBox) rmFromButton.setObjectName("rmFromGroupButton") verticalLayout.addWidget(rmFromButton) horizontalLayout.addLayout(verticalLayout) verticalLayout_3 = QtGui.QVBoxLayout() verticalLayout_3.setObjectName("verticalLayout_3") rmButton = QtGui.QPushButton("Remove group",groupBox) rmButton.setObjectName("rmLocusGroupButton") verticalLayout_3.addWidget(rmButton) listWidget = QtGui.QListWidget(groupBox) listWidget.setObjectName("locusGroupList") verticalLayout_3.addWidget(listWidget) horizontalLayout.addLayout(verticalLayout_3) listWidget.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) verticalLayout_2 = QtGui.QVBoxLayout() verticalLayout_2.setObjectName("verticalLayout_2") setMutationButton = QtGui.QPushButton("Set mutation\nModel",groupBox) setMutationButton.setObjectName("setMutationButton") verticalLayout_2.addWidget(setMutationButton) setSumButton = QtGui.QPushButton("Set Summary\nStatistics",groupBox) setSumButton.setObjectName("setSumButton") verticalLayout_2.addWidget(setSumButton) horizontalLayout.addLayout(verticalLayout_2) self.ui.verticalLayout_3.addWidget(groupBox) QObject.connect(addToButton,SIGNAL("clicked()"),self.addToGroup) QObject.connect(rmFromButton,SIGNAL("clicked()"),self.rmFromGroup) QObject.connect(rmButton,SIGNAL("clicked()"),self.rmGroup) QObject.connect(setMutationButton,SIGNAL("clicked()"),self.setMutation) QObject.connect(setSumButton,SIGNAL("clicked()"),self.setSum) self.groupList.append(groupBox) self.group_info_dico[groupBox] = [ "" , [] ] self.majProjectGui(g=len(self.groupList)) return groupBox def switchTo(self,widget): """ methode virtuelle a redefinir """ pass def setMutation(self,box=None): """ déclenché par le clic sur le bouton 'set mutation model' ou par le clic sur 'clear' dans 'set mutation model'. bascule vers la saisie du modèle mutationnel """ if box == None: box = self.sender().parent() title = str(box.title()) if "Microsatellites" in title: #self.parent.addTab(self.setMutation_dico[box],"Set mutation model") #self.parent.setTabEnabled(self.parent.indexOf(self),False) #self.parent.setCurrentWidget(self.setMutation_dico[box]) self.switchTo(self.setMutation_dico[box]) # maj du titre de la frame lab = self.setMutation_dico[box].ui.setMutMsLabel lab.setText("Set mutation model of %s (microsatellites)"%(" ".join(str(box.title()).split()[:2]))) # on considère que le setmutation n'est plus valide, il faut le revalider self.setMutationValid_dico[box] = False elif "Sequences" in title: #self.parent.addTab(self.setMutationSeq_dico[box],"Set mutation model") #self.parent.setTabEnabled(self.parent.indexOf(self),False) #self.parent.setCurrentWidget(self.setMutationSeq_dico[box]) self.switchTo(self.setMutationSeq_dico[box]) # maj du titre de la frame lab = self.setMutationSeq_dico[box].ui.setMutSeqLabel lab.setText("Set mutation model of %s (sequences)"%(" ".join(str(box.title()).split()[:2]))) # on considère que le setmutation n'est plus valide, il faut le revalider self.setMutationSeqValid_dico[box] = False else: output.notify(self,"Set Mutation Model error","Add locus to a group before setting the mutation model") def rmGroup(self,box=None): """ Enlève les loci présents dans le groupe et supprime le groupe """ if (box == None): box = self.sender().parent() lw = box.findChild(QListWidget,"locusGroupList") lw.selectAll() self.rmFromGroup(box) # suppression de la box box.hide() self.groupList.remove(box) del self.group_info_dico[box] # renommage des groupes for i,box in enumerate(self.groupList): old_title = str(box.title()) box.setTitle("Group %i %s"%(i+1,' '.join(old_title.split()[2:]))) # pour chaque groupe, on maj le numero de groupe de tous les locus du groupe lw = box.findChild(QListWidget,"locusGroupList") for j in range(lw.count()): itemtxt = str(lw.item(j).text()) self.dico_num_and_numgroup_locus[itemtxt][1] = i+1 self.majProjectGui(g=len(self.groupList)) def addToGroup(self,box=None): """ ajoute les loci selectionnés au groupe du bouton pressé """ all_similar = True first_type_found = "" if box == None: box = self.sender().parent() listwidget = box.findChild(QListWidget,"locusGroupList") row_list = [] selection = self.ui.tableWidget.selectedIndexes() selection.sort() for it in selection: if it.row() not in row_list: row_list.append(it.row()) # verif que tous les loci selectionnés ont le meme type if first_type_found == "": first_type_found = str(self.ui.tableWidget.item(it.row(),1).text()) else: if first_type_found != str(self.ui.tableWidget.item(it.row(),1).text()): all_similar = False # verif que les loci deja dans le groupe sont du même type que ceux sélectionnés # on compare le premier type trouvé dans la selection avec le type du premier # élément du groupe if listwidget.count() > 0: if all_similar: name = str(listwidget.item(0).text()) #num = int(name.split(' ')[1]) num = self.dico_num_and_numgroup_locus[name][0] # info sur le premier locus du groupe type = str(self.ui.tableWidget.item(num-1,1).text()) #print "\ntype deja present : %s"%type if type != first_type_found: all_similar = False else: if all_similar: # le groupe est vide, on set le nom avec le type old_title = str(box.title()) tt = '' if first_type_found == 'M': tt = "Microsatellites" elif first_type_found == 'S': tt = "Sequences" if tt != '': box.setTitle("%s %s : %s"%(old_title.split()[0],old_title.split()[1],tt)) # on met à jour le dico des groupes self.group_info_dico[box][0] = tt if all_similar: # déselection des présents for ind_to_unselect in range(listwidget.count()): listwidget.item(ind_to_unselect).setSelected(False) # ajout des nouveaux for row in row_list: name = self.ui.tableWidget.item(row,0).text() # ajout trié dans le groupe i = 0 #num_to_insert = int(name.split(' ')[1]) num_to_insert = row+1 while i < listwidget.count() and self.dico_num_and_numgroup_locus[str(listwidget.item(i).text())][0] < num_to_insert : i+=1 #box.findChild(QListWidget,"locusGroupList").addItem(name) box.findChild(QListWidget,"locusGroupList").insertItem(i,name) box.findChild(QListWidget,"locusGroupList").item(i).setSelected(True) # on cache la ligne self.ui.tableWidget.setRowHidden(row,True) # on met à jour le dico des groupes self.group_info_dico[box][1].append(num_to_insert) # on met à jour le numero du groupe pour ce locus self.dico_num_and_numgroup_locus[str(name)][1] = (self.groupList.index(box)+1) else: output.notify(self,"Group error","In a group, all the loci must have the same type") def rmFromGroup(self,box=None): """ retire les loci selectionnés du groupe du bouton pressé """ if box == None: box = self.sender().parent() listw_of_group = box.findChild(QListWidget,"locusGroupList") row_list = [] selection = listw_of_group.selectedIndexes() for it in selection: if it.row() not in row_list: row_list.append(int(it.row())) row_list.sort() row_list.reverse() for row in row_list: name = str(listw_of_group.item(row).text()) #num = int(name.split(' ')[1]) num = self.dico_num_and_numgroup_locus[name][0] # retrait du groupe #item = listw_of_group.takeItem(row) listw_of_group.takeItem(row) # on decouvre la ligne self.ui.tableWidget.setRowHidden(num-1,False) # on met à jour le dico des groupes self.group_info_dico[box][1].remove(num) self.dico_num_and_numgroup_locus[name][1] = 0 # si le groupe devient vide, on enleve le type dans le nom if listw_of_group.count() == 0: old_title = str(box.title()) box.setTitle("%s %s"%(old_title.split()[0],old_title.split()[1])) # on met à jour le dico des groupes self.group_info_dico[box][0] = "" ## on remet en gras les boutons de mutation model et sum stats #set_mut_button = box.findChild(QPushButton,"setMutationButton") #set_sum_button = box.findChild(QPushButton,"setSumButton") #set_mut_button.setStyleSheet("background-color: #EFB1B3") #set_sum_button.setStyleSheet("background-color: #EFB1B3") #fontt = set_mut_button.font() #fontt.setBold(True) #set_mut_button.setFont(fontt) #set_sum_button.setFont(fontt) def getNbSumStats(self): """ retourne le nombre total de summary statistics (nb de cases cochées) """ nb_sum_stats = 0 for box in self.groupList: if "Microsatellites" in str(box.title()): (nstat,stat_txt) = self.setSum_dico[box].getSumConf() nb_sum_stats += nstat elif "Sequences" in str(box.title()): (nstat,stat_txt) = self.setSumSeq_dico[box].getSumConf() nb_sum_stats += nstat return nb_sum_stats def getNbParam(self): """ retourne le nombre de paramètres mutationnels réels (qui varient. min<max pour le MEAN) """ nb_param = 0 for box in self.groupList: if "Microsatellites" in str(box.title()): nb_param += self.setMutation_dico[box].getNbParam() elif "Sequences" in str(box.title()): nb_param += self.setMutationSeq_dico[box].getNbParam() return nb_param def getParamTableHeader(self): """ retourne la chaine des noms des paramètres pour le conf.th.tmp """ result = u"" for box in self.groupList: if "Microsatellites" in str(box.title()): params_txt = self.setMutation_dico[box].getParamTableHeader() elif "Sequences" in str(box.title()): params_txt = self.setMutationSeq_dico[box].getParamTableHeader() result += params_txt return result def getConstantParameters(self): """ retourne une liste de noms de paramètres mutationnels qui sont constants pour chaque groupe, le tout rangé dans un dico indexé par le numero de groupe """ result = {} for i,box in enumerate(self.groupList): if "Microsatellites" in str(box.title()): result[i] = self.setMutation_dico[box].getConstantParameters() elif "Sequences" in str(box.title()): result[i] = self.setMutationSeq_dico[box].getConstantParameters() return result def getSumStatsTableHeader(self): """ retourne la partie sumstats du table header """ result = u"" for box in self.groupList: if "Microsatellites" in str(box.title()): sums_txt = self.setSum_dico[box].getSumStatsTableHeader() elif "Sequences" in str(box.title()): sums_txt = self.setSumSeq_dico[box].getSumStatsTableHeader() result += sums_txt return result def clearSummaryStats(self,box): """ vide les summary statistics des microsats """ self.setSum_dico[box].exit() self.setSum_dico[box] = SetSummaryStatisticsMsat(self,box) self.setSum(box) def clearSummaryStatsSeq(self,box): """ vide les summary statistics des sequences """ self.setSumSeq_dico[box].exit() self.setSumSeq_dico[box] = SetSummaryStatisticsSeq(self,box) self.setSum(box)
class HistDrawn(formHistModelDrawn,baseHistModelDrawn): """ définition du modèle historique dans le cadre d'une analyse les valeurs ne sont pas fixées """ def __init__(self,analysis,parent=None): super(HistDrawn,self).__init__(parent) self.parent=parent self.parents = Parents(parent) self.analysis = analysis self.sc_to_show = self.analysis.chosenSc self.list_selected_evaluate_sc = self.analysis.candidateScList self.paramList = [] self.condList = [] self.param_info_dico = {} self.createWidgets() self.addTheSc() self.addTheParams() self.addTheConditions() self.hideFixedParams() self.restoreAnalysisValues() def createWidgets(self): self.ui=self self.ui.setupUi(self) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.validate) QObject.connect(self.ui.exitButton,SIGNAL("clicked()"),self.exit) self.ui.clearButton.hide() self.ui.frame_3.hide() self.ui.frame_2.hide() #self.ui.scrollArea_3.hide() self.ui.defPrButton.hide() self.ui.chkScButton.hide() self.ui.addScButton.hide() self.ui.drawPreviewsCheck.hide() self.ui.refreshPreviewsButton.hide() self.ui.verticalLayout_6.setAlignment(QtCore.Qt.AlignTop) self.ui.horizontalLayout_6.setAlignment(QtCore.Qt.AlignLeft) self.ui.horizontalLayout_2.setAlignment(QtCore.Qt.AlignLeft) self.ui.horizontalLayout_3.setAlignment(QtCore.Qt.AlignLeft) self.ui.analysisNameLabel.setText(self.analysis.name) def restoreAnalysisValues(self): if self.analysis.histParamsDrawn != None: for p in self.analysis.histParamsDrawn.keys(): for param in self.paramList: pname = str(param.findChild(QLabel,"paramNameLabel").text()) if pname == p: param.findChild(QLineEdit,"minValueParamEdit").setText(self.analysis.histParamsDrawn[p][2]) param.findChild(QLineEdit,"maxValueParamEdit").setText(self.analysis.histParamsDrawn[p][3]) param.findChild(QLineEdit,"meanValueParamEdit").setText(self.analysis.histParamsDrawn[p][4]) param.findChild(QLineEdit,"stValueParamEdit").setText(self.analysis.histParamsDrawn[p][5]) law = self.analysis.histParamsDrawn[p][1] if law == "LN": param.findChild(QRadioButton,'logNormalRadio').setChecked(True) elif law == "NO": param.findChild(QRadioButton,'normalRadio').setChecked(True) elif law == "UN": param.findChild(QRadioButton,'uniformParamRadio').setChecked(True) elif law == "LU": param.findChild(QRadioButton,'logUniformRadio').setChecked(True) 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) def addTheSc(self): # creation de la groupbox a ajouter groupBox = QtGui.QGroupBox(self.ui.scScrollContent) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox.sizePolicy().hasHeightForWidth()) groupBox.setSizePolicy(sizePolicy) groupBox.setObjectName("groupBox_"+str(self.sc_to_show)) verticalLayout_6 = QtGui.QVBoxLayout(groupBox) verticalLayout_6.setObjectName("verticalLayout_6") horizontalLayout_6 = QtGui.QHBoxLayout() horizontalLayout_6.setObjectName("horizontalLayout_6") label_3 = QtGui.QLabel("scenario %i"%self.sc_to_show,groupBox) # ne mettre qu'un seul label du nom scLabel pour pouvoir le retrouver avec findChild() label_3.setObjectName("scLabel") horizontalLayout_6.addWidget(label_3) verticalLayout_6.addLayout(horizontalLayout_6) plainTextEdit = QtGui.QPlainTextEdit(groupBox) plainTextEdit.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap) plainTextEdit.setObjectName("scplainTextEdit") verticalLayout_6.addWidget(plainTextEdit) # ajout de la groupbox self.ui.horizontalLayout_3.addWidget(groupBox) # recup du texte du scenario plainTextEdit.setPlainText(self.getScText()) plainTextEdit.setReadOnly(True) def getScText(self): """ récupère le texte du scenario concerné dans le modèle historique de la reftable """ return self.parents.hist_model_win.scList[self.sc_to_show-1].findChild(QPlainTextEdit,"scplainTextEdit").toPlainText() def addTheParams(self): """ trouve et ajoute les paramètres du scenario concerné """ try: sc = str(self.getScText()) scChecker = Scenario(number=self.sc_to_show) scChecker.checkread(sc.strip().split('\n'),self.parents.data) scChecker.checklogic() dico_sc_infos = {} dico_sc_infos["text"] = sc.strip().split('\n') dico_sc_infos["checker"] = scChecker #print "nb param du sc ",num," ",scChecker.nparamtot except Exception as e: output.notify(self,"Unexpected Error",str(e)) self.exit() return # calcul des infos pour savoir si on peut setCondition sur ce param dico_cat = {} lprem = [] for param in scChecker.parameters: if dico_cat.has_key(param.category): dico_cat[param.category] += 1 else: lprem.append(param.name) dico_cat[param.category] = 1 dico_param = self.parents.hist_model_win.param_info_dico for param in scChecker.parameters: pname = param.name pcat = param.category visible = False if pname not in lprem and dico_cat[pcat] > 1: visible = True elem = dico_param[pname] self.addParamGui(pname,elem[1],elem[2],elem[3],elem[4],elem[5],visible) self.param_info_dico[pname] = [pcat] def addTheConditions(self): """ récupère les conditions du modèle historique de la reftable contenant uniquement des paramètre du scenarion concerné """ self.majParamInfoDico() for condbox in self.parents.hist_model_win.condList: txt = str(condbox.findChild(QLabel,"condLabel").text()) if "<=" in txt: sep = "<=" elif ">=" in txt: sep = ">=" elif ">" in txt: sep = ">" elif "<" in txt: sep = "<" termes = txt.split(sep) if termes[0] in self.param_info_dico.keys() and termes[1] in self.param_info_dico.keys(): self.addCondition(txt) def addParamGui(self,name,law,min,max,mean,stdev,visible): """ ajoute un paramètre à la GUI et à la liste locale de paramètres et retourne la groupBox créée """ groupBox_8 = QtGui.QFrame(self.ui.scrollArea) #groupBox_8.setFrameShape(QtGui.QFrame.StyledPanel) #groupBox_8.setFrameShadow(QtGui.QFrame.Raised) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_8.sizePolicy().hasHeightForWidth()) groupBox_8.setSizePolicy(sizePolicy) groupBox_8.setMinimumSize(QtCore.QSize(0, 26)) groupBox_8.setMaximumSize(QtCore.QSize(16777215, 26)) groupBox_8.setObjectName("groupBox_8") horizontalLayout_13 = QtGui.QHBoxLayout(groupBox_8) horizontalLayout_13.setObjectName("horizontalLayout_13") horizontalLayout_13.setContentsMargins(-1, 1, -1, 1) groupBox_9 = QtGui.QGroupBox(groupBox_8) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_9.sizePolicy().hasHeightForWidth()) groupBox_9.setSizePolicy(sizePolicy) groupBox_9.setMinimumSize(QtCore.QSize(140, 25)) groupBox_9.setMaximumSize(QtCore.QSize(140, 25)) groupBox_9.setObjectName("groupBox_9") horizontalLayout_8 = QtGui.QHBoxLayout(groupBox_9) horizontalLayout_8.setObjectName("horizontalLayout_8") horizontalLayout_8.setContentsMargins(-1, 1, -1, 1) paramNameLabel = QtGui.QLabel(name,groupBox_9) paramNameLabel.setObjectName("paramNameLabel") horizontalLayout_8.addWidget(paramNameLabel) setCondButton = QtGui.QPushButton("set condition",groupBox_9) setCondButton.setObjectName("setCondButton") setCondButton.setMinimumSize(QtCore.QSize(80, 20)) setCondButton.setMaximumSize(QtCore.QSize(80, 20)) if not visible: setCondButton.hide() else: QObject.connect(setCondButton,SIGNAL("clicked()"),self.setConditionAction) if "darwin" in sys.platform: ff = setCondButton.font() ff.setPointSize(10) setCondButton.setFont(ff) else: ff = setCondButton.font() ff.setPointSize(8) setCondButton.setFont(ff) horizontalLayout_8.addWidget(setCondButton) horizontalLayout_13.addWidget(groupBox_9) groupBox_10 = QtGui.QGroupBox(groupBox_8) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_10.sizePolicy().hasHeightForWidth()) groupBox_10.setSizePolicy(sizePolicy) groupBox_10.setMinimumSize(QtCore.QSize(290, 25)) groupBox_10.setMaximumSize(QtCore.QSize(290, 25)) groupBox_10.setObjectName("groupBox_10") horizontalLayout_9 = QtGui.QHBoxLayout(groupBox_10) horizontalLayout_9.setObjectName("horizontalLayout_9") horizontalLayout_9.setContentsMargins(-1, 1, -1, 1) uniformParamRadio = QtGui.QRadioButton(groupBox_10) uniformParamRadio.setChecked(True) uniformParamRadio.setObjectName("uniformParamRadio") uniformParamRadio.setMinimumSize(QtCore.QSize(20, 0)) horizontalLayout_9.addWidget(uniformParamRadio) logUniformRadio = QtGui.QRadioButton(groupBox_10) logUniformRadio.setObjectName("logUniformRadio") logUniformRadio.setMinimumSize(QtCore.QSize(20, 0)) horizontalLayout_9.addWidget(logUniformRadio) normalRadio = QtGui.QRadioButton(groupBox_10) normalRadio.setObjectName("normalRadio") normalRadio.setMinimumSize(QtCore.QSize(20, 0)) horizontalLayout_9.addWidget(normalRadio) logNormalRadio = QtGui.QRadioButton(groupBox_10) logNormalRadio.setObjectName("logNormalRadio") logNormalRadio.setMinimumSize(QtCore.QSize(20, 0)) ## alignement des radio #uniformParamRadio.setAlignment(QtCore.Qt.AlignCenter) #logUniformRadio.setAlignment(QtCore.Qt.AlignCenter) #normalRadio.setAlignment(QtCore.Qt.AlignCenter) #logNormalRadio.setAlignment(QtCore.Qt.AlignCenter) horizontalLayout_9.addWidget(logNormalRadio) horizontalLayout_9.insertStretch(4) horizontalLayout_9.insertStretch(3) horizontalLayout_9.insertStretch(2) horizontalLayout_9.insertStretch(1) horizontalLayout_9.insertStretch(0) horizontalLayout_13.addWidget(groupBox_10) groupBox_14 = QtGui.QGroupBox(groupBox_8) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_14.sizePolicy().hasHeightForWidth()) groupBox_14.setSizePolicy(sizePolicy) groupBox_14.setMinimumSize(QtCore.QSize(0, 25)) groupBox_14.setMaximumSize(QtCore.QSize(16777215,25)) groupBox_14.setObjectName("groupBox_14") horizontalLayout_10 = QtGui.QHBoxLayout(groupBox_14) horizontalLayout_10.setObjectName("horizontalLayout_10") horizontalLayout_10.setContentsMargins(-1, 1, -1, 1) minValueParamEdit = QtGui.QLineEdit(groupBox_14) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(minValueParamEdit.sizePolicy().hasHeightForWidth()) minValueParamEdit.setSizePolicy(sizePolicy) minValueParamEdit.setMinimumSize(QtCore.QSize(60, 0)) minValueParamEdit.setMaximumSize(QtCore.QSize(60, 16777215)) minValueParamEdit.setObjectName("minValueParamEdit") horizontalLayout_10.addWidget(minValueParamEdit) maxValueParamEdit = QtGui.QLineEdit(groupBox_14) maxValueParamEdit.setMinimumSize(QtCore.QSize(60, 0)) maxValueParamEdit.setMaximumSize(QtCore.QSize(60, 16777215)) maxValueParamEdit.setObjectName("maxValueParamEdit") horizontalLayout_10.addWidget(maxValueParamEdit) meanValueParamEdit = QtGui.QLineEdit(groupBox_14) meanValueParamEdit.setMinimumSize(QtCore.QSize(60, 0)) meanValueParamEdit.setMaximumSize(QtCore.QSize(60, 16777215)) meanValueParamEdit.setObjectName("meanValueParamEdit") horizontalLayout_10.addWidget(meanValueParamEdit) stValueParamEdit = QtGui.QLineEdit(groupBox_14) stValueParamEdit.setMinimumSize(QtCore.QSize(60, 0)) stValueParamEdit.setMaximumSize(QtCore.QSize(60, 16777215)) stValueParamEdit.setObjectName("stValueParamEdit") horizontalLayout_10.addWidget(stValueParamEdit) horizontalLayout_13.addWidget(groupBox_14) self.ui.verticalLayout_6.addWidget(groupBox_8) # liste locale des paramètres self.paramList.append(groupBox_8) minValueParamEdit.setText(min) maxValueParamEdit.setText(max) meanValueParamEdit.setText(mean) stValueParamEdit.setText(stdev) if law == "UN": uniformParamRadio.setChecked(True) elif law == "NO": normalRadio.setChecked(True) elif law == "LN": logNormalRadio.setChecked(True) elif law == "LU": logUniformRadio.setChecked(True) return groupBox_8 def setConditionAction(self): """ methode qui receptionne l'evennement du clic sur "set condition" ajout d'une condition sur un paramètre ou une paire de paramètres """ param_src = self.sender().parent().findChild(QLabel,"paramNameLabel").text() # construction de la liste des params qui sont dans la même catégorie que le notre target_list = [] for pname in self.param_info_dico.keys(): if pname != param_src and self.param_info_dico[str(pname)][0] == self.param_info_dico[str(param_src)][0]: target_list.append(pname) self.setCondition = SetCondition(self.sender().parent().findChild(QLabel,"paramNameLabel").text(),target_list,self) self.setCondition.show() def majParamInfoDico(self): """ met a jour les infos des paramètres dans l'attribut param_info_dico """ # recup des valeurs pour les params for param in self.paramList: pname = str(param.findChild(QLabel,"paramNameLabel").text()) min = str(param.findChild(QLineEdit,"minValueParamEdit").text()) max = str(param.findChild(QLineEdit,"maxValueParamEdit").text()) mean = str(param.findChild(QLineEdit,"meanValueParamEdit").text()) stdev = str(param.findChild(QLineEdit,"stValueParamEdit").text()) if param.findChild(QRadioButton,'logNormalRadio').isChecked(): law = "LN" elif param.findChild(QRadioButton,'normalRadio').isChecked(): law = "NO" elif param.findChild(QRadioButton,'uniformParamRadio').isChecked(): law = "UN" elif param.findChild(QRadioButton,'logUniformRadio').isChecked(): law = "LU" visible = param.findChild(QPushButton,"setCondButton").isVisible() self.param_info_dico[pname] = [self.param_info_dico[pname][0],law,min,max,mean,stdev,visible] def addCondition(self,cond_str=""): """ ajout d'une condition dans la zone du bas réservée à cet effet """ groupBox_cond = QtGui.QGroupBox(self.ui.scrollAreaWidgetContents_3) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_cond.sizePolicy().hasHeightForWidth()) groupBox_cond.setSizePolicy(sizePolicy) groupBox_cond.setTitle("") groupBox_cond.setObjectName("groupBox_6") groupBox_cond.setMaximumSize(QtCore.QSize(100, 44)) verticalLayout_2 = QtGui.QVBoxLayout(groupBox_cond) verticalLayout_2.setObjectName("verticalLayout_2") verticalLayout_2.setContentsMargins(-1, 1, -1, 1) label_2 = QtGui.QLabel(cond_str,groupBox_cond) label_2.setObjectName("condLabel") label_2.setAlignment(QtCore.Qt.AlignCenter) label_2.setMinimumSize(QtCore.QSize(52, 11)) label_2.setMaximumSize(QtCore.QSize(52, 11)) verticalLayout_2.addWidget(label_2) pushButton_5 = QtGui.QPushButton("remove",groupBox_cond) #sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Fixed) #sizePolicy.setHorizontalStretch(0) #sizePolicy.setVerticalStretch(0) #sizePolicy.setHeightForWidth(pushButton_5.sizePolicy().hasHeightForWidth()) #pushButton_5.setSizePolicy(sizePolicy) pushButton_5.setMinimumSize(QtCore.QSize(52, 17)) pushButton_5.setMaximumSize(QtCore.QSize(52, 17)) pushButton_5.setObjectName("rmCondButton") verticalLayout_2.addWidget(pushButton_5) # ajout dans la GUI self.ui.horizontalLayout_2.addWidget(groupBox_cond) # evennement de suppression de la condition QObject.connect(pushButton_5,SIGNAL("clicked()"),self.rmCond) self.condList.append(groupBox_cond) def rmCond(self,condBox=None): """ Suppression d'une condition sur les variables dans l'affichage et dans la liste locale """ if condBox == None: condBox = self.sender().parent() condBox.hide() self.condList.remove(condBox) def checkAll(self): """ verification de la coherence des valeurs du modèle historique """ # pour tous les params, min<=max, tout>0 problems = "" for param in self.paramList: pname = str(param.findChild(QLabel,"paramNameLabel").text()) try: min = float(param.findChild(QLineEdit,"minValueParamEdit").text()) max = float(param.findChild(QLineEdit,"maxValueParamEdit").text()) mean = float(param.findChild(QLineEdit,"meanValueParamEdit").text()) stdev = float(param.findChild(QLineEdit,"stValueParamEdit").text()) #step = float(param.findChild(QLineEdit,"stepValueParamEdit").text()) if min > max or min < 0 or max < 0 or mean < 0 or stdev < 0: problems += "Values for parameter %s are incoherent\n"%pname except Exception as e: problems += "%s\n"%e if problems == "": return True else: QMessageBox.information(self,"Value error","%s"%problems) return False def getNextWidgetSnp(self): """ méthode appelée par ping pong """ if self.analysis.category == "bias": #next_title = "bias and precision" return SetupEstimationBias(self.analysis,self.parent) else: #next_title = "evaluate confidence" return SetupComparisonConfidence(self.analysis,self.parent) def getNextWidgetMsatSeq(self): """ méthode appelée par ping pong """ return SetGeneticDataAnalysis(self.analysis,self.parent.parent) def validate(self): """ validation du historical model, nous n'avons ici que les valeurs à vérifier """ if self.checkAll(): self.majParamInfoDico() self.analysis.histParamsDrawn = self.param_info_dico lCond = [] for cb in self.condList: lCond.append(str(cb.findChild(QLabel,"condLabel").text())) self.analysis.condTxtList = lCond # appel ping pong next_widget = self.parents.getNextWidget(self) self.ui.parents.analysisStack.addWidget(next_widget) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentWidget(next_widget) self.parents.updateDoc(next_widget) def exit(self): ## reactivation des onglets #self.parent.parent.setTabEnabled(1,True) #self.parent.parent.setTabEnabled(0,True) #self.parent.parent.removeTab(self.parent.parent.indexOf(self)) #self.parent.parent.setCurrentIndex(1) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentIndex(0) def getNbParam(self): return len(self.paramList)
class GenericScenarioSelection(formGenericScenarioSelection,baseGenericScenarioSelection): """ Sélection du scenario dans la cadre d'une analyse de type comparison ou estimate """ def __init__(self,nb_sc,label,next_widget,next_title,nb_min_sel,analysis,parent): super(GenericScenarioSelection,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.nb_sc = nb_sc self.nb_min_sel = nb_min_sel self.next_widget = next_widget self.next_title = next_title self.checklist = [] self.createWidgets() self.ui.selectionLabel.setText(label) self.ui.analysisTypeLabel.setText(self.next_title) self.ui.projectDirEdit.setText(self.parents.dir) self.putChoices() self.ui.verticalLayout_3.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_3.setAlignment(Qt.AlignTop) self.ui.verticalLayout_2.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_2.setAlignment(Qt.AlignTop) self.ui.verticalLayout.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout.setAlignment(Qt.AlignTop) self.restoreAnalysisValues() def createWidgets(self): self.ui=self self.ui.setupUi(self) QObject.connect(self.ui.exitButton,SIGNAL("clicked()"),self.exit) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.validate) self.ui.analysisNameLabel.setText(self.analysis.name) def restoreAnalysisValues(self): """ Si on est en edition d'analyse, elle possède déjà des valeurs que l'on doit afficher """ if self.analysis.candidateScList != []: for i,ch in enumerate(self.checklist): ch.setChecked((i+1) in self.analysis.candidateScList) def validate(self): """ passe à l'étape suivante de définition de l'analyse """ if len(self.getListSelectedScenarios()) >= self.nb_min_sel: self.analysis.candidateScList = self.getListSelectedScenarios() self.next_widget.setScenarios(self.analysis.candidateScList) analysis_in_edition = (self.analysis.computationParameters != "") if self.analysis.category == "compare" and not analysis_in_edition: self.next_widget.setRecordValues(self.analysis.candidateScList) self.ui.parents.analysisStack.addWidget(self.next_widget) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentWidget(self.next_widget) self.parents.updateDoc(self.next_widget) else: QMessageBox.information(self,"Selection error","At least %s scenarios have to be selected"%self.nb_min_sel) def getListSelectedScenarios(self): """ retourne la liste des scenarios choisis """ res = [] for i,ch in enumerate(self.checklist): if ch.isChecked(): res.append(i+1) return res 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() def exit(self): # reactivation des onglets self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentIndex(0)
def __init__(self,parent,analysis): super(ViewAnalysisParameters,self).__init__(parent) self.parent = parent self.analysis = analysis self.parents = Parents(self.parent) self.createWidgets()
class HistFixed(formHistModelFixed,baseHistModelFixed): """ définition du modèle historique dans le cadre d'une analyse les valeurs sont fixées """ def __init__(self,analysis,parent=None): super(HistFixed,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.sc_to_show = self.analysis.chosenSc self.list_selected_evaluate_sc = self.analysis.candidateScList self.paramList = [] self.condList = [] self.param_info_dico = {} self.createWidgets() self.addTheSc() self.addTheParams() self.restoreAnalysisValues() def createWidgets(self): self.ui=self self.ui.setupUi(self) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.validate) QObject.connect(self.ui.exitButton,SIGNAL("clicked()"),self.exit) self.ui.clearButton.hide() self.ui.frame_3.hide() self.ui.frame_2.hide() self.ui.scrollArea_3.hide() self.ui.defPrButton.hide() self.ui.chkScButton.hide() self.ui.addScButton.hide() self.ui.groupBox_12.hide() self.ui.maxLabel.hide() self.ui.meanLabel.hide() # self.ui.label_11.hide() self.ui.stdevLabel.hide() self.ui.minLabel.setText("Value") self.ui.drawPreviewsCheck.hide() self.ui.refreshPreviewsButton.hide() self.ui.groupBox_13.setMinimumSize(QtCore.QSize(150, 20)) self.ui.groupBox_13.setMaximumSize(QtCore.QSize(150,20)) self.ui.verticalLayout_6.setAlignment(QtCore.Qt.AlignTop) self.ui.horizontalLayout_5.setAlignment(QtCore.Qt.AlignLeft) self.ui.horizontalLayout_6.setAlignment(QtCore.Qt.AlignLeft) self.ui.horizontalLayout_2.setAlignment(QtCore.Qt.AlignLeft) self.ui.horizontalLayout_3.setAlignment(QtCore.Qt.AlignLeft) self.ui.analysisNameLabel.setText(self.analysis.name) def restoreAnalysisValues(self): if self.analysis.histParamsFixed != None: for p in self.analysis.histParamsFixed.keys(): for param in self.paramList: pname = str(param.findChild(QLabel,"paramNameLabel").text()) if pname == p: param.findChild(QLineEdit,"meanValueParamEdit").setText(self.analysis.histParamsFixed[p][1]) def addTheSc(self): # creation de la groupbox a ajouter groupBox = QtGui.QGroupBox(self.ui.scScrollContent) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox.sizePolicy().hasHeightForWidth()) groupBox.setSizePolicy(sizePolicy) groupBox.setObjectName("groupBox_"+str(self.sc_to_show)) verticalLayout_6 = QtGui.QVBoxLayout(groupBox) verticalLayout_6.setObjectName("verticalLayout_6") horizontalLayout_6 = QtGui.QHBoxLayout() horizontalLayout_6.setObjectName("horizontalLayout_6") label_3 = QtGui.QLabel("scenario %i"%self.sc_to_show,groupBox) # ne mettre qu'un seul label du nom scLabel pour pouvoir le retrouver avec findChild() label_3.setObjectName("scLabel") horizontalLayout_6.addWidget(label_3) verticalLayout_6.addLayout(horizontalLayout_6) plainTextEdit = QtGui.QPlainTextEdit(groupBox) plainTextEdit.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap) plainTextEdit.setObjectName("scplainTextEdit") verticalLayout_6.addWidget(plainTextEdit) # ajout de la groupbox self.ui.horizontalLayout_3.addWidget(groupBox) # recup du texte du scenario plainTextEdit.setPlainText(self.getScText()) plainTextEdit.setReadOnly(True) def getScText(self): """ récupère le texte du scenario concerné dans le modèle historique de la reftable """ return self.parents.hist_model_win.scList[self.sc_to_show-1].findChild(QPlainTextEdit,"scplainTextEdit").toPlainText() def addTheParams(self): """ trouve et ajoute les paramètres du scenario concerné """ try: sc = str(self.getScText()) scChecker = Scenario(number=self.sc_to_show) scChecker.checkread(sc.strip().split('\n'),self.parents.data) scChecker.checklogic() dico_sc_infos = {} dico_sc_infos["text"] = sc.strip().split('\n') dico_sc_infos["checker"] = scChecker #print "nb param du sc ",num," ",scChecker.nparamtot except Exception as e: output.notify(str(e)) self.exit() return visible = False dico_param = self.parents.hist_model_win.param_info_dico for param in scChecker.parameters: pname = param.name pcat = param.category elem = dico_param[pname] val = (float(elem[2]) + float(elem[3])) / 2 self.addParamGui(pname,str(val),visible) self.param_info_dico[pname] = [pcat] def addParamGui(self,name,val,visible): """ ajoute un paramètre à la GUI et à la liste locale de paramètres et retourne la groupBox créée """ groupBox_8 = QtGui.QFrame(self.ui.scrollArea) #groupBox_8.setFrameShape(QtGui.QFrame.StyledPanel) #groupBox_8.setFrameShadow(QtGui.QFrame.Raised) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_8.sizePolicy().hasHeightForWidth()) groupBox_8.setSizePolicy(sizePolicy) groupBox_8.setMinimumSize(QtCore.QSize(0, 26)) groupBox_8.setMaximumSize(QtCore.QSize(16777215, 26)) groupBox_8.setObjectName("groupBox_8") horizontalLayout_13 = QtGui.QHBoxLayout(groupBox_8) horizontalLayout_13.setAlignment(QtCore.Qt.AlignLeft) horizontalLayout_13.setObjectName("horizontalLayout_13") horizontalLayout_13.setContentsMargins(-1, 1, -1, 1) groupBox_9 = QtGui.QGroupBox(groupBox_8) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_9.sizePolicy().hasHeightForWidth()) groupBox_9.setSizePolicy(sizePolicy) groupBox_9.setMinimumSize(QtCore.QSize(140, 25)) groupBox_9.setMaximumSize(QtCore.QSize(140, 25)) groupBox_9.setObjectName("groupBox_9") horizontalLayout_8 = QtGui.QHBoxLayout(groupBox_9) horizontalLayout_8.setObjectName("horizontalLayout_8") horizontalLayout_8.setContentsMargins(-1, 1, -1, 1) paramNameLabel = QtGui.QLabel(name,groupBox_9) paramNameLabel.setObjectName("paramNameLabel") horizontalLayout_8.addWidget(paramNameLabel) setCondButton = QtGui.QPushButton("set condition",groupBox_9) setCondButton.setObjectName("setCondButton") setCondButton.setMinimumSize(QtCore.QSize(80, 20)) setCondButton.setMaximumSize(QtCore.QSize(80, 20)) if not visible: setCondButton.hide() else: QObject.connect(setCondButton,SIGNAL("clicked()"),self.setConditionAction) if "darwin" in sys.platform: ff = setCondButton.font() ff.setPointSize(10) setCondButton.setFont(ff) else: ff = setCondButton.font() ff.setPointSize(8) setCondButton.setFont(ff) horizontalLayout_8.addWidget(setCondButton) horizontalLayout_13.addWidget(groupBox_9) groupBox_14 = QtGui.QGroupBox(groupBox_8) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(groupBox_14.sizePolicy().hasHeightForWidth()) groupBox_14.setSizePolicy(sizePolicy) groupBox_14.setMinimumSize(QtCore.QSize(150, 25)) groupBox_14.setMaximumSize(QtCore.QSize(150,25)) groupBox_14.setObjectName("groupBox_14") horizontalLayout_10 = QtGui.QHBoxLayout(groupBox_14) horizontalLayout_10.setObjectName("horizontalLayout_10") horizontalLayout_10.setContentsMargins(-1, 1, -1, 1) meanValueParamEdit = QtGui.QLineEdit(groupBox_14) meanValueParamEdit.setMinimumSize(QtCore.QSize(60, 0)) meanValueParamEdit.setMaximumSize(QtCore.QSize(60, 16777215)) meanValueParamEdit.setObjectName("meanValueParamEdit") horizontalLayout_10.addWidget(meanValueParamEdit) horizontalLayout_13.addWidget(groupBox_14) self.ui.verticalLayout_6.addWidget(groupBox_8) # liste locale des paramètres self.paramList.append(groupBox_8) meanValueParamEdit.setText(val) return groupBox_8 def majParamInfoDico(self): """ met a jour les infos des paramètres dans l'attribut param_info_dico """ # recup des valeurs pour les params for param in self.paramList: pname = str(param.findChild(QLabel,"paramNameLabel").text()) val = str(param.findChild(QLineEdit,"meanValueParamEdit").text()) self.param_info_dico[pname] = [self.param_info_dico[pname][0],val] def checkAll(self): """ verification de la coherence des valeurs du modèle historique. Vérification des conditions. """ problems = "" conditions = defaultdict(set) for cond in self.parents.findChildren(QtGui.QLabel, "condLabel") : condText = str(cond.text()).strip() for b in ['<=','<','>=','>'] : if b in condText : a,c = condText.split(b) conditions[a].add((b,c)) break paramValues = {} for param in self.paramList: pname = str(param.findChild(QLabel,"paramNameLabel").text()) try: value = float(param.findChild(QLineEdit,"meanValueParamEdit").text()) paramValues[pname] = value if value < 0: problems += "Values for parameter %s are incoherent.\n"%pname except Exception as e: problems += "%s.\n"%e for pname in paramValues.keys() : for condition in conditions[pname] : if not eval("{0} {1} {2}".format(paramValues[pname], condition[0], paramValues[condition[1]])) : problems += "Parameter {0} ({1}) must be {2} to parameter {3} ({4}).\n".format(pname, paramValues[pname], condition[0], condition[1], paramValues[condition[1]]) if problems == "": return True else: QMessageBox.information(self,"Value error","%s"%problems) return False def getNextWidgetSnp(self): """ methode appelée par ping pong """ if self.analysis.category == "bias": #next_title = "bias and precision" return SetupEstimationBias(self.analysis,self.parent) else: #next_title = "evaluate confidence" return SetupComparisonConfidence(self.analysis,self.parent) def getNextWidgetMsatSeq(self): """ methode appelée par ping pong """ return SetGeneticDataAnalysis(self.analysis,self.parent.parent) def validate(self): """ on vérifie ici que les valeurs sont bien des float et qu'elles sont bien supérieures à 0 """ if self.checkAll(): self.majParamInfoDico() self.analysis.histParamsFixed = self.param_info_dico # appel ping pong next_widget = self.parents.getNextWidget(self) self.ui.parents.analysisStack.addWidget(next_widget) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentWidget(next_widget) self.parents.updateDoc(next_widget) def exit(self): ## reactivation des onglets #self.parent.parent.setTabEnabled(1,True) #self.parent.parent.setTabEnabled(0,True) #self.parent.parent.removeTab(self.parent.parent.indexOf(self)) #self.parent.parent.setCurrentIndex(1) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentIndex(0) def getNbParam(self): return len(self.paramList)
class ConfidenceTypeSelection(formConfidenceTypeSelection,baseConfidenceTypeSelection): """ Selection du scenario dans la cadre d'une analyse de type bias ou confidence """ def __init__(self,nb_sc,analysis,parent=None): super(ConfidenceTypeSelection,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.nb_sc = nb_sc self.createWidgets() self.restoreAnalysisValues() def createWidgets(self): self.ui=self self.ui.setupUi(self) QObject.connect(self.ui.exitButton,SIGNAL("clicked()"),self.exit) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.validate) QObject.connect(self.ui.posteriorConfidenceButton,SIGNAL("clicked()"),self.checkParameterValues) QObject.connect(self.ui.priorConfidenceButton,SIGNAL("clicked()"),self.checkParameterValues) QObject.connect(self.ui.priorGlobalConfidenceButton,SIGNAL("clicked()"),self.checkParameterValues) QObject.connect(self.ui.priorSpecificConfidenceButton,SIGNAL("clicked()"),self.checkParameterValues) if "confidence" in self.analysis.category : pass #self.ui.analysisTypeLabel.setText("Type based confidence") else : log(1,"Should found a confidence scenario but found : " % self.analysis.category) raise Exception("Should found a confidence scenario but found : " % self.analysis.category) self.ui.projectDirEdit.setText(self.parents.dir) self.ui.analysisNameLabel.setText(self.analysis.name) self.checkParameterValues() def restoreAnalysisValues(self): if self.analysis.category == "confidence_posterior_global": self.ui.posteriorConfidenceButton.setChecked(True) else : if self.analysis.category == "confidence_prior_global": self.ui.priorConfidenceButton.setChecked(True) self.ui.priorGlobalConfidenceButton.setChecked(True) elif self.analysis.category == "confidence_prior_specific" or \ (self.analysis.category == "confidence" and len(self.analysis.computationParameters) > 1) : self.ui.priorConfidenceButton.setChecked(True) self.ui.priorSpecificConfidenceButton.setChecked(True) self.checkParameterValues(reset=False) def checkParameterValues(self, reset=True): self.ui.priorTypeFrame.hide() if self.ui.posteriorConfidenceButton.isChecked() : self.ui.priorGlobalConfidenceButton.setChecked(False) self.ui.priorSpecificConfidenceButton.setChecked(False) if self.ui.priorConfidenceButton.isChecked() : self.ui.priorTypeFrame.show() def validate(self): """ passe à l'étape suivante de la définition de l'analyse """ next_widget = False if self.ui.posteriorConfidenceButton.isChecked() : self.analysis.category = "confidence_posterior_global" next_widget = SetupComparisonConfidence(analysis=self.analysis, parent=self) elif self.ui.priorConfidenceButton.isChecked() : if self.ui.priorGlobalConfidenceButton.isChecked() : self.analysis.category = "confidence_prior_global" next_widget = SetupComparisonConfidence(analysis=self.analysis, parent=self) elif self.ui.priorSpecificConfidenceButton.isChecked() : self.analysis.category = "confidence_prior_specific" next_widget = BiasNConfidenceScenarioSelection(len(self.parents.hist_model_win.scList),self.analysis,self) else : QMessageBox.information(self,"No prior selection error","You must choose a prior type : GLOBAL or SCENARIO SPECIFIC.") return 0 else : QMessageBox.information(self,"No type based selection error","You must choose a type based confidence : Posterior or Prior.") return 0 self.ui.parents.analysisStack.addWidget(next_widget) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentWidget(next_widget) # skip group loci selection for microsat and seqs analysis self.parents.updateDoc(next_widget) def exit(self): ## reactivation des onglets self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentIndex(0)
def __init__(self,analysis,parent=None): super(SetGeneticDataAnalysis,self).__init__(parent) self.parent = parent self.parents = Parents(self.parent) self.analysis = analysis self.fsCoding = getFsEncoding(logLevel=False) self.analysisFrame.show() self.analysisNameLabel.setText(self.analysis.name) self.ui.addGroupButton.hide() self.ui.autoGroupButton.hide() self.ui.clearButton.hide() self.fillLocusTableFromData() gen_data_ref = self.parents.gen_data_win # copie des valeurs de range et size for locusrow in range(gen_data_ref.ui.tableWidget.rowCount()): self.ui.tableWidget.setItem(locusrow,2,QTableWidgetItem("%s"%gen_data_ref.ui.tableWidget.item(locusrow,2).text())) self.ui.tableWidget.setItem(locusrow,3,QTableWidgetItem("%s"%gen_data_ref.ui.tableWidget.item(locusrow,3).text())) # remplissage des groupes et set des mutation model et sum stats ac valeurs for numgr,box in enumerate(gen_data_ref.groupList): title = gen_data_ref.group_info_dico[box][0] locus_list = gen_data_ref.group_info_dico[box][1] self.addGroup() self.groupList[-1].setTitle("Group %s : %s"%(len(self.groupList),title)) self.groupList[-1].findChild(QPushButton,"rmLocusGroupButton").hide() # selection pour ajouter dans le groupe for locus in locus_list: #index = gen_data_ref.dico_num_and_numgroup_locus[locus] self.ui.tableWidget.setItemSelected(self.ui.tableWidget.item(locus-1,0),True) self.addToGroup(self.groupList[-1]) # creation des objets mutation model if self.analysis.drawn : # on instancie des mutationmodel normaux (mais fait pour analysis) if "Microsatellites" in str(box.title()): self.setMutation_dico[self.groupList[-1]] = SetMutationModelMsatAnalysis(self,self.groupList[-1]) self.setMutation_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutation_dico[box].getMutationConf() if self.analysis.mutationModelDrawn != "": self.setMutation_dico[self.groupList[-1]].setMutationConf(self.analysis.mutationModelDrawn[numgr].split('\n')) else: self.setMutation_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutation_dico[box].getMutationConf().split('\n')) # on grise ce qui ne varie pas self.setMutation_dico[self.groupList[-1]].hideFixedParameters() self.setMutationValid_dico[self.groupList[-1]] = True elif "Sequences" in str(box.title()): self.setMutationSeq_dico[self.groupList[-1]] = SetMutationModelSequencesAnalysis(self,self.groupList[-1]) self.setMutationSeq_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutationSeq_dico[box].getMutationConf() if self.analysis.mutationModelDrawn != "": self.setMutationSeq_dico[self.groupList[-1]].setMutationConf(self.analysis.mutationModelDrawn[numgr].split('\n')) else: self.setMutationSeq_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutationSeq_dico[box].getMutationConf().split('\n')) # on grise ce qui ne varie pas self.setMutationSeq_dico[self.groupList[-1]].hideFixedParameters() self.setMutationSeqValid_dico[self.groupList[-1]] = True else: # on instancie des mutationmodel fixed if "Microsatellites" in str(box.title()): self.setMutation_dico[self.groupList[-1]] = SetMutationModelMsatFixed(self,self.groupList[-1]) self.setMutation_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutation_dico[box].getMutationConf() if self.analysis.mutationModelFixed != "": self.setMutation_dico[self.groupList[-1]].setMutationConfFromAnalysisValues(self.analysis.mutationModelFixed[numgr]) else: self.setMutation_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutation_dico[box].getMutationConf().split('\n')) self.setMutationValid_dico[self.groupList[-1]] = True # on grise ce qui ne varie pas if float(str(gen_data_ref.setMutation_dico[box].mmrMinEdit.text())) == float(str(gen_data_ref.setMutation_dico[box].mmrMaxEdit.text())): self.setMutation_dico[self.groupList[-1]].mmrFrame.setDisabled(True) if float(str(gen_data_ref.setMutation_dico[box].mcpMinEdit.text())) == float(str(gen_data_ref.setMutation_dico[box].mcpMaxEdit.text())): self.setMutation_dico[self.groupList[-1]].mcpFrame.setDisabled(True) if float(str(gen_data_ref.setMutation_dico[box].msrMinEdit.text())) == float(str(gen_data_ref.setMutation_dico[box].msrMaxEdit.text())): self.setMutation_dico[self.groupList[-1]].msrFrame.setDisabled(True) elif "Sequences" in str(box.title()): self.setMutationSeq_dico[self.groupList[-1]] = SetMutationModelSequencesFixed(self,self.groupList[-1]) self.setMutationSeq_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutationSeq_dico[box].getMutationConf() if self.analysis.mutationModelFixed != "": self.setMutationSeq_dico[self.groupList[-1]].setMutationConfFromAnalysisValues(self.analysis.mutationModelFixed[numgr]) else: self.setMutationSeq_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutationSeq_dico[box].getMutationConf().split('\n')) self.setMutationSeqValid_dico[self.groupList[-1]] = True # on grise ce qui ne varie pas if float(str(gen_data_ref.setMutationSeq_dico[box].mmrMinEdit.text())) == float(str(gen_data_ref.setMutationSeq_dico[box].mmrMaxEdit.text())): self.setMutationSeq_dico[self.groupList[-1]].mmrFrame.setDisabled(True) if float(str(gen_data_ref.setMutationSeq_dico[box].mc1MinEdit.text())) == float(str(gen_data_ref.setMutationSeq_dico[box].mc1MaxEdit.text())): self.setMutationSeq_dico[self.groupList[-1]].mc1Frame.setDisabled(True) if float(str(gen_data_ref.setMutationSeq_dico[box].mc2MinEdit.text())) == float(str(gen_data_ref.setMutationSeq_dico[box].mc2MaxEdit.text())): self.setMutationSeq_dico[self.groupList[-1]].mc2Frame.setDisabled(True) for box in self.groupList: box.findChild(QPushButton,"addToGroupButton").hide() box.findChild(QPushButton,"rmFromGroupButton").hide() box.findChild(QPushButton,"setSumButton").hide()
class SetGeneticDataAnalysis(SetGeneticData): """ set genetic data pour les informations concernant une analyse bias ou confidence """ def __init__(self,analysis,parent=None): super(SetGeneticDataAnalysis,self).__init__(parent) self.parent = parent self.parents = Parents(self.parent) self.analysis = analysis self.fsCoding = getFsEncoding(logLevel=False) self.analysisFrame.show() self.analysisNameLabel.setText(self.analysis.name) self.ui.addGroupButton.hide() self.ui.autoGroupButton.hide() self.ui.clearButton.hide() self.fillLocusTableFromData() gen_data_ref = self.parents.gen_data_win # copie des valeurs de range et size for locusrow in range(gen_data_ref.ui.tableWidget.rowCount()): self.ui.tableWidget.setItem(locusrow,2,QTableWidgetItem("%s"%gen_data_ref.ui.tableWidget.item(locusrow,2).text())) self.ui.tableWidget.setItem(locusrow,3,QTableWidgetItem("%s"%gen_data_ref.ui.tableWidget.item(locusrow,3).text())) # remplissage des groupes et set des mutation model et sum stats ac valeurs for numgr,box in enumerate(gen_data_ref.groupList): title = gen_data_ref.group_info_dico[box][0] locus_list = gen_data_ref.group_info_dico[box][1] self.addGroup() self.groupList[-1].setTitle("Group %s : %s"%(len(self.groupList),title)) self.groupList[-1].findChild(QPushButton,"rmLocusGroupButton").hide() # selection pour ajouter dans le groupe for locus in locus_list: #index = gen_data_ref.dico_num_and_numgroup_locus[locus] self.ui.tableWidget.setItemSelected(self.ui.tableWidget.item(locus-1,0),True) self.addToGroup(self.groupList[-1]) # creation des objets mutation model if self.analysis.drawn : # on instancie des mutationmodel normaux (mais fait pour analysis) if "Microsatellites" in str(box.title()): self.setMutation_dico[self.groupList[-1]] = SetMutationModelMsatAnalysis(self,self.groupList[-1]) self.setMutation_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutation_dico[box].getMutationConf() if self.analysis.mutationModelDrawn != "": self.setMutation_dico[self.groupList[-1]].setMutationConf(self.analysis.mutationModelDrawn[numgr].split('\n')) else: self.setMutation_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutation_dico[box].getMutationConf().split('\n')) # on grise ce qui ne varie pas self.setMutation_dico[self.groupList[-1]].hideFixedParameters() self.setMutationValid_dico[self.groupList[-1]] = True elif "Sequences" in str(box.title()): self.setMutationSeq_dico[self.groupList[-1]] = SetMutationModelSequencesAnalysis(self,self.groupList[-1]) self.setMutationSeq_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutationSeq_dico[box].getMutationConf() if self.analysis.mutationModelDrawn != "": self.setMutationSeq_dico[self.groupList[-1]].setMutationConf(self.analysis.mutationModelDrawn[numgr].split('\n')) else: self.setMutationSeq_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutationSeq_dico[box].getMutationConf().split('\n')) # on grise ce qui ne varie pas self.setMutationSeq_dico[self.groupList[-1]].hideFixedParameters() self.setMutationSeqValid_dico[self.groupList[-1]] = True else: # on instancie des mutationmodel fixed if "Microsatellites" in str(box.title()): self.setMutation_dico[self.groupList[-1]] = SetMutationModelMsatFixed(self,self.groupList[-1]) self.setMutation_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutation_dico[box].getMutationConf() if self.analysis.mutationModelFixed != "": self.setMutation_dico[self.groupList[-1]].setMutationConfFromAnalysisValues(self.analysis.mutationModelFixed[numgr]) else: self.setMutation_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutation_dico[box].getMutationConf().split('\n')) self.setMutationValid_dico[self.groupList[-1]] = True # on grise ce qui ne varie pas if float(str(gen_data_ref.setMutation_dico[box].mmrMinEdit.text())) == float(str(gen_data_ref.setMutation_dico[box].mmrMaxEdit.text())): self.setMutation_dico[self.groupList[-1]].mmrFrame.setDisabled(True) if float(str(gen_data_ref.setMutation_dico[box].mcpMinEdit.text())) == float(str(gen_data_ref.setMutation_dico[box].mcpMaxEdit.text())): self.setMutation_dico[self.groupList[-1]].mcpFrame.setDisabled(True) if float(str(gen_data_ref.setMutation_dico[box].msrMinEdit.text())) == float(str(gen_data_ref.setMutation_dico[box].msrMaxEdit.text())): self.setMutation_dico[self.groupList[-1]].msrFrame.setDisabled(True) elif "Sequences" in str(box.title()): self.setMutationSeq_dico[self.groupList[-1]] = SetMutationModelSequencesFixed(self,self.groupList[-1]) self.setMutationSeq_dico[self.groupList[-1]].hide() # on transfere la conf depuis le mutmod reftable #print "mut conf : %s"%gen_data_ref.setMutationSeq_dico[box].getMutationConf() if self.analysis.mutationModelFixed != "": self.setMutationSeq_dico[self.groupList[-1]].setMutationConfFromAnalysisValues(self.analysis.mutationModelFixed[numgr]) else: self.setMutationSeq_dico[self.groupList[-1]].setMutationConf(gen_data_ref.setMutationSeq_dico[box].getMutationConf().split('\n')) self.setMutationSeqValid_dico[self.groupList[-1]] = True # on grise ce qui ne varie pas if float(str(gen_data_ref.setMutationSeq_dico[box].mmrMinEdit.text())) == float(str(gen_data_ref.setMutationSeq_dico[box].mmrMaxEdit.text())): self.setMutationSeq_dico[self.groupList[-1]].mmrFrame.setDisabled(True) if float(str(gen_data_ref.setMutationSeq_dico[box].mc1MinEdit.text())) == float(str(gen_data_ref.setMutationSeq_dico[box].mc1MaxEdit.text())): self.setMutationSeq_dico[self.groupList[-1]].mc1Frame.setDisabled(True) if float(str(gen_data_ref.setMutationSeq_dico[box].mc2MinEdit.text())) == float(str(gen_data_ref.setMutationSeq_dico[box].mc2MaxEdit.text())): self.setMutationSeq_dico[self.groupList[-1]].mc2Frame.setDisabled(True) for box in self.groupList: box.findChild(QPushButton,"addToGroupButton").hide() box.findChild(QPushButton,"rmFromGroupButton").hide() box.findChild(QPushButton,"setSumButton").hide() def majProjectGui(self,m=None,s=None,g=None,ss=None): pass # if m != None: # self.parent.ui.nbMicrosatLabel.setText("%s microsatellite loci"%m) # if s != None: # self.parent.ui.nbSequencesLabel.setText("%s DNA sequence loci"%s) # if g != None: # self.parent.ui.nbGroupLabel.setText("%s locus groups"%g) # if ss != None: # self.parent.ui.nbSumStatsLabel.setText("%s summary statistics"%ss) def setSum(self,box=None): """ déclenché par le clic sur le bouton 'set summary statistics' ou par le clic sur 'clear' dans 'set summary statistics'. bascule vers la saisie des summary statistics """ if box == None: box = self.sender().parent() title = str(box.title()) if "Microsatellites" in title: #self.parent.addTab(self.setSum_dico[box],"Set summary statistics") #self.parent.setTabEnabled(self.parent.indexOf(self),False) #self.parent.setCurrentWidget(self.setSum_dico[box]) self.switchTo(self.setSum_dico[box]) # maj du titre de la frame lab = self.setSum_dico[box].ui.sumStatLabel lab.setText("Set summary statistics of %s (microsatellites)"%(" ".join(str(box.title()).split()[:2]))) elif "Sequences" in title: #self.parent.addTab(self.setSumSeq_dico[box],"Set summary statistics") #self.parent.setTabEnabled(self.parent.indexOf(self),False) #self.parent.setCurrentWidget(self.setSumSeq_dico[box]) self.switchTo(self.setSumSeq_dico[box]) # maj du titre de la frame lab = self.setSumSeq_dico[box].ui.sumStatLabel lab.setText("Set summary statistics of %s (sequences)"%(" ".join(str(box.title()).split()[:2]))) else: QMessageBox.information(self,"Set Summary statistics error","Add locus to a group before setting the summary statistics") def switchTo(self,widget): """ on switche dans la stack analysis """ self.ui.parents.analysisStack.addWidget(widget) self.ui.parents.analysisStack.setCurrentWidget(widget) def exit(self): ## reactivation des onglets #self.parent.setTabEnabled(0,True) #self.parent.setTabEnabled(1,True) #self.parent.removeTab(self.parent.indexOf(self)) #self.parent.setCurrentIndex(1) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentIndex(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) #self.parent.addAnalysis(self.analysis) #self.exit() def clear(self): """ On supprime tous les groupes """ #for i in range(len(self.groupList)): # self.groupList[i].hide() for box in self.groupList: box.hide() lw = box.findChild(QListWidget,"locusGroupList") for row in range(lw.count()): name = str(lw.item(row).text()) #num = int(name.split(' ')[1]) num = self.dico_num_and_numgroup_locus[name][0] # on decouvre la ligne self.ui.tableWidget.setRowHidden(num-1,False) self.groupList = [] def writeGeneticConfFromGui(self): """ on ecrit l'etat actuel des genetic data dans conf.gen.tmp """ if os.path.exists((u"%s/%s"%(self.parents.dir,self.parents.gen_conf_name)).encode(self.fsCoding)): os.remove((u"%s/%s"%(self.parents.dir,self.parents.gen_conf_name)).encode(self.fsCoding)) f = codecs.open((u"%s/%s"%(self.parents.dir,self.parents.gen_conf_name)).encode(self.fsCoding),'w',"utf-8") # partie description des locus f.write("loci description (%i)\n"%self.nbLocusGui) data = self.parents.data for i in range(data.nloc): name = data.locuslist[i].name type = data.locuslist[i].type group = self.dico_num_and_numgroup_locus[name][1] if type > 4: microSeq = "S" typestr = LOC_TYP[type-5] length = data.locuslist[i].dnalength f.write("%s %s [%s] G%i %s\n"%(name.replace(' ','_'),typestr,microSeq,group,length)) else: microSeq = "M" typestr = LOC_TYP[type] indice_dans_table = self.dico_num_and_numgroup_locus[name][0] motif_size = str(self.ui.tableWidget.item(indice_dans_table-1,2).text()) motif_range = str(self.ui.tableWidget.item(indice_dans_table-1,3).text()).strip() f.write("%s %s [%s] G%i %s %s\n"%(name.replace(' ','_'),typestr,microSeq,group,motif_size,motif_range)) # partie mutation model f.write("\ngroup priors (%i)\n"%len(self.groupList)) if len(self.groupList) == 0: f.write("\n") else: for i,box in enumerate(self.groupList): if "Microsatellites" in str(box.title()): f.write("group G%i [M]\n"%(i+1)) f.write(u'%s'%self.setMutation_dico[box].getMutationConf()) elif "Sequences" in str(box.title()): f.write("group G%i [S]\n"%(i+1)) to_write = u'%s'%self.setMutationSeq_dico[box].getMutationConf() f.write(to_write) # partie sum stats stat_txt_list = [] nstat_tot = 0 for i,box in enumerate(self.groupList): stat_txt = "" if "Microsatellites" in str(box.title()): (nstat_tmp,stat_txt) = self.setSum_dico[box].getSumConf() stat_header_txt = "group G%i [M] (%i)\n"%((i+1),nstat_tmp) nstat_tot += nstat_tmp # construction de la chaine a ecrire pour ce groupe stat_to_write = stat_header_txt+stat_txt elif "Sequences" in str(box.title()): (nstat_tmp,stat_txt) = self.setSumSeq_dico[box].getSumConf() stat_header_txt = "group G%i [S] (%i)\n"%((i+1),nstat_tmp) nstat_tot += nstat_tmp # construction de la chaine a ecrire pour ce groupe stat_to_write = stat_header_txt+stat_txt stat_txt_list.append(stat_to_write) f.write("group summary statistics (%i)\n"%nstat_tot) for txt in stat_txt_list: f.write(txt) #print txt f.write('\n') def loadGeneticConf(self): """ Charge le fichier conf.gen.tmp """ # de toute façon, on rempli le tableau de locus #self.fillLocusTableFromData() if os.path.exists(str(self.parents.dir).encode(self.fsCoding)): if os.path.exists((u"%s/%s"%(self.parents.dir,self.parents.gen_conf_name)).encode(self.fsCoding)): f = codecs.open((u"%s/%s"%(self.parents.dir,self.parents.gen_conf_name)).encode(self.fsCoding),"rU","utf-8") lines = f.readlines() nloc = int(lines[0].split('(')[1].split(')')[0]) # determination du nombre de groupes l = 1 gmax = 0 while l < nloc+1: g = int(lines[l].split()[3].replace('G','')) if g > gmax: gmax = g l+=1 # creation du bon nombre de groupes for it in range(gmax): self.addGroup() # recup des infos de chaque locus l = 1 while l < nloc+1: lname = lines[l].split()[0].replace('_',' ') #ltype = lines[l].split(' ')[1] #ltype_num = LOC_TYP.index(ltype) lmicroSeq = lines[l].split('[')[1].split(']')[0] num_group = int(lines[l].split()[3].replace('G','')) # maj du dico self.dico_num_and_numgroup_locus[lname] = [l,num_group] if lmicroSeq == 'M': # ajout ds le groupe if num_group != 0: self.ui.tableWidget.setItemSelected(self.ui.tableWidget.item(l-1,0),True) self.addToGroup(self.groupList[num_group-1]) # maj des infos dans le table ranger = lines[l].split()[4] motif = lines[l].split()[5] self.ui.tableWidget.setItem(l-1,2,QTableWidgetItem("%s"%(ranger))) self.ui.tableWidget.setItem(l-1,3,QTableWidgetItem("%s"%(motif))) else: # ajout ds le groupe if num_group != 0: self.ui.tableWidget.setItemSelected(self.ui.tableWidget.item(l-1,0),True) self.addToGroup(self.groupList[num_group-1]) l+=1 # chargement des infos sur les groupes l+=1 if l < len(lines): #print 'ligne:',lines[l] #nb_groupes = int(lines[l].split('(')[1].split(')')[0]) #num_group_max_done = 0 l+=1 # on va jusqu'à la prochaine ligne vide ou la fin du fichier while l<len(lines) and lines[l].strip() != "": #print 'prem ligne du groupe:',lines[l] num_group = int(lines[l].split('group G')[1].split()[0]) #num_group_max_done = num_group type_group = lines[l].split('[')[1].split(']')[0] l+=1 if type_group == 'S': self.setMutationSeq_dico[self.groupList[num_group-1]].setMutationConf(lines[l:(l+7)]) l+=7 else: self.setMutation_dico[self.groupList[num_group-1]].setMutationConf(lines[l:(l+6)]) l+=6 # on avance jusqu'au summary stats while l<len(lines) and "group summary statistics" not in lines[l]: l+=1 # on est sur la première ligne #nb_sum_stat = int(lines[l].split('(')[1].split(')')[0]) #print "nbsumstat %s"%nb_sum_stat l+=1 # parcours de tous les groupes while l<len(lines) and lines[l].strip() != "": num_group = int(lines[l].split('group G')[1].split()[0]) type_group = lines[l].split('[')[1].split(']')[0] l+=1 # parcours des lignes du groupe lines_group = [] while l<len(lines) and "group" not in lines[l]: lines_group.append(lines[l].strip()) l+=1 if len(lines_group) > 0: if type_group == 'S': self.setSumSeq_dico[self.groupList[num_group-1]].setSumConf(lines_group) else: self.setSum_dico[self.groupList[num_group-1]].setSumConf(lines_group) self.majProjectGui(ss=self.getNbSumStats()) def clearMutationModel(self,box): self.setMutation_dico[box].exit() self.setMutation_dico[box] = SetMutationModelMsat(self,box) self.setMutation(box) def clearMutationModelSeq(self,box): self.setMutationSeq_dico[box].exit() self.setMutationSeq_dico[box] = SetMutationModelSequences(self,box) self.setMutation(box)
class SetupComparisonConfidence(formSetupComparisonConfidence,baseSetupComparisonConfidence): """ dernière étape de définition d'une analyse de type comparison ou confidence """ def __init__(self,analysis,parent=None): super(SetupComparisonConfidence,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.scNumList = [] self.dico_values = {} self.createWidgets() self.ui.verticalLayout_2.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_2.setAlignment(Qt.AlignTop) self.restoreAnalysisValues() self.parents.updateDoc(self) def createWidgets(self): self.ui=self self.ui.setupUi(self) self.deInterValuesW = [] self.lrInterValuesW = [] self.ui.projectNameEdit.setText(self.parents.dir) self.ui.gridLayout.setAlignment(Qt.AlignTop) self.ui.posteriorDistributionFrame.hide() QObject.connect(self.ui.exitButton,SIGNAL("clicked()"),self.exit) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.validate) QObject.connect(self.ui.redefButton,SIGNAL("clicked()"),self.redefineScenarios) QObject.connect(self.ui.numRegCombo,SIGNAL("currentIndexChanged(QString)"),self.updateInterValues) QObject.connect(self.ui.deEdit,SIGNAL("textChanged(QString)"),self.updateInterValues) QObject.connect(self.ui.lrEdit,SIGNAL("textChanged(QString)"),self.updateInterValues) QObject.connect(self.ui.posteriorDistributionSampleSizeEdit,SIGNAL("textChanged(QString)"),self.updateInterValues) QObject.connect(self.ui.logisticRegressioncheckBox,SIGNAL("stateChanged(int)"),self.updateInterValues) if "confidence" in self.analysis.category : self.ui.label.setText("Confidence in scenario choice") self.setScenarios([self.analysis.chosenSc]) self.setCandidateScenarios(self.analysis.candidateScList) self.setRecordValues(self.analysis.candidateScList) self.ui.redefButton.hide() self.ui.numRegCombo.clear() self.ui.numRegCombo.addItem("0") self.ui.numRegCombo.addItem("1") #self.ui.notdsEdit.setText("500") self.ui.intermediateValuesFrame.hide() if self.analysis.category == "confidence_posterior_global" : self.ui.posteriorDistributionFrame.show() self.ui.notdsLabel.setText(self.ui.notdsLabel.text().replace("[TO-REPLACE]", "pseudo-observed")) self.ui.scenarioProbaExplainLabel.setText(self.ui.scenarioProbaExplainLabel.text().replace("[TO-REPLACE]", "pseudo-observed")) else: # assume self.analysis.category == "compare" self.ui.logisticRegressioncheckBox.setChecked(True) self.ui.logisticRegressioncheckBox.hide() self.ui.notdsEdit.hide() self.ui.notdsLabel.hide() self.ui.candidateLabel.hide() self.setScenarios([self.analysis.chosenSc]) self.setCandidateScenarios(self.analysis.candidateScList) self.setRecordValues(self.analysis.candidateScList) self.ui.notdsLabel.setText(self.ui.notdsLabel.text().replace("[TO-REPLACE]", "observed")) self.ui.scenarioProbaExplainLabel.setText(self.ui.scenarioProbaExplainLabel.text().replace("[TO-REPLACE]", "observed")) self.ui.numRegCombo.setCurrentIndex(1) self.ui.deEdit.setText("500") self.ui.analysisNameLabel.setText(self.analysis.name) def updateInterValues(self,numstr): if self.ui.logisticRegressioncheckBox.isChecked() : self.lrEdit.setEnabled(True) if "confidence" in self.analysis.category : self.ui.numRegCombo.setCurrentIndex(self.ui.numRegCombo.findText("1")) else : self.lrEdit.setDisabled(True) if "confidence" in self.analysis.category : self.ui.numRegCombo.setCurrentIndex(self.ui.numRegCombo.findText("0")) for w in self.lrInterValuesW: w.hide() self.ui.lrValLayout.removeWidget(w) for w in self.deInterValuesW: w.hide() self.ui.deValLayout.removeWidget(w) self.lrInterValuesW = [] self.deInterValuesW = [] try: #de = int(self.ui.deEdit.text()) lr = int(self.ui.lrEdit.text()) numreg = int(self.ui.numRegCombo.currentText()) if numreg == 0: self.ui.lrValuesFrame.setDisabled(True) self.ui.lrEdit.setDisabled(True) self.analysis.logreg = False else : self.ui.lrValuesFrame.setDisabled(False) self.ui.lrEdit.setDisabled(False) self.analysis.logreg = True #dedec = de/numreg lrdec = lr/numreg for i in range(numreg): lrlab = QLabel(str(lr)) #delab = QLabel(str(de)) self.lrInterValuesW.append(lrlab) #self.deInterValuesW.append(delab) self.ui.lrValLayout.addWidget(lrlab) #self.ui.deValLayout.addWidget(delab) #de -= dedec lr -= lrdec except Exception as e: print e def restoreAnalysisValues(self): if self.analysis.computationParameters != "": cp = self.analysis.computationParameters self.ui.cnosdEdit.setText(cp.split('n:')[1].split(';')[0]) self.ui.deEdit.setText(cp.split('d:')[1].split(';')[0]) numreg = cp.split('m:')[1].split(';')[0] self.ui.numRegCombo.setCurrentIndex(self.ui.numRegCombo.findText(numreg)) if numreg in [1, "1"] : self.ui.logisticRegressioncheckBox.setChecked(True) else : self.ui.logisticRegressioncheckBox.setChecked(False) self.ui.lrEdit.setText(cp.split('l:')[1].split(';')[0]) if "confidence" in self.analysis.category : if self.analysis.category == "confidence_posterior_global": if "z:" in cp : self.ui.posteriorDistributionSampleSizeEdit.setText(cp.split('z:')[1].split(';')[0]) if "c:" in cp : self.ui.notdsEdit.setText(cp.split('c:')[1].split(';')[0]) elif self.analysis.category == "confidence_prior_global": if "b:" in cp : self.ui.notdsEdit.setText(cp.split('b:')[1].split(';')[0]) elif self.analysis.category in ["confidence_prior_specific", "confidence"]: if "t:" in cp : self.ui.notdsEdit.setText(cp.split('t:')[1].split(';')[0]) def checkAll(self): problems = "" try: if "confidence" in self.analysis.category : notds = int(self.ui.notdsEdit.text()) if self.analysis.category == "confidence_posterior_global": linearRegrassion = int(self.ui.posteriorDistributionSampleSizeEdit.text()) lr = int(self.ui.lrEdit.text()) de = int(self.ui.deEdit.text()) cnosd = int(self.ui.cnosdEdit.text()) except Exception as e: problems += "Only non-empty integer values are accepted\n" if problems == "": return True else: output.notify(self,"value problem",problems) return False def validate(self): """ defini les computation parameters de l'analyse et ajoute celle-ci au projet """ analysis_in_edition = (self.analysis.computationParameters != "") self.analysis.candidateScList = self.scNumList self.majDicoValues() chosen_scs_txt = "" for cs in self.scNumList: chosen_scs_txt+="%s,"%str(cs) chosen_scs_txt = chosen_scs_txt[:-1] if self.checkAll(): if self.analysis.category == "compare": self.analysis.computationParameters = "s:%s;n:%s;d:%s;l:%s;m:%s;f:%s"%(chosen_scs_txt,self.dico_values['choNumberOfsimData'],self.dico_values['de'],self.dico_values['lr'],self.dico_values['numReg'],self.analysis.fda) elif "confidence" in self.analysis.category : # == "confidence": # FIXED : # "/home/dehneg/diyabc/src-JMC-C++/general" # -p "/media/psf/Home/VMshare/example_2_microsat_sequence_data_complexe_scenarios_ghost_pop_project_2013_7_9-1/" # -f "s:1,2;r:1;n:203900;m:1;d:501;l:2039;t:509;f:0;h:t2=25500.0 t1=5005.0 ra=0.5 NS1=25500.0 N1=25500.0 N2=25500.0 # N3=5005.0 NS2=25500.0 ta=5005.0;u:g1(0.00055 2 0.2 2 5.005e-06 2)*g2(0.00055 2 0.2 2 5.005e-06 2)*g3(0.00055 # 2 0.2 2 5.005e-06 2)*g4(5.5e-09 2 10.025 2)*g5(5.05e-08 2 10.025 2)" # -i fixed # -g 509 # -m # -t 1 #PRIOR #"/home/dehneg/diyabc/src-JMC-C++/general" # -p "/media/psf/Home/VMshare/example_2_microsat_sequence_data_complexe_scenarios_ghost_pop_project_2013_7_9-1/" # -f "s:1,2;r:1;n:203900;m:1;d:501;l:2039;t:509;f:0;h:t2=UN[1000,50000.0,0.0,0.0] t1=UN[10.0,10000.0,0.0,0.0] ra=UN[0.001,0.999,0.0,0.0] # NS1=UN[1000,50000.0,0.0,0.0] N1=UN[1000,50000.0,0.0,0.0] N2=UN[1000,50000.0,0.0,0.0] N3=UN[10,10000.0,0.0,0.0] # NS2=UN[1000,50000.0,0.0,0.0] ta=UN[10.0,10000.0,0.0,0.0] ta>t1 t2>ta;u:g1(UN[1.00E-004,1.00E-3,0.0005,2] # GA[1.00E-005,1.00E-002,Mean_u,2] UN[1.00E-001,3.00E-001,0.22,2] GA[1.00E-002,9.00E-001,Mean_P,2] # LU[1.00E-008,1.00E-005,1.00E-007,2] GA[1.00E-009,1.00E-004,Mean_u_SNI,2])*g2(UN[1.00E-004,1.00E-3,0.0005,2] # GA[1.00E-005,1.00E-002,Mean_u,2] UN[1.00E-001,3.00E-001,0.22,2] GA[1.00E-002,9.00E-001,Mean_P,2] # LU[1.00E-008,1.00E-005,1.00E-007,2] GA[1.00E-009,1.00E-004,Mean_u_SNI,2])*g3(UN[1.00E-004,1.00E-3,0.0005,2] # GA[1.00E-005,1.00E-002,Mean_u,2] UN[1.00E-001,3.00E-001,0.22,2] GA[1.00E-002,9.00E-001,Mean_P,2] # LU[1.00E-008,1.00E-005,1.00E-007,2] # GA[1.00E-009,1.00E-004,Mean_u_SNI,2])*g4(UN[1.00E-9,1.00E-8,5E-9,2] GA[1.00E-10,1.00E-7,Mean_u,2] UN[0.050,20,10,2] # GA[0.050,20,Mean_k1,2] UN[0.050,20,10,2] GA[0.050,20,Mean_k2,2])*g5(UN[1.00E-9,1.00E-7,5E-9,2] GA[1.00E-9,1.00E-6,Mean_u,2] # UN[0.050,20,10,2] GA[0.050,20,Mean_k1,2] UN[0.050,20,10,2] GA[0.050,20,Mean_k2,2])" # -i prior # -g 509 -m -t 1 candListTxt = "" for cs in self.analysis.candidateScList: candListTxt+="%s,"%str(cs) candListTxt = candListTxt[:-1] strparam = "" strparam += "n:%s;"%self.dico_values['choNumberOfsimData'] strparam += "m:%s;"%self.dico_values['numReg'] strparam += "d:%s;"%self.dico_values['de'] strparam += "f:%s;"%self.analysis.fda if self.analysis.category == "confidence_posterior_global": strparam += "z:%s;" % self.dico_values['linearRegression'] strparam += "l:%s;" % self.dico_values['lr'] strparam += "c:%s;"%self.dico_values['notds'] strparam += "" elif self.analysis.category == "confidence_prior_global": strparam += "l:%s;"%self.dico_values['lr'] strparam += "b:%s;"%self.dico_values['notds'] elif self.analysis.category == "confidence_prior_specific": strparam += "s:%s;"%candListTxt strparam += "r:%s;"%self.analysis.chosenSc strparam += "l:%s;"%self.dico_values['lr'] strparam += "t:%s;"%self.dico_values['notds'] if self.analysis.drawn is 'posterior': strparam += "po;z:%s;a:%s"% (self.dico_values['posteriorNumDataSets'], self.dico_values['posteriorSimNumDataSets']) else : strparam += "h:" if self.analysis.drawn: for paramname in self.analysis.histParamsDrawn.keys(): l = self.analysis.histParamsDrawn[paramname] strparam += "%s="%paramname strparam += "%s[%s,%s,%s,%s] "%(l[1],l[2],l[3],l[4],l[5]) for ctxt in self.analysis.condTxtList: strparam += "%s "%ctxt else: for paramname in self.analysis.histParamsFixed.keys(): l = self.analysis.histParamsFixed[paramname] strparam += "%s="%paramname strparam += "%s "%l[1] strparam = strparam[:-1] if self.analysis.drawn: mutmod = self.analysis.mutationModelDrawn else: mutmod = self.analysis.mutationModelFixed if len(mutmod)>0: strparam += ";u:" if type(mutmod[0]) == type(u'plop'): for ind,gr in enumerate(mutmod): strparam += "g%s("%(ind+1) strgr = gr.strip() strgr = strgr.split('\n') for j,elem in enumerate(strgr): if elem.split()[0] != "MODEL": to_add = strgr[j].split()[1] strparam += "%s "%to_add # virer le dernier espace strparam = strparam[:-1] strparam += ")*" else: for ind,gr in enumerate(mutmod): strparam += "g%s("%(ind+1) for num in gr: strparam += "%s "%num # virer le dernier espace strparam = strparam[:-1] strparam += ")*" # virer le dernier '-' strparam = strparam[:-1] self.analysis.computationParameters = strparam if not analysis_in_edition: self.parents.addAnalysis(self.analysis) self.exit() def setRecordValues(self,scList): if scList in [None, False, [None], [False]] or len(scList) == 0 : scList = [x for x in range(1,self.parents.nb_sc+1)] sumRec = 0 for i in scList: sumRec+=self.parents.readNbRecordsOfScenario(int(i)) self.ui.cnosdEdit.setText(str(sumRec)) # total number of simulated data default self.ui.totNumSimLabel.setText(str(sumRec)) # logistic regression default onePc = sumRec / 100 if onePc < 1000: if sumRec < 1000: onePc = sumRec else: onePc = 1000 self.ui.lrEdit.setText(str(onePc)) # posteriorDistributionSampleSize default #onePcScn = (sumRec / 100 ) / len(scList) #self.ui.posteriorDistributionSampleSizeEdit.setText(str(onePcScn)) def setCandidateScenarios(self,scList): """ ecrit la liste des scenarios candidats """ if scList in [None, False, [None], [False]] or len(scList) == 0 : txt = "" else : plur= "" if len(scList)>1: plur = "s" lstxt="" self.scNumList = [] for i in scList: lstxt+="%s, "%i self.scNumList.append(i) lstxt = lstxt[:-2] txt = "Candidate scenario%s : %s"%(plur,lstxt) self.ui.candidateLabel.setText(txt) def setScenarios(self,scList): """ ecrit la liste des scenarios à comparer """ if scList in [None, False, [None], [False]] or len(scList) == 0 : txt = "" else : plur= "" if len(scList)>1: plur = "s" lstxt="" self.scNumList = [] for i in scList: lstxt+="%s, "%i self.scNumList.append(i) lstxt = lstxt[:-2] txt = "Chosen scenario%s : %s"%(plur,lstxt) self.ui.scenariosLabel.setText(txt) def redefineScenarios(self): """ retourne au choix des scenarios en lui redonnant moi même comme next_widget """ compFrame = self genSel = GenericScenarioSelection(len(self.parents.hist_model_win.scList),"Select the scenarios that you wish to compare",compFrame,"Comparison of scenarios",2,self.analysis,self.parent) self.ui.parents.analysisStack.addWidget(genSel) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentWidget(genSel) def majDicoValues(self): self.dico_values["choNumberOfsimData"] = str(self.ui.cnosdEdit.text()) self.dico_values["de"] = str(self.ui.deEdit.text()) self.dico_values["linearRegression"] = str(self.ui.posteriorDistributionSampleSizeEdit.text()) self.dico_values["lr"] = str(self.ui.lrEdit.text()) self.dico_values["numReg"] = str(self.ui.numRegCombo.currentText()) self.dico_values["notds"] = str(self.ui.notdsEdit.text()) #look for posteriorDataSetNumberEdit in BiasNConfidenceScenarioSelection for child in self.ui.parents.analysisStack.children(): try : self.dico_values['posteriorNumDataSets'] = child.posteriorDataSetNumberEdit.text() except AttributeError as e : pass try : self.dico_values['posteriorSimNumDataSets'] = child.posteriorSimulatedDataSetNumberEdit.text() except AttributeError as e : pass def exit(self): ## reactivation des onglets self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentIndex(0)
class BiasNConfidenceScenarioSelection(formBiasScenarioSelection,baseBiasScenarioSelection): """ Selection du scenario dans la cadre d'une analyse de type bias ou confidence """ def __init__(self,nb_sc,analysis,parent=None): super(BiasNConfidenceScenarioSelection,self).__init__(parent) self.parent=parent self.parents = Parents(self.parent) self.analysis = analysis self.nb_sc = nb_sc self.checklist = [] self.radiolist = [] self.createWidgets() self.putChoices() self.ui.verticalLayout_3.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_3.setAlignment(Qt.AlignTop) self.ui.verticalLayout_2.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout_2.setAlignment(Qt.AlignTop) self.ui.verticalLayout.setAlignment(Qt.AlignHCenter) self.ui.verticalLayout.setAlignment(Qt.AlignTop) self.restoreAnalysisValues() def createWidgets(self): self.ui=self self.ui.setupUi(self) QObject.connect(self.ui.exitButton,SIGNAL("clicked()"),self.exit) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.validate) QObject.connect(self.ui.fixedRadio,SIGNAL("clicked()"),self.checkParameterValues) QObject.connect(self.ui.drawnPriorRadio,SIGNAL("clicked()"),self.checkParameterValues) QObject.connect(self.ui.drawnPosteriorRadio,SIGNAL("clicked()"),self.checkParameterValues) if self.analysis.category == "bias": self.ui.analysisTypeLabel.setText("Bias and mean square error") else: self.ui.analysisTypeLabel.setText("Confidence in scenario choice") self.ui.projectDirEdit.setText(self.parents.dir) self.ui.analysisNameLabel.setText(self.analysis.name) # hide posterior option if self.analysis.category != "bias": self.ui.drawnPosteriorRadio.hide() self.checkParameterValues() def restoreAnalysisValues(self): if self.analysis.chosenSc != None: self.radiolist[self.analysis.chosenSc - 1].setChecked(True) if self.analysis.category == "confidence_prior_specific": for i in range(self.nb_sc): num = i+1 check = self.checklist[i] check.setChecked(len(self.analysis.candidateScList) == 0 or num in self.analysis.candidateScList) if self.analysis.drawn != None: if self.analysis.drawn is False : self.ui.fixedRadio.setChecked(True) # in legacy analysis, drawn can be set to True for prior : elif self.analysis.drawn is True : self.ui.drawnPriorRadio.setChecked(True) else : self.ui.drawnPriorRadio.setChecked('prior' in self.analysis.drawn) self.ui.drawnPosteriorRadio.setChecked('posterior' in self.analysis.drawn) cp = self.analysis.computationParameters posteriorDataSetNumber = "" try: posteriorDataSetNumber = cp.split('z:')[1].split(';')[0] except IndexError: pass posteriorSimulatedDataSetNumber = "" try: posteriorSimulatedDataSetNumber = cp.split('a:')[1].split(';')[0] except IndexError: pass self.ui.posteriorDataSetNumberEdit.setText(posteriorDataSetNumber) self.ui.posteriorSimulatedDataSetNumberEdit.setText(posteriorSimulatedDataSetNumber) self.checkParameterValues(reset=False) def checkParameterValues(self, reset=True): self.ui.posteriorDataSetNumberFrame.hide() if self.analysis.category == "confidence_prior_specific" and self.ui.drawnPosteriorRadio.isChecked(): nbRecordsSelectedScenario = self.parents.readNbRecordsOfScenario(int(self.getSelectedScenario())) self.ui.maxPosteriorDataSetNumberLabel.setText("max = %s"%nbRecordsSelectedScenario) if str(self.ui.posteriorSimulatedDataSetNumberEdit.text()) is '' : self.ui.posteriorSimulatedDataSetNumberEdit.setText(str(nbRecordsSelectedScenario)) elif int(str(self.ui.posteriorSimulatedDataSetNumberEdit.text())) > nbRecordsSelectedScenario : self.ui.posteriorSimulatedDataSetNumberEdit.setText(str(nbRecordsSelectedScenario)) if reset or str(self.ui.posteriorDataSetNumberEdit.text()) is '' : self.ui.posteriorDataSetNumberEdit.setText(str(nbRecordsSelectedScenario/100)) self.ui.posteriorDataSetNumberFrame.show() def validate(self): """ passe à l'étape suivante de la définition de l'analyse """ # pour confidence et bias, on a selectionné un scenario self.analysis.chosenSc = self.getSelectedScenario() if self.ui.fixedRadio.isChecked(): self.analysis.drawn = False elif self.ui.drawnPriorRadio.isChecked(): self.analysis.drawn = 'prior' elif self.ui.drawnPosteriorRadio.isChecked(): self.analysis.drawn = 'posterior' if self.analysis.category == "confidence_prior_specific": try : if int(str(self.ui.posteriorSimulatedDataSetNumberEdit.text())) > self.parents.readNbRecordsOfScenario(int(self.analysis.chosenSc)) \ or int(str(self.ui.posteriorSimulatedDataSetNumberEdit.text())) <= 0 : raise except : QMessageBox.information(self,"Number error","Total number of simulated data considered for local regression should be a positive number and inferior to the number of records of the scenario %s : %s" \ %(self.analysis.chosenSc, self.parents.readNbRecordsOfScenario(int(self.analysis.chosenSc)) )) return 0 try : if int(str(self.ui.posteriorDataSetNumberEdit.text())) > int(str(self.ui.posteriorSimulatedDataSetNumberEdit.text())) \ or int(str(self.ui.posteriorDataSetNumberEdit.text())) <= 0 : raise except : QMessageBox.information(self,"Number error","Number of datasets for local linear regression (simulate data closest to observed) should be a positive number and inferior to the number of records of the scenario %s : %s" \ %(self.analysis.chosenSc, str(self.ui.posteriorSimulatedDataSetNumberEdit.text()) )) return 0 # le cas du confidence, les sc à afficher dans le hist model sont ceux selectionnés if self.analysis.category == "confidence_prior_specific": if len(self.getListSelectedScenarios()) >= 2: # pour confidence on a du selectionner au moins deux scenarios self.analysis.candidateScList = self.getListSelectedScenarios() if self.ui.fixedRadio.isChecked(): next_widget = HistFixed(self.analysis,self.parent) # prior else: next_widget = HistDrawn(self.analysis,self.parent) else: QMessageBox.information(self,"Selection error","At least %s scenarios have to be selected"%2) return 0 # le cas du bias, un sc à afficher, celui du radio button else: # en fonction de fixed ou drawn, l'écran suivant présente un objet différent if self.ui.fixedRadio.isChecked(): next_widget = HistFixed(self.analysis,self.parent) elif self.ui.drawnPosteriorRadio.isChecked(): next_widget = SetupEstimationBias(self.analysis,self.parent) else: next_widget = HistDrawn(self.analysis,self.parent) self.ui.parents.analysisStack.addWidget(next_widget) self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentWidget(next_widget) # skip group loci selection for microsat and seqs analysis # if self.ui.drawnPosteriorRadio.isChecked() and not self.parents.isSnp() : # next_widget.validate() self.parents.updateDoc(next_widget) def getSelectedScenario(self): """ retourne le numero du scenario choisi """ for i,r in enumerate(self.radiolist): if r.isChecked(): return i+1 def getListSelectedScenarios(self): """ retourne la liste des scenarios choisis """ res = [] for i,ch in enumerate(self.checklist): if ch.isChecked(): res.append(i+1) return res def putChoices(self): """ met les choix de scenario en place """ for i in range(self.nb_sc): num = i+1 radio = QRadioButton("Scenario %s"%num,self) self.radiolist.append(radio) self.ui.verticalLayout_4.addWidget(radio) QObject.connect(radio,SIGNAL("clicked()"),self.checkParameterValues) self.radiolist[0].setChecked(True) if self.analysis.category == "confidence_prior_specific": for i in range(self.nb_sc): num = i+1 check = QCheckBox("Scenario %s"%num,self) self.checklist.append(check) self.ui.verticalLayout_6.addWidget(check) else: self.ui.candidateScenariosLabel.hide() self.ui.candidateScenariosTipLabel.hide() self.ui.frame_3.hide() def exit(self): ## reactivation des onglets self.ui.parents.analysisStack.removeWidget(self) self.ui.parents.analysisStack.setCurrentIndex(0)
class ViewAnalysisParameters(formViewAnalysisParameters,baseViewAnalysisParameters): def __init__(self,parent,analysis): super(ViewAnalysisParameters,self).__init__(parent) self.parent = parent self.analysis = analysis self.parents = Parents(self.parent) self.createWidgets() def createWidgets(self): #self.ui = Ui_Frame() self.ui = self self.setupUi(self) self.ui.tableWidget.setColumnWidth(0,250) self.ui.tableWidget.setColumnWidth(1,600) QObject.connect(self.ui.okButton,SIGNAL("clicked()"),self.exit) self.addRow("name",self.analysis.name,editable=True) tab={"pre-ev":"Pre-evaluate scenario-prior combinations", "estimate":"Estimate posterior distributions of parameters", "bias":"Compute bias and precision on parameter estimations", "compare":"Compute posterior probabilities of scenarios", "confidence":"Evaluate confidence in scenario choice", "confidence_posterior_global":"Evaluate confidence in scenario choice, posterior based error, global", "confidence_prior_global":"Evaluate confidence in scenario choice, prior based error, global", "confidence_prior_specific":"Evaluate confidence in scenario choice, prior based error, scenario specific", "modelChecking":"Perform model checking"} self.addRow("type",tab[self.analysis.category]) #if self.analysis.chosenSc != None: # self.addRow("Selected scenario",self.analysis.chosenSc) #if self.analysis.candidateScList != [] and self.analysis.candidateScList != None: # self.addRow("Selected scenarios",self.analysis.candidateScList) tabCompParams = self.analysis.computationParameters.split(';') transDico = {'1':"no",'2':"log",'3':"logit",'4':"logtg"} execRowSize = 75 if self.analysis.category == "estimate" or self.analysis.category == "modelChecking" or self.analysis.category == "bias": if self.analysis.category == "bias": execRowSize = 200 for e in tabCompParams: if e.split(':')[0] == 'n': self.addRow("Chosen number of simulated data",e.split(':')[1]) elif e.split(':')[0] == 'm': self.addRow("Number of selected data",e.split(':')[1]) elif e.split(':')[0] == 'd': self.addRow("Number of test data sets",e.split(':')[1]) elif e.split(':')[0] == 't': self.addRow("Transformation applied to parameters",transDico[e.split(':')[1]]) elif e.split(':')[0] == 'p': self.addRow("Choice of parameters",e.split(':')[1].replace('c',"COMPOSITE ").replace('o',"ORIGINAL ").lower()) elif self.analysis.category == "compare": for e in tabCompParams: if e.split(':')[0] == 's': self.addRow("Chosen scenarios",e.split(':')[1]) elif e.split(':')[0] == 'd': self.addRow("Direct estimate",e.split(':')[1]) elif e.split(':')[0] == 'n': self.addRow("Chosen number of simulated data",e.split(':')[1]) elif e.split(':')[0] == 'l': self.addRow("Logistic regression",e.split(':')[1]) elif e.split(':')[0] == 'm': self.addRow("Regression number",e.split(':')[1]) elif "confidence" in self.analysis.category : # == "confidence": execRowSize = 200 for e in tabCompParams: if e.split(':')[0] == 's' and self.analysis.category == "confidence_prior_specific" : self.addRow("Candidate scenarios",e.split(':')[1]) elif e.split(':')[0] == 'r' and self.analysis.category == "confidence_prior_specific" : self.addRow("Chosen scenario",e.split(':')[1]) elif e.split(':')[0] == 'd': self.addRow("Direct estimate",e.split(':')[1]) elif e.split(':')[0] == 'n': self.addRow("Chosen number of simulated data",e.split(':')[1]) elif e.split(':')[0] == 'l': self.addRow("Logistic regression",e.split(':')[1]) elif e.split(':')[0] == 'z': self.addRow("Logistic regression, posterior global, zzzzz",e.split(':')[1]) elif e.split(':')[0] == 'm': self.addRow("Regression number",e.split(':')[1]) elif e.split(':')[0] == 't': self.addRow("Number of requested test data sets",e.split(':')[1]) elif e.split(':')[0] == 'c': self.addRow("Number of requested test data sets",e.split(':')[1]) elif e.split(':')[0] == 'b': self.addRow("Number of requested test data sets, posterior global, bbb",e.split(':')[1]) # executablePath = self.parent.parent.preferences_win.getExecutablePath() # nbMaxThread = self.parent.parent.preferences_win.getMaxThreadNumber() # particleLoopSize = str(self.parent.parent.preferences_win.particleLoopSizeEdit.text()) # params = self.analysis.computationParameters # # #self.addRow("computation parameters",self.analysis.computationParameters) # c = self.analysis.category # if c == "estimate": # option = "-e" # elif c == "modelChecking": # option = "-j" # elif c == "bias": # option = "-b" # particleLoopSize = int(params.split('d:')[1].split(';')[0]) # elif c == "compare": # option = "-c" # elif "confidence" in c : #== "confidence": # option = "-f" # suboption = "t" # if c == "confidence_posterior_global" : # suboption = "c" # elif c == "confidence_prior_global" : # suboption = "b" # particleLoopSize = int(params.split('%s:'%suboption)[1].split(';')[0]) # elif c == "pre-ev": # option = "-d" # # #cmd_args_list = [executablePath,"-p", "%s/"%self.parent.dir, option, '"%s"'%params, "-i", '%s'%self.analysis.name, "-m", "-t", "%s"%nbMaxThread] # cmd_args_list = ['"'+executablePath+'"',"-p", '"%s/"'%self.parent.dir, "%s"%option, '"%s"'%params, "-i", '%s'%self.analysis.name,"-g" ,"%s"%particleLoopSize , "-m", "-t", "%s"%nbMaxThread] # cmd_args_list_quoted = self.parents.getAnalysisCmdArgsList(self.analysis, quoted=True) command_line = " ".join(cmd_args_list_quoted) self.addRow("executed command line",command_line,editable=True) self.ui.tableWidget.setRowHeight(self.ui.tableWidget.rowCount()-1,execRowSize) QObject.connect(self.ui.tableWidget,SIGNAL("cellChanged(int,int)"),self.cellChanged) def cellChanged(self,row,col): if row == 0 and col == 1: val = str(self.ui.tableWidget.item(0,1).text()) self.parent.changeAnalysisName(self.analysis,val) def addRow(self,name,value,editable=False): self.ui.tableWidget.insertRow(self.ui.tableWidget.rowCount()) 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"%value)) self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,0).setFlags(self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,0).flags() & ~Qt.ItemIsEditable & ~Qt.ItemIsSelectable) if not editable: self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,1).setFlags(self.ui.tableWidget.item(self.ui.tableWidget.rowCount()-1,1).flags() & ~Qt.ItemIsEditable & ~Qt.ItemIsSelectable) def exit(self): self.parent.ui.analysisStack.removeWidget(self) self.parent.ui.analysisStack.setCurrentIndex(0)