class initialConditionsWidget(initialConditionsUI): def __init__(self,folder,nproc): self.currentFolder = folder initialConditionsUI.__init__(self) self.nproc = nproc [self.timedir,self.fields,currtime] = currentFields(self.currentFolder,nproc=self.nproc) self.addTabs() #--Ver si runPFlow esta habilitado for itab in range(self.tabWidget.count()): ifield = self.tabWidget.tabText(itab) if ifield=='U': filename = '%s/system/fvSolution'%self.currentFolder parsedData2 = ParsedParameterFile(filename,createZipped=False) cb = self.tabWidget.widget(itab).findChildren(QtGui.QCheckBox)[0] if ('potentialFlowEnabled' in parsedData2.content.keys()): val = parsedData2['potentialFlowEnabled'] if val=='yes': cb.setChecked(True) self.pushButton.setEnabled(False) def setInitialConditions(self,field): filename = '%s/%s' % (self.timedir,field) filenamefield = ParsedParameterFile(filename,listLengthUnparsed=20,createZipped=False) unifield = filenamefield['internalField'] if (unifield.isUniform()): return unifield.val else: return 'error' def addTabs(self,ipatch=None): for itab in range(self.tabWidget.count()): layout = self.tabWidget.widget(itab).findChildren(QtGui.QVBoxLayout)[0] self.clearLayout(layout,0) self.tabWidget.clear() for ifield in self.fields: if ifield not in unknowns: continue widget = QtGui.QWidget() layout = QtGui.QVBoxLayout(widget) layout2 = QtGui.QHBoxLayout() cb = QtGui.QComboBox() cb.addItems(['uniform','nonuniform']) values = self.setInitialConditions(ifield) layout2.addWidget(cb) if types[ifield]=='scalar': ledit = QtGui.QLineEdit() ledit.setValidator(QtGui.QDoubleValidator()) if type(values)!=str: ledit.setText(str(values)) QtCore.QObject.connect(ledit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.checkData) layout2.addWidget(ledit) else: for j in range(3): ledit = QtGui.QLineEdit() ledit.setValidator(QtGui.QDoubleValidator()) if type(values)!=str: ledit.setText(str(values.vals[j])) layout2.addWidget(ledit) QtCore.QObject.connect(ledit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.checkData) layout.addLayout(layout2) if ifield=='U': qbutton = QtGui.QCheckBox() qbutton.setText('Initialize from potential flow') layout.addWidget(qbutton) QtCore.QObject.connect(qbutton, QtCore.SIGNAL(_fromUtf8("stateChanged(int)")), self.onPotentialFlow) QtCore.QObject.connect(qbutton, QtCore.SIGNAL(_fromUtf8("stateChanged(int)")), self.checkData) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) layout.addItem(spacerItem) self.tabWidget.addTab(widget, ifield) self.tabWidget.setTabText(self.tabWidget.count(),ifield) def onPotentialFlow(self): for itab in range(self.tabWidget.count()): ifield = self.tabWidget.tabText(itab) if ifield=='U': print ifield layout = self.tabWidget.widget(itab).findChildren(QtGui.QVBoxLayout)[0] cb = self.tabWidget.widget(itab).findChildren(QtGui.QCheckBox)[0] layout2 = layout.itemAt(0).layout() for i in range(layout2.count()): if isinstance(layout2.itemAt(i), QtGui.QWidgetItem): layout2.itemAt(i).widget().setEnabled(not cb.isChecked()) if cb.isChecked(): layoutH = QtGui.QHBoxLayout() layoutH.setObjectName('RunFlowButton') self.runButton = QtGui.QPushButton() self.runButton.setText(' Run Potential Flow') icon = QtGui.QIcon() from os import path filename = _fromUtf8(path.join(path.dirname(__file__),"images/fromHelyx/next_grey16.png")) icon.addPixmap(QtGui.QPixmap(filename),QtGui.QIcon.Normal,QtGui.QIcon.Off) self.runButton.setIcon(icon) QtCore.QObject.connect(self.runButton, QtCore.SIGNAL(_fromUtf8("pressed()")), self.runPotentialFlow) layoutH.addWidget(self.runButton) layout.addLayout(layoutH) else: layH = self.tabWidget.widget(itab).findChildren(QtGui.QHBoxLayout,'RunFlowButton')[0] layV = self.tabWidget.widget(itab).findChildren(QtGui.QVBoxLayout)[0] self.clearLayout(layH,0) layV.removeItem(layH) break def runPotentialFlow(self): self.runButton.setEnabled(False) command = 'touch %s/potentialFoam.log'%self.currentFolder os.system(command) #--Abrir ventana de log self.window().newLogTab('Potential Foam','%s/potentialFoam.log'%self.currentFolder) #--Creo un thread para potentialFoam if int(self.nproc)<=1: command = 'potentialFoam -case %s 1> %s/potentialFoam.log 2> %s/error.log &'%(self.currentFolder,self.currentFolder,self.currentFolder) else: command = 'mpirun -np %s potentialFoam -case %s -parallel 1> %s/potentialFoam.log 2> %s/error.log &'%(str(self.nproc), self.currentFolder,self.currentFolder,self.currentFolder) self.threadpotentialFoam = ExampleThread(command) self.connect(self.threadpotentialFoam, QtCore.SIGNAL("finished()"), self.enableButton) #Esto es una porqueria pero no encontre otra forma self.connect(self.threadpotentialFoam, QtCore.SIGNAL("finished()"), self.threadpotentialFoam.terminate) self.threadpotentialFoam.start() def enableButton(self): self.runButton.setEnabled(True) def clearLayout(self, layout, dejar): for i in reversed(range(layout.count())): if i>= dejar: item = layout.itemAt(i) if isinstance(item, QtGui.QWidgetItem): item.widget().close() item.widget().deleteLater() # or # item.widget().setParent(None) elif isinstance(item, QtGui.QSpacerItem): None # no need to do extra stuff else: self.clearLayout(item.layout(),0) # remove the item from layout layout.removeItem(item) def setConditions(self): runPotentialFlow = 0 for itab in range(self.tabWidget.count()): ifield = self.tabWidget.tabText(itab) layout = self.tabWidget.widget(itab).findChildren(QtGui.QVBoxLayout)[0] filename = '%s/%s'%(self.timedir,ifield) parsedData = ParsedParameterFile(filename,listLengthUnparsed=20,createZipped=False) layout2 = layout.itemAt(0).layout() if layout2.count()==2: parsedData['internalField'] = '%s %s'%(layout2.itemAt(0).widget().currentText(),layout2.itemAt(1).widget().text()) else: parsedData['internalField'] = '%s (%s %s %s)'%(layout2.itemAt(0).widget().currentText(),layout2.itemAt(1).widget().text(),layout2.itemAt(2).widget().text(),layout2.itemAt(3).widget().text()) parsedData.writeFile() if ifield == 'U': #and self.tabWidget.widget(itab).findChildren(QtGui.QCheckBox)[0].isChecked(): #QtGui.QMessageBox.about(self, "ERROR", 'Debe simularse con potentialFoam, hacer!!') parsedData['internalField'] = '%s (%s %s %s)'%('uniform',0,0,0) filename = '%s/system/fvSolution'%self.currentFolder parsedData2 = ParsedParameterFile(filename,createZipped=False) if ('potentialFlowEnabled' not in parsedData2.content.keys()): #Si no existe (nunca abrio al gui) la creo parsedData2['potentialFlowEnabled'] = {} cb = self.tabWidget.widget(itab).findChildren(QtGui.QCheckBox)[0] parsedData2['potentialFlowEnabled'] = 'yes' if cb.isChecked() else 'no' parsedData2.writeFile() self.pushButton.setEnabled(False) return def checkData(self): # ready = True # for itab in range(self.tabWidget.count()): # edits = self.tabWidget.widget(itab).findChildren(QtGui.QLineEdit) # for E in edits: # if E.isEnabled(): # if not E.text(): # ready = False # if ready: self.pushButton.setEnabled(True) # else: # self.pushButton.setEnabled(False)
class tracers(tracersUI): def __init__(self, currentFolder, nproc): tracersUI.__init__(self) self.currentFolder = currentFolder self.nproc = nproc [self.timedir,fields,self.currtime] = utils.currentFields(str(self.currentFolder),nproc=self.nproc) self.patches = [] self.emptys = [] self.colors = ['r', 'b', 'k', 'g', 'y', 'c'] self.firstPlot = True self.loadCaseData() self.refreshTable() self.refreshTimeline() self.pushButton_3.setEnabled(False) def loadCaseData(self): filename = '%s/system/controlDict'%self.currentFolder backupFile(filename) self.parsedData = ParsedParameterFile(filename,createZipped=False) self.tracersData = [] if 'functions' in self.parsedData.getValueDict().keys(): for key in self.parsedData['functions'].keys(): if self.parsedData['functions'][key]['type'] == 'scalarTransport': tracer = {} tracer['name'] = key tracer['patchName'] = self.parsedData['functions'][key]['patchName'] tracer['startTime'] = self.parsedData['functions'][key]['fvOptions']['S']['timeStart'] #TODO: cargar aca if tracer['patchName']=='box': tracer['p0'] = self.parsedData['functions'][key]['fvOptions']['S']['p0'] tracer['p1'] = self.parsedData['functions'][key]['fvOptions']['S']['p1'] self.tracersData.append(tracer) if self.patches==[]: boundaries = BoundaryDict(str(self.currentFolder)) self.patches = boundaries.patches() for ipatch in self.patches: if boundaries[ipatch]['type']=='empty': self.emptys.append(ipatch) self.pushButton_3.setEnabled(True) def refreshTable(self): for ii in range(self.tableWidget.rowCount()-1,-1,-1): self.tableWidget.removeRow(ii) for i in range(len(self.tracersData)): self.tableWidget.insertRow(i) item1 = QtGui.QTableWidgetItem() item2 = QtGui.QTableWidgetItem() item3 = QtGui.QTableWidgetItem() item4 = QtGui.QTableWidgetItem() wdg1 = QtGui.QLineEdit() wdg2 = QtGui.QComboBox() wdg3 = QtGui.QLineEdit() wdg4 = QtGui.QLineEdit() wdg2.addItems(list(set(self.patches)-set(self.emptys))) wdg2.addItem('box') wdg2.setObjectName(str(i)) wdg1.setText(str(self.tracersData[i]['startTime'])) wdg2.setCurrentIndex(wdg2.findText(self.tracersData[i]['patchName'])) #TODO: Hay que ver como cagarlo del archivo, preguntar a juan wdg3.setText(str(self.tracersData[i]['p0'])) if self.tracersData[i]['patchName']=='box' else wdg3.setText("(0 0 0)") wdg4.setText(str(self.tracersData[i]['p1'])) if self.tracersData[i]['patchName']=='box' else wdg4.setText("(0 0 0)") wdg3.setEnabled(False) if self.tracersData[i]['patchName']!='box' else wdg3.setEnabled(True) wdg4.setEnabled(False) if self.tracersData[i]['patchName']!='box' else wdg4.setEnabled(True) QtCore.QObject.connect(wdg2, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.change_combobox) wdg3.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}"))) wdg4.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}"))) QtCore.QObject.connect(wdg1,QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect(wdg2,QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.checkAccept) QtCore.QObject.connect(wdg3,QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect(wdg4,QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) self.tableWidget.setItem(i,0,item1) self.tableWidget.setCellWidget(i,0,wdg1) self.tableWidget.setItem(i,1,item2) self.tableWidget.setCellWidget(i,1,wdg2) self.tableWidget.setItem(i,2,item3) self.tableWidget.setCellWidget(i,2,wdg3) self.tableWidget.setItem(i,3,item4) self.tableWidget.setCellWidget(i,3,wdg4) self.pushButton_3.setEnabled(True) def refreshTimeline(self): if not self.firstPlot: self.figureLayout.removeWidget(self.canvas) self.canvas.destroy() self.canvas.close() self.firstPlot = False fig = Figure((2.0, 1.5), dpi=100) self.canvas = FigureCanvas(fig) #self.canvas.setParent(self) self.ax = fig.add_subplot(111) self.ax.clear() #levantar el controlDict y ver los tracers Tf = float(self.parsedData['endTime']) T = float(self.currtime) dT = float(self.parsedData['deltaT']) self.ax.set_ylim(0,1.1) self.ax.set_xlim(-10*dT,Tf) self.ax.plot([0,T-dT,T,T+dT,Tf],[0,0,1,0,0], 'k', marker='o', label='Current Time') i = 0 for itracer in self.tracersData: Tini = float(itracer['startTime']) if float(itracer['startTime'])<T: Tini = T self.ax.plot([0,Tini,Tini+dT,Tf],[0,0,1,1], self.colors[i%6], label=itracer['name']) i = i+1 self.ax.set_title('Timeline') self.ax.set_xlabel('Time [s]') self.ax.set_ylabel('Event') self.ax.legend(loc=0, fontsize = 'small') self.figureLayout.addWidget(self.canvas) self.pushButton_3.setEnabled(True) return def change_combobox(self): name = str(self.sender().objectName()) c1=self.tableWidget.cellWidget(int(name),2) c2=self.tableWidget.cellWidget(int(name),3) if self.sender().currentText()=='box': c1.setEnabled(True) c2.setEnabled(True) else: c1.setEnabled(False) c2.setEnabled(False) print 'done' return def newTracer(self): i = self.tableWidget.rowCount() self.tableWidget.insertRow(i) item1 = QtGui.QTableWidgetItem() item2 = QtGui.QTableWidgetItem() item3 = QtGui.QTableWidgetItem() item4 = QtGui.QTableWidgetItem() wdg1 = QtGui.QLineEdit() wdg2 = QtGui.QComboBox() wdg3 = QtGui.QLineEdit() wdg4 = QtGui.QLineEdit() wdg2.addItems(list(set(self.patches)-set(self.emptys))) wdg2.addItem('box') wdg2.setObjectName(str(i)) wdg3.setEnabled(False) wdg4.setEnabled(False) wdg1.setText('0') wdg3.setText('(0 0 0)') wdg4.setText('(0 0 0)') QtCore.QObject.connect(wdg2, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.change_combobox) wdg3.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}"))) wdg4.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}"))) QtCore.QObject.connect(wdg1,QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect(wdg2,QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.checkAccept) QtCore.QObject.connect(wdg3,QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect(wdg4,QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) self.tableWidget.setItem(i,0,item1) self.tableWidget.setCellWidget(i,0,wdg1) self.tableWidget.setItem(i,1,item2) self.tableWidget.setCellWidget(i,1,wdg2) self.tableWidget.setItem(i,2,item3) self.tableWidget.setCellWidget(i,2,wdg3) self.tableWidget.setItem(i,3,item4) self.tableWidget.setCellWidget(i,3,wdg4) self.pushButton_3.setEnabled(True) def removeTracer(self): ii = self.tableWidget.currentRow() if ii==-1: QtGui.QMessageBox.about(self, "ERROR", "No tracer selected") return w = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Removing", "Do you want to remove tracer data?", QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) ret = w.exec_() if(QtGui.QMessageBox.Yes == ret): self.tableWidget.removeRow(ii) self.drawTracers() self.pushButton_3.setEnabled(False) return def saveCaseData(self): saved = self.drawTracers(True) if saved: self.pushButton_3.setEnabled(False) def drawTracers(self, doTopoSet=False): #Estoy obligado a hacer esto antes porque si lo hago durante la escritura #de datos, me pueden quedar datos a mitad de escritura y corruptos for i in range(self.tableWidget.rowCount()): patchName = str(self.tableWidget.cellWidget(i,1).currentText()) if patchName=='box': if str(self.tableWidget.cellWidget(i,2).text())[-1]!=')' or str(self.tableWidget.cellWidget(i,3).text())[-1]!=')': tracer = 'T%s'%str(i) QtGui.QMessageBox.about(self, "Error", "Wrong regular expression in "+tracer+"!") return False for dd in self.tracersData: del self.parsedData['functions'][dd['name']] if 'functions' not in self.parsedData.getValueDict().keys(): self.parsedData['functions'] = {} patches = [] for i in range(self.tableWidget.rowCount()): patchName = str(self.tableWidget.cellWidget(i,1).currentText()) newkey = 'T%s'%str(i) cellsetname = '%s_c'%newkey tracer = copy.deepcopy(dicc) tracer['fvOptions']['S']['timeStart'] = str(self.tableWidget.cellWidget(i,0).text()) tracer['fvOptions']['S']['cellSet'] = cellsetname tracer['patchName'] = patchName if patchName=='box': tracer['fvOptions']['S']['p0'] = {} if 'p0' not in tracer['fvOptions']['S'].keys() else None tracer['fvOptions']['S']['p1'] = {} if 'p1' not in tracer['fvOptions']['S'].keys() else None #TODO: Verificar que sea correcto el punto tracer['fvOptions']['S']['p0'] = str(self.tableWidget.cellWidget(i,2).text()) tracer['fvOptions']['S']['p1'] = str(self.tableWidget.cellWidget(i,3).text()) del tracer['fvOptions']['S']['scalarExplicitSetValueCoeffs']['injectionRate']['T0'] tracer['fvOptions']['S']['scalarExplicitSetValueCoeffs']['injectionRate'][newkey] = '1' self.parsedData['functions'][newkey] = tracer patches.append(patchName) self.parsedData.writeFile() if doTopoSet: ii = 0 cmd = 'cp %s/caseDicts/topoSetDict %s/system/.'%(os.path.dirname(os.path.realpath(__file__)),self.currentFolder) os.system(cmd) filename = '%s/system/topoSetDict'%self.currentFolder topoSetData = ParsedParameterFile(filename,createZipped=False) #armo el topoSet de manera de generar los cellSet deseados for i in range(self.tableWidget.rowCount()): newkey = 'T%s'%str(i) patchName = str(self.tableWidget.cellWidget(i,1).currentText()) cellsetname = '%s_c'%newkey facesetname = '%s_f'%newkey if patchName != 'box': topoSetData['actions'].append(dic_patchToFace) topoSetData['actions'].append(dic_faceToCell) topoSetData['actions'][ii]['name'] = facesetname topoSetData['actions'][ii]['sourceInfo']['name'] = patchName topoSetData['actions'][ii+1]['name'] = cellsetname topoSetData['actions'][ii+1]['sourceInfo']['set'] = facesetname ii = ii+2 else: p0 = str(self.tableWidget.cellWidget(i,2).text()) p1 = str(self.tableWidget.cellWidget(i,3).text()) topoSetData['actions'].append(copy.deepcopy(dic_boxToCell)) topoSetData['actions'][ii]['name'] = cellsetname topoSetData['actions'][ii]['sourceInfo']['box'] = p0+' '+p1 ii = ii+1 topoSetData.writeFile() cmd = 'topoSet -case %s > %s/run_topoSet.log &'%(self.currentFolder,self.currentFolder) self.threadtopoSet = ExampleThread(cmd) self.connect(self.threadtopoSet, QtCore.SIGNAL("finished()"), self.verifyCells) self.connect(self.threadtopoSet, QtCore.SIGNAL("finished()"), self.threadtopoSet.terminate) self.threadtopoSet.start() self.loadCaseData() self.refreshTable() self.refreshTimeline() return True def verifyCells(self): from os import listdir from os.path import isfile, join folder = '%s/constant/polyMesh/sets'%self.currentFolder files = [f for f in listdir(folder) if isfile(join(folder, f))] empties = [] for ifile in files: if '_c' in ifile: filename = folder+'/'+ifile cmd="grep -in '(' %s"%filename proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() out=out.replace(":(","").replace("\n","") out = int(out)-1 cmd="awk \"NR==%s\" %s"%(str(out),filename) proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() out=out.replace("\n","") if int(out)==0: empties.append(ifile.replace("_c","")) if empties!=[]: strempties=' '.join(empties) w = QtGui.QMessageBox(QtGui.QMessageBox.Warning, "Warning", "The tracer(s) "+strempties+" generated 0 cells!") w.exec_() return def checkAccept(self): ready = True edits = self.findChildren(QtGui.QLineEdit) for E in edits: if E.isEnabled(): if not E.text(): ready = False if ready: self.pushButton_3.setEnabled(True) else: self.pushButton_3.setEnabled(False)
class meshWidget(meshUI): def __init__(self): meshUI.__init__(self) self.canvas = '' self.toolbar = '' self.fig = '' for iatt in self.__dict__.keys(): if 'bm_' in iatt: self.__getattribute__(iatt).setValidator( QtGui.QDoubleValidator()) def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder self.nproc = self.window().nproc [self.timedir, self.fields, self.currtime] = currentFields(str(self.currentFolder), nproc=self.nproc) def createMesh(self): #--Creacion del log (instantaneo) command = 'touch %s/createMesh.log' % self.currentFolder os.system(command) #--Abrir ventana de log self.window().newLogTab('Create Mesh', '%s/createMesh.log' % self.currentFolder) #--Creo un thread para blockMesh y conecto su finalizacion con checkMesh command = 'blockMesh -case %s 1> %s/createMesh.log 2> %s/error.log' % ( self.currentFolder, self.currentFolder, self.currentFolder) self.threadblockmesh = ExampleThread(command) #self.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.checkMesh) #self.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.threadblockmesh.terminate) QtCore.QObject.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.checkMesh) QtCore.QObject.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.threadblockmesh.terminate) QtCore.QObject.connect( self.threadblockmesh, QtCore.SIGNAL("finished()"), lambda: self. window().postproW.setCurrentFolder(self.currentFolder)) self.threadblockmesh.start() def blockMesh(self): about = QtGui.QDialog() blockmesh = Ui_blockmeshDialog() about.setFixedSize(454, 186) blockmesh.setupUi(about) about.exec_() def checkMesh(self): #-- Desabilitar los botones self.pushButton_check.setEnabled(False) self.pushButton_import.setEnabled(False) self.pushButton_view.setEnabled(False) self.pushButton_create.setEnabled(False) self.comboBox_histo.setEnabled(False) #--Crear el log command = 'touch %s/checkMesh.log' % self.currentFolder os.system(command) #--Crear la ventana del log self.window().newLogTab('Check Mesh', '%s/checkMesh.log' % self.currentFolder) #--Creo un thread para checkMesh y lo inicio command = 'checkMesh -case %s 1> %s/checkMesh.log 2> %s/errorcheck.log' % ( self.currentFolder, self.currentFolder, self.currentFolder) self.threadcheckmesh = ExampleThread(command) self.connect(self.threadcheckmesh, QtCore.SIGNAL("finished()"), self.showCheckResult) self.connect(self.threadcheckmesh, QtCore.SIGNAL("finished()"), self.threadcheckmesh.terminate) self.threadcheckmesh.start() #--Comando meshQuality command = 'meshQuality -case %s -time 0 > %s/meshQuality.log' % ( self.currentFolder, self.currentFolder) subprocess.Popen([command], shell=True) return def showCheckResult(self): filename = '%s/errorcheck.log' % self.currentFolder if (self.showError(filename, 'CheckMesh')): self.pushButton_check.setEnabled(True) self.pushButton_import.setEnabled(True) self.pushButton_create.setEnabled(True) self.pushButton_view.setEnabled(True) self.comboBox_histo.setEnabled(True) else: w = QtGui.QMessageBox( QtGui.QMessageBox.Information, "Check Mesh", "Mesh succesfully checked! Click OK to load the mesh data") w.exec_() w.repaint() QtGui.QApplication.processEvents() self.loadMeshData() return def importMesh(self): dialog = QtGui.QFileDialog(self) dialog.setNameFilter( "Fluent 2D Mesh Files (*.msh) ;; Fluent 3D Mesh Files (*.msh) ;; GMSH Mesh Files (*.msh)" ) dialog.setWindowTitle('Select Mesh to Import') dialog.setDirectory(self.currentFolder) if dialog.exec_(): #-- Desabilitar los botones self.pushButton_check.setEnabled(False) self.pushButton_import.setEnabled(False) self.pushButton_view.setEnabled(False) self.pushButton_create.setEnabled(False) self.comboBox_histo.setEnabled(False) filename = dialog.selectedFiles()[0] tipo = dialog.selectedNameFilter() if 'Fluent 3D' in tipo: utility = 'fluent3DMeshToFoam' elif 'Fluent 2D' in tipo: utility = 'fluentMeshToFoam' elif 'GMSH' in tipo: utility = 'gmshToFoam' # with open(filename,'r') as fil: # l1=fil.readline() # if ('$MeshFormat' in l1 and utility!='gmshToFoam') or ('$MeshFormat' not in l1 and utility=='gmshToFoam'): #Agregar la logica para las dos restantes # w = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Error", "Bad Mesh Format") # w.exec_() # self.pushButton_check.setEnabled(True) # self.pushButton_import.setEnabled(True) # self.pushButton_create.setEnabled(True) # self.pushButton_view.setEnabled(True) # self.comboBox_histo.setEnabled(True) # return command = 'touch %s/importMesh.log' % self.currentFolder os.system(command) #command = 'touch %s/error.log'%self.currentFolder #os.system(command) self.window().newLogTab('Import Mesh', '%s/importMesh.log' % self.currentFolder) command = '%s -case %s %s 1> %s/importMesh.log 2> %s/errorimport.log' % ( utility, self.currentFolder, filename, self.currentFolder, self.currentFolder) self.threadimportmesh = ExampleThread(command) self.connect(self.threadimportmesh, QtCore.SIGNAL("finished()"), self.showImportResult) self.connect(self.threadimportmesh, QtCore.SIGNAL("finished()"), self.threadimportmesh.terminate) self.window().runningCommand = 1 self.threadimportmesh.start() def showError(self, filename, title): if os.path.isfile(filename) and os.path.getsize(filename) > 0: with open(filename, 'r') as log: content = log.readlines() while '\n' in content: content.remove('\n') content = ''.join(content) w = QtGui.QMessageBox(QtGui.QMessageBox.Critical, title + " Error", content) QtGui.QApplication.processEvents() w.exec_() log.close() command = 'rm %s' % filename os.system(command) return True return False def showImportResult(self): filename = '%s/errorimport.log' % self.currentFolder if (self.showError(filename, 'ImportMesh')): self.pushButton_check.setEnabled(True) self.pushButton_import.setEnabled(True) self.pushButton_create.setEnabled(True) self.pushButton_view.setEnabled(True) self.comboBox_histo.setEnabled(True) else: w = QtGui.QMessageBox( QtGui.QMessageBox.Information, "Import Mesh", "Mesh succesfully imported. Click OK to do the checkMesh") w.exec_() w.repaint() QtGui.QApplication.processEvents() self.checkMesh() self.updateFieldFiles() return def drawGeo(self): command = 'pyFoamDisplayBlockMesh.py %s/constant/polyMesh/blockMeshDict &' % self.currentFolder os.system(command) def saveBlockMesh(self): return def editBlockMesh(self): return def loadMeshData(self): filename = '%s/checkMesh.log' % self.currentFolder if os.path.isfile(filename): with open(filename, 'r') as log: content = log.readlines() for i in range(len(content)): linea = content[i] self.label_npoints.setText( linea.replace( '\n', '').strip()) if ' points:' in linea else None self.label_ncells.setText(linea.replace( '\n', '').strip()) if ' cells:' in linea else None self.label_nfaces.setText(linea.replace( '\n', '').strip()) if ' faces: ' in linea else None self.label_nifaces.setText(linea[:-1].strip( )) if ' internal faces: ' in linea else None if 'bounding box' in linea: limits = linea.replace('(', '').replace(')', '').strip().split() self.label_xrange.setText('x Range: [%s, %s]' % (limits[4], limits[7])) self.label_yrange.setText('y Range: [%s, %s]' % (limits[5], limits[8])) self.label_zrange.setText('z Range: [%s, %s]' % (limits[6], limits[9])) self.label_nhexa.setText(linea.replace( '\n', '').strip()) if ' hexa' in linea else None self.label_nprisms.setText( linea.replace( '\n', '').strip()) if ' prism' in linea else None self.label_nwedges.setText( linea.replace('\n', '').strip() ) if ' wedges:' in linea and 'tet' not in linea else None self.label_npyramids.setText( linea.replace( '\n', '').strip()) if ' pyramids:' in linea else None self.label_ntet.setText(linea.replace( '\n', '').strip()) if ' tet wedges:' in linea else None self.label_ntetra.setText(linea.replace( '\n', '').strip()) if ' tetra' in linea else None self.label_npoly.setText(linea[:-1].strip( )) if ' polyhedra:' in linea else None log.close() else: QtGui.QMessageBox( QtGui.QMessageBox.Information, "Caution!", "Statistics must be executed in order to see mesh data").exec_( ) self.pushButton_check.setEnabled(True) self.pushButton_import.setEnabled(True) self.pushButton_create.setEnabled(True) self.pushButton_view.setEnabled(True) self.comboBox_histo.setEnabled(True) def drawStatistics(self): print 'En draw statistics' if self.comboBox_histo.currentIndex() == 0: return filename = '%s/meshQuality.log' % self.currentFolder if os.path.isfile(filename): if self.canvas != '': self.verticalLayout_draw.removeWidget(self.canvas) self.canvas.destroy() self.canvas.close() self.canvas = '' import matplotlib item = self.groupBox_draw.findChild( matplotlib.backends.backend_qt4agg.FigureCanvasAgg) item.close() item.deleteLater() if self.toolbar != '': self.verticalLayout_draw.removeWidget(self.toolbar) self.toolbar.destroy() self.toolbar.close() self.toolbar = '' #import matplotlib #item=self.groupBox_draw.findChild(matplotlib.backends.backend_qt4agg.FigureCanvasAgg) #item.close() #item.deleteLater() keys = ['nonOrth', 'skew', 'vol'] bins = {} bins['nonOrth'] = range(0, 95, 10) bins['skew'] = [x / 100.0 for x in range(25, 520, 50)] width = [2.5, 0.25] maxV = 0.0 minV = 0.0 ikey = self.comboBox_histo.currentIndex() - 1 data = [] log = open(filename, 'r') for linea in log: if keys[ikey] in linea: datastr = linea.strip().split()[1:] if keys[ikey] == 'vol': maxV = float(linea.strip().split() [1]) if 'maxVol' in linea else maxV minV = float(linea.strip().split() [1]) if 'minVol' in linea else maxV for i in datastr: data.append(int(i)) if keys[ikey] == 'vol': #bins[keys[ikey]] = [x for x in drange(minV,maxV*1.05,(maxV-minV)/10)] if (maxV - minV) > 1e-12: bins[keys[ikey]] = arange(1, maxV * 1.05 / minV, (maxV / minV) / 10.0) width.append((maxV - minV) / 40.0) else: bins[keys[ikey]] = [minV * x for x in range(1, 11)] width.append(0.25 * minV) for i in range(len(data)): data[i] = 1 if data[i] < 1 else data[i] self.fig = Figure((1.5, 1.0), dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.groupBox_draw) ax = self.fig.add_subplot(111) ax.bar(bins[keys[ikey]], data, width[ikey]) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + \ ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(7) self.toolbar = myNavigationToolbar(self.canvas, self) self.toolbar.removeAction( self.toolbar.actions()[7]) #elimino el boton de eliminar self.toolbar.setFixedHeight(32) self.verticalLayout_draw.addWidget(self.canvas, 1) self.verticalLayout_draw.addWidget(self.toolbar, 0, QtCore.Qt.AlignCenter) return def viewMesh(self): filequa = '%s/meshQuality.log' if not os.path.isfile(filequa): command = 'meshQuality -case %s -time 0 > %s/meshQuality.log &' % ( self.currentFolder, self.currentFolder) os.system(command) #command = 'pvpython /usr/local/bin/pyFoamPVLoadState.py --state=meshNonOrth.pvsm %s &'%self.currentFolder #TODO: Estaria bueno ver una manera de silenciar los warnings molestos que tira paraview command = 'pvpython /usr/local/bin/pyFoamPVLoadState.py --state=%s/pvsms/meshNonOrthWhite.pvsm %s &' % ( os.path.dirname(os.path.realpath(__file__)), self.currentFolder) os.system(command) return def updateFieldFiles(self): #tengo que releer cada uno de los campos en el directorio actual, #pisar los boundaries por los que aparece en constant/polyMesh/boundary #imponerles alguna CB por defecto dependiendo del tipo de patch boundaries = BoundaryDict(self.currentFolder) #veo los campos que tengo en el directorio inicial [timedir, fields, currtime] = currentFields(self.currentFolder, nproc=self.window().nproc, filterTurb=False) fileDict = '%s/system/changeDictionaryPetroSym' % self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict, createZipped=False) for ifield in fields: if dictDict == []: filename = '%s/%s' % (timedir, ifield) fieldData = ParsedParameterFile(filename, createZipped=False) else: fieldData = dictDict['dictionaryReplacement'][ifield] oldKeys = fieldData['boundaryField'].keys() fieldData['boundaryField'] = {} for ipatch in boundaries.getValueDict(): if ipatch not in fieldData['boundaryField']: if boundaries[ipatch]['nFaces'] == 0: continue patchDict = {} if ifield in unknowns: if boundaries[ipatch]['type'] == 'empty': patchDict['type'] = 'empty' if ipatch in oldKeys: patchDict['ZZvalue'] = '0' else: patchDict['type'] = 'zeroGradient' if ipatch in oldKeys: patchDict['ZZvalue'] = '0' else: patchDict['type'] = 'calculated' if ipatch in oldKeys: patchDict['ZZvalue'] = '0' fieldData['boundaryField'][ipatch] = patchDict # poner el campo interno uniforme en cero if types[ifield] == 'scalar': fieldData['internalField'] = 'uniform 0' elif types[ifield] == 'vector': fieldData['internalField'] = 'uniform (0 0 0)' if dictDict == []: fieldData.writeFile() if dictDict != []: dictDict.writeFile() dictDictBak = ParsedParameterFile(fileDict, createZipped=False) keysDict = dictDict['dictionaryReplacement'].keys() dictDictBak['dictionaryReplacement'] = {} for ikey in keysDict: if ikey in self.fields: dictDictBak['dictionaryReplacement'][ikey] = dictDict[ 'dictionaryReplacement'][ikey] dictDictBak.writeFileAs('%s/system/changeDictionaryPetroSym.bak' % self.currentFolder) command = 'sed -i "s/ZZ/~/g" %s/system/changeDictionaryPetroSym.bak' % ( self.currentFolder) os.system(command) #chequear que no bloquee if self.window().nproc <= 1: command = 'changeDictionary -case %s -dict %s/system/changeDictionaryPetroSym.bak 1> %s/changeDictionary.log 2> %s/error.log &' % ( self.currentFolder, self.currentFolder, self.currentFolder, self.currentFolder) else: command = 'mpirun -np %s changeDictionary -case %s -dict %s/system/changeDictionaryPetroSym.bak -parallel 1> %s/changeDictionary.log 2> %s/error.log &' % ( str(self.nproc), self.currentFolder, self.currentFolder, self.currentFolder, self.currentFolder) os.system(command) return
class initialConditionsWidget(initialConditionsUI): def __init__(self, folder, nproc): self.currentFolder = folder initialConditionsUI.__init__(self) self.nproc = nproc [self.timedir, self.fields, currtime] = currentFields(self.currentFolder, nproc=self.nproc) self.addTabs() #--Ver si runPFlow esta habilitado for itab in range(self.tabWidget.count()): ifield = self.tabWidget.tabText(itab) if ifield == 'U': filename = '%s/system/fvSolution' % self.currentFolder parsedData2 = ParsedParameterFile(filename, createZipped=False) cb = self.tabWidget.widget(itab).findChildren( QtGui.QCheckBox)[0] if ('potentialFlowEnabled' in parsedData2.content.keys()): val = parsedData2['potentialFlowEnabled'] if val == 'yes': cb.setChecked(True) self.pushButton.setEnabled(False) def setInitialConditions(self, field): filename = '%s/%s' % (self.timedir, field) filenamefield = ParsedParameterFile(filename, listLengthUnparsed=20, createZipped=False) unifield = filenamefield['internalField'] if (unifield.isUniform()): return unifield.val else: return 'error' def addTabs(self, ipatch=None): for itab in range(self.tabWidget.count()): layout = self.tabWidget.widget(itab).findChildren( QtGui.QVBoxLayout)[0] self.clearLayout(layout, 0) self.tabWidget.clear() for ifield in self.fields: if ifield not in unknowns: continue widget = QtGui.QWidget() layout = QtGui.QVBoxLayout(widget) layout2 = QtGui.QHBoxLayout() cb = QtGui.QComboBox() cb.addItems(['uniform', 'nonuniform']) values = self.setInitialConditions(ifield) layout2.addWidget(cb) if types[ifield] == 'scalar': ledit = QtGui.QLineEdit() ledit.setValidator(QtGui.QDoubleValidator()) if type(values) != str: ledit.setText(str(values)) QtCore.QObject.connect( ledit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.checkData) layout2.addWidget(ledit) else: for j in range(3): ledit = QtGui.QLineEdit() ledit.setValidator(QtGui.QDoubleValidator()) if type(values) != str: ledit.setText(str(values.vals[j])) layout2.addWidget(ledit) QtCore.QObject.connect( ledit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.checkData) layout.addLayout(layout2) if ifield == 'U': qbutton = QtGui.QCheckBox() qbutton.setText('Initialize from potential flow') layout.addWidget(qbutton) QtCore.QObject.connect( qbutton, QtCore.SIGNAL(_fromUtf8("stateChanged(int)")), self.onPotentialFlow) QtCore.QObject.connect( qbutton, QtCore.SIGNAL(_fromUtf8("stateChanged(int)")), self.checkData) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) layout.addItem(spacerItem) self.tabWidget.addTab(widget, ifield) self.tabWidget.setTabText(self.tabWidget.count(), ifield) def onPotentialFlow(self): for itab in range(self.tabWidget.count()): ifield = self.tabWidget.tabText(itab) if ifield == 'U': print ifield layout = self.tabWidget.widget(itab).findChildren( QtGui.QVBoxLayout)[0] cb = self.tabWidget.widget(itab).findChildren( QtGui.QCheckBox)[0] layout2 = layout.itemAt(0).layout() for i in range(layout2.count()): if isinstance(layout2.itemAt(i), QtGui.QWidgetItem): layout2.itemAt(i).widget().setEnabled( not cb.isChecked()) if cb.isChecked(): layoutH = QtGui.QHBoxLayout() layoutH.setObjectName('RunFlowButton') self.runButton = QtGui.QPushButton() self.runButton.setText(' Run Potential Flow') icon = QtGui.QIcon() from os import path filename = _fromUtf8( path.join(path.dirname(__file__), "images/fromHelyx/next_grey16.png")) icon.addPixmap(QtGui.QPixmap(filename), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.runButton.setIcon(icon) QtCore.QObject.connect( self.runButton, QtCore.SIGNAL(_fromUtf8("pressed()")), self.runPotentialFlow) layoutH.addWidget(self.runButton) layout.addLayout(layoutH) else: layH = self.tabWidget.widget(itab).findChildren( QtGui.QHBoxLayout, 'RunFlowButton')[0] layV = self.tabWidget.widget(itab).findChildren( QtGui.QVBoxLayout)[0] self.clearLayout(layH, 0) layV.removeItem(layH) break def runPotentialFlow(self): self.runButton.setEnabled(False) command = 'touch %s/potentialFoam.log' % self.currentFolder os.system(command) #--Abrir ventana de log self.window().newLogTab('Potential Foam', '%s/potentialFoam.log' % self.currentFolder) #--Creo un thread para potentialFoam if int(self.nproc) <= 1: command = 'potentialFoam -case %s 1> %s/potentialFoam.log 2> %s/error.log &' % ( self.currentFolder, self.currentFolder, self.currentFolder) else: command = 'mpirun -np %s potentialFoam -case %s -parallel 1> %s/potentialFoam.log 2> %s/error.log &' % ( str(self.nproc), self.currentFolder, self.currentFolder, self.currentFolder) self.threadpotentialFoam = ExampleThread(command) self.connect(self.threadpotentialFoam, QtCore.SIGNAL("finished()"), self.enableButton ) #Esto es una porqueria pero no encontre otra forma self.connect(self.threadpotentialFoam, QtCore.SIGNAL("finished()"), self.threadpotentialFoam.terminate) self.threadpotentialFoam.start() def enableButton(self): self.runButton.setEnabled(True) def clearLayout(self, layout, dejar): for i in reversed(range(layout.count())): if i >= dejar: item = layout.itemAt(i) if isinstance(item, QtGui.QWidgetItem): item.widget().close() item.widget().deleteLater() # or # item.widget().setParent(None) elif isinstance(item, QtGui.QSpacerItem): None # no need to do extra stuff else: self.clearLayout(item.layout(), 0) # remove the item from layout layout.removeItem(item) def setConditions(self): runPotentialFlow = 0 for itab in range(self.tabWidget.count()): ifield = self.tabWidget.tabText(itab) layout = self.tabWidget.widget(itab).findChildren( QtGui.QVBoxLayout)[0] filename = '%s/%s' % (self.timedir, ifield) parsedData = ParsedParameterFile(filename, listLengthUnparsed=20, createZipped=False) layout2 = layout.itemAt(0).layout() if layout2.count() == 2: parsedData['internalField'] = '%s %s' % ( layout2.itemAt(0).widget().currentText(), layout2.itemAt(1).widget().text()) else: parsedData['internalField'] = '%s (%s %s %s)' % ( layout2.itemAt(0).widget().currentText(), layout2.itemAt(1).widget().text(), layout2.itemAt(2).widget().text(), layout2.itemAt(3).widget().text()) parsedData.writeFile() if ifield == 'U': #and self.tabWidget.widget(itab).findChildren(QtGui.QCheckBox)[0].isChecked(): #QtGui.QMessageBox.about(self, "ERROR", 'Debe simularse con potentialFoam, hacer!!') parsedData['internalField'] = '%s (%s %s %s)' % ('uniform', 0, 0, 0) filename = '%s/system/fvSolution' % self.currentFolder parsedData2 = ParsedParameterFile(filename, createZipped=False) if ('potentialFlowEnabled' not in parsedData2.content.keys() ): #Si no existe (nunca abrio al gui) la creo parsedData2['potentialFlowEnabled'] = {} cb = self.tabWidget.widget(itab).findChildren( QtGui.QCheckBox)[0] parsedData2['potentialFlowEnabled'] = 'yes' if cb.isChecked( ) else 'no' parsedData2.writeFile() self.pushButton.setEnabled(False) return def checkData(self): # ready = True # for itab in range(self.tabWidget.count()): # edits = self.tabWidget.widget(itab).findChildren(QtGui.QLineEdit) # for E in edits: # if E.isEnabled(): # if not E.text(): # ready = False # if ready: self.pushButton.setEnabled(True) # else: # self.pushButton.setEnabled(False)
class meshWidget(meshUI): def __init__(self): meshUI.__init__(self) self.canvas = '' self.toolbar = '' self.fig = '' for iatt in self.__dict__.keys(): if 'bm_' in iatt: self.__getattribute__(iatt).setValidator(QtGui.QDoubleValidator()) def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder self.nproc = self.window().nproc [self.timedir,self.fields,self.currtime] = currentFields(str(self.currentFolder),nproc=self.nproc) def createMesh(self): #--Creacion del log (instantaneo) command = 'touch %s/createMesh.log'%self.currentFolder os.system(command) #--Abrir ventana de log self.window().newLogTab('Create Mesh','%s/createMesh.log'%self.currentFolder) #--Creo un thread para blockMesh y conecto su finalizacion con checkMesh command = 'blockMesh -case %s 1> %s/createMesh.log 2> %s/error.log'%(self.currentFolder,self.currentFolder,self.currentFolder) self.threadblockmesh = ExampleThread(command) #self.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.checkMesh) #self.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.threadblockmesh.terminate) QtCore.QObject.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.checkMesh) QtCore.QObject.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), self.threadblockmesh.terminate) QtCore.QObject.connect(self.threadblockmesh, QtCore.SIGNAL("finished()"), lambda: self.window().postproW.setCurrentFolder(self.currentFolder)) self.threadblockmesh.start() def blockMesh(self): about = QtGui.QDialog() blockmesh = Ui_blockmeshDialog() about.setFixedSize(454,186) blockmesh.setupUi(about) about.exec_() def checkMesh(self): #-- Desabilitar los botones self.pushButton_check.setEnabled(False) self.pushButton_import.setEnabled(False) self.pushButton_view.setEnabled(False) self.pushButton_create.setEnabled(False) self.comboBox_histo.setEnabled(False) #--Crear el log command = 'touch %s/checkMesh.log'%self.currentFolder os.system(command) #--Crear la ventana del log self.window().newLogTab('Check Mesh','%s/checkMesh.log'%self.currentFolder) #--Creo un thread para checkMesh y lo inicio command = 'checkMesh -case %s 1> %s/checkMesh.log 2> %s/errorcheck.log'%(self.currentFolder,self.currentFolder,self.currentFolder) self.threadcheckmesh = ExampleThread(command) self.connect(self.threadcheckmesh, QtCore.SIGNAL("finished()"), self.showCheckResult) self.connect(self.threadcheckmesh, QtCore.SIGNAL("finished()"), self.threadcheckmesh.terminate) self.threadcheckmesh.start() #--Comando meshQuality command = 'meshQuality -case %s -time 0 > %s/meshQuality.log'%(self.currentFolder,self.currentFolder) subprocess.Popen([command],shell=True) return def showCheckResult(self): filename = '%s/errorcheck.log'%self.currentFolder if (self.showError(filename,'CheckMesh')): self.pushButton_check.setEnabled(True) self.pushButton_import.setEnabled(True) self.pushButton_create.setEnabled(True) self.pushButton_view.setEnabled(True) self.comboBox_histo.setEnabled(True) else: w = QtGui.QMessageBox(QtGui.QMessageBox.Information,"Check Mesh","Mesh succesfully checked! Click OK to load the mesh data") w.exec_() w.repaint() QtGui.QApplication.processEvents() self.loadMeshData() return def importMesh(self): dialog = QtGui.QFileDialog(self) dialog.setNameFilter("Fluent 2D Mesh Files (*.msh) ;; Fluent 3D Mesh Files (*.msh) ;; GMSH Mesh Files (*.msh)") dialog.setWindowTitle('Select Mesh to Import') dialog.setDirectory(self.currentFolder) if dialog.exec_(): #-- Desabilitar los botones self.pushButton_check.setEnabled(False) self.pushButton_import.setEnabled(False) self.pushButton_view.setEnabled(False) self.pushButton_create.setEnabled(False) self.comboBox_histo.setEnabled(False) filename = dialog.selectedFiles()[0]; tipo = dialog.selectedNameFilter() if 'Fluent 3D' in tipo: utility = 'fluent3DMeshToFoam' elif 'Fluent 2D' in tipo: utility = 'fluentMeshToFoam' elif 'GMSH' in tipo: utility = 'gmshToFoam' # with open(filename,'r') as fil: # l1=fil.readline() # if ('$MeshFormat' in l1 and utility!='gmshToFoam') or ('$MeshFormat' not in l1 and utility=='gmshToFoam'): #Agregar la logica para las dos restantes # w = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Error", "Bad Mesh Format") # w.exec_() # self.pushButton_check.setEnabled(True) # self.pushButton_import.setEnabled(True) # self.pushButton_create.setEnabled(True) # self.pushButton_view.setEnabled(True) # self.comboBox_histo.setEnabled(True) # return command = 'touch %s/importMesh.log'%self.currentFolder os.system(command) #command = 'touch %s/error.log'%self.currentFolder #os.system(command) self.window().newLogTab('Import Mesh','%s/importMesh.log'%self.currentFolder) command = '%s -case %s %s 1> %s/importMesh.log 2> %s/errorimport.log' %(utility, self.currentFolder, filename, self.currentFolder, self.currentFolder) self.threadimportmesh = ExampleThread(command) self.connect(self.threadimportmesh, QtCore.SIGNAL("finished()"), self.showImportResult) self.connect(self.threadimportmesh, QtCore.SIGNAL("finished()"), self.threadimportmesh.terminate) self.window().runningCommand = 1 self.threadimportmesh.start() def showError(self,filename,title): if os.path.isfile(filename) and os.path.getsize(filename) > 0: with open(filename, 'r') as log: content = log.readlines() while '\n' in content: content.remove('\n') content = ''.join(content) w = QtGui.QMessageBox(QtGui.QMessageBox.Critical,title+" Error",content) QtGui.QApplication.processEvents() w.exec_() log.close() command = 'rm %s'%filename os.system(command) return True return False def showImportResult(self): filename = '%s/errorimport.log'%self.currentFolder if (self.showError(filename,'ImportMesh')): self.pushButton_check.setEnabled(True) self.pushButton_import.setEnabled(True) self.pushButton_create.setEnabled(True) self.pushButton_view.setEnabled(True) self.comboBox_histo.setEnabled(True) else: w = QtGui.QMessageBox(QtGui.QMessageBox.Information,"Import Mesh","Mesh succesfully imported. Click OK to do the checkMesh") w.exec_() w.repaint() QtGui.QApplication.processEvents() self.checkMesh() self.updateFieldFiles() return def drawGeo(self): command = 'pyFoamDisplayBlockMesh.py %s/constant/polyMesh/blockMeshDict &'%self.currentFolder os.system(command) def saveBlockMesh(self): return def editBlockMesh(self): return def loadMeshData(self): filename = '%s/checkMesh.log'%self.currentFolder if os.path.isfile(filename): with open(filename, 'r') as log: content = log.readlines() for i in range(len(content)): linea = content[i] self.label_npoints.setText(linea.replace('\n','').strip()) if ' points:' in linea else None self.label_ncells.setText(linea.replace('\n','').strip()) if ' cells:' in linea else None self.label_nfaces.setText(linea.replace('\n','').strip()) if ' faces: ' in linea else None self.label_nifaces.setText(linea[:-1].strip()) if ' internal faces: ' in linea else None if 'bounding box' in linea: limits = linea.replace('(','').replace(')','').strip().split() self.label_xrange.setText('x Range: [%s, %s]'%(limits[4],limits[7])) self.label_yrange.setText('y Range: [%s, %s]'%(limits[5],limits[8])) self.label_zrange.setText('z Range: [%s, %s]'%(limits[6],limits[9])) self.label_nhexa.setText(linea.replace('\n','').strip()) if ' hexa' in linea else None self.label_nprisms.setText(linea.replace('\n','').strip()) if ' prism' in linea else None self.label_nwedges.setText(linea.replace('\n','').strip()) if ' wedges:' in linea and 'tet' not in linea else None self.label_npyramids.setText(linea.replace('\n','').strip()) if ' pyramids:' in linea else None self.label_ntet.setText(linea.replace('\n','').strip()) if ' tet wedges:' in linea else None self.label_ntetra.setText(linea.replace('\n','').strip()) if ' tetra' in linea else None self.label_npoly.setText(linea[:-1].strip()) if ' polyhedra:' in linea else None log.close() else: QtGui.QMessageBox(QtGui.QMessageBox.Information, "Caution!", "Statistics must be executed in order to see mesh data").exec_() self.pushButton_check.setEnabled(True) self.pushButton_import.setEnabled(True) self.pushButton_create.setEnabled(True) self.pushButton_view.setEnabled(True) self.comboBox_histo.setEnabled(True) def drawStatistics(self): print 'En draw statistics' if self.comboBox_histo.currentIndex()==0: return filename = '%s/meshQuality.log'%self.currentFolder if os.path.isfile(filename): if self.canvas != '': self.verticalLayout_draw.removeWidget(self.canvas) self.canvas.destroy() self.canvas.close() self.canvas = '' import matplotlib item=self.groupBox_draw.findChild(matplotlib.backends.backend_qt4agg.FigureCanvasAgg) item.close() item.deleteLater() if self.toolbar != '': self.verticalLayout_draw.removeWidget(self.toolbar) self.toolbar.destroy() self.toolbar.close() self.toolbar = '' #import matplotlib #item=self.groupBox_draw.findChild(matplotlib.backends.backend_qt4agg.FigureCanvasAgg) #item.close() #item.deleteLater() keys = ['nonOrth','skew','vol'] bins = {} bins['nonOrth'] = range(0,95,10) bins['skew'] = [x / 100.0 for x in range(25, 520, 50)] width = [2.5,0.25] maxV = 0.0 minV = 0.0 ikey = self.comboBox_histo.currentIndex()-1 data = [] log = open(filename, 'r') for linea in log: if keys[ikey] in linea: datastr = linea.strip().split()[1:] if keys[ikey]=='vol': maxV = float(linea.strip().split()[1]) if 'maxVol' in linea else maxV minV = float(linea.strip().split()[1]) if 'minVol' in linea else maxV for i in datastr: data.append(int(i)) if keys[ikey]=='vol': #bins[keys[ikey]] = [x for x in drange(minV,maxV*1.05,(maxV-minV)/10)] if(maxV-minV)>1e-12: bins[keys[ikey]] = arange(1,maxV*1.05/minV,(maxV/minV)/10.0) width.append((maxV-minV)/40.0) else: bins[keys[ikey]] = [minV*x for x in range(1,11)] width.append(0.25*minV) for i in range(len(data)): data[i] = 1 if data[i]<1 else data[i] self.fig = Figure((1.5, 1.0), dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.groupBox_draw) ax = self.fig.add_subplot(111) ax.bar(bins[keys[ikey]], data, width[ikey]) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + \ ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(7) self.toolbar = myNavigationToolbar(self.canvas,self) self.toolbar.removeAction(self.toolbar.actions()[7]) #elimino el boton de eliminar self.toolbar.setFixedHeight(32) self.verticalLayout_draw.addWidget(self.canvas,1) self.verticalLayout_draw.addWidget(self.toolbar,0,QtCore.Qt.AlignCenter) return def viewMesh(self): filequa = '%s/meshQuality.log' if not os.path.isfile(filequa): command = 'meshQuality -case %s -time 0 > %s/meshQuality.log &'%(self.currentFolder,self.currentFolder) os.system(command) #command = 'pvpython /usr/local/bin/pyFoamPVLoadState.py --state=meshNonOrth.pvsm %s &'%self.currentFolder #TODO: Estaria bueno ver una manera de silenciar los warnings molestos que tira paraview command = 'pvpython /usr/local/bin/pyFoamPVLoadState.py --state=%s/pvsms/meshNonOrthWhite.pvsm %s &'%(os.path.dirname(os.path.realpath(__file__)),self.currentFolder) os.system(command) return def updateFieldFiles(self): #tengo que releer cada uno de los campos en el directorio actual, #pisar los boundaries por los que aparece en constant/polyMesh/boundary #imponerles alguna CB por defecto dependiendo del tipo de patch boundaries = BoundaryDict(self.currentFolder) #veo los campos que tengo en el directorio inicial [timedir,fields,currtime] = currentFields(self.currentFolder, nproc = self.window().nproc, filterTurb=False) fileDict = '%s/system/changeDictionaryPetroSym'%self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict,createZipped=False) for ifield in fields: if dictDict==[]: filename = '%s/%s'%(timedir,ifield) fieldData = ParsedParameterFile(filename,createZipped=False) else: fieldData = dictDict['dictionaryReplacement'][ifield] oldKeys = fieldData['boundaryField'].keys() fieldData['boundaryField'] = {} for ipatch in boundaries.getValueDict(): if ipatch not in fieldData['boundaryField']: if boundaries[ipatch]['nFaces']==0: continue patchDict={} if ifield in unknowns: if boundaries[ipatch]['type']=='empty': patchDict['type'] = 'empty' if ipatch in oldKeys: patchDict['ZZvalue'] = '0' else: patchDict['type'] = 'zeroGradient' if ipatch in oldKeys: patchDict['ZZvalue'] = '0' else: patchDict['type'] = 'calculated' if ipatch in oldKeys: patchDict['ZZvalue'] = '0' fieldData['boundaryField'][ipatch] = patchDict # poner el campo interno uniforme en cero if types[ifield] == 'scalar': fieldData['internalField'] = 'uniform 0' elif types[ifield] == 'vector': fieldData['internalField'] = 'uniform (0 0 0)' if dictDict==[]: fieldData.writeFile() if dictDict!=[]: dictDict.writeFile() dictDictBak = ParsedParameterFile(fileDict,createZipped=False) keysDict = dictDict['dictionaryReplacement'].keys() dictDictBak['dictionaryReplacement'] = {} for ikey in keysDict: if ikey in self.fields: dictDictBak['dictionaryReplacement'][ikey] = dictDict['dictionaryReplacement'][ikey] dictDictBak.writeFileAs('%s/system/changeDictionaryPetroSym.bak'%self.currentFolder) command = 'sed -i "s/ZZ/~/g" %s/system/changeDictionaryPetroSym.bak'%(self.currentFolder) os.system(command) #chequear que no bloquee if self.window().nproc<=1: command = 'changeDictionary -case %s -dict %s/system/changeDictionaryPetroSym.bak 1> %s/changeDictionary.log 2> %s/error.log &'%(self.currentFolder,self.currentFolder,self.currentFolder,self.currentFolder) else: command = 'mpirun -np %s changeDictionary -case %s -dict %s/system/changeDictionaryPetroSym.bak -parallel 1> %s/changeDictionary.log 2> %s/error.log &'%(str(self.nproc),self.currentFolder,self.currentFolder,self.currentFolder,self.currentFolder) os.system(command) return
class tracers(tracersUI): def __init__(self, currentFolder, nproc): tracersUI.__init__(self) self.currentFolder = currentFolder self.nproc = nproc [self.timedir, fields, self.currtime] = utils.currentFields(str(self.currentFolder), nproc=self.nproc) self.patches = [] self.emptys = [] self.colors = ['r', 'b', 'k', 'g', 'y', 'c'] self.firstPlot = True self.loadCaseData() self.refreshTable() self.refreshTimeline() self.pushButton_3.setEnabled(False) def loadCaseData(self): filename = '%s/system/controlDict' % self.currentFolder backupFile(filename) self.parsedData = ParsedParameterFile(filename, createZipped=False) self.tracersData = [] if 'functions' in self.parsedData.getValueDict().keys(): for key in self.parsedData['functions'].keys(): if self.parsedData['functions'][key][ 'type'] == 'scalarTransport': tracer = {} tracer['name'] = key tracer['patchName'] = self.parsedData['functions'][key][ 'patchName'] tracer['startTime'] = self.parsedData['functions'][key][ 'fvOptions']['S']['timeStart'] #TODO: cargar aca if tracer['patchName'] == 'box': tracer['p0'] = self.parsedData['functions'][key][ 'fvOptions']['S']['p0'] tracer['p1'] = self.parsedData['functions'][key][ 'fvOptions']['S']['p1'] self.tracersData.append(tracer) if self.patches == []: boundaries = BoundaryDict(str(self.currentFolder)) self.patches = boundaries.patches() for ipatch in self.patches: if boundaries[ipatch]['type'] == 'empty': self.emptys.append(ipatch) self.pushButton_3.setEnabled(True) def refreshTable(self): for ii in range(self.tableWidget.rowCount() - 1, -1, -1): self.tableWidget.removeRow(ii) for i in range(len(self.tracersData)): self.tableWidget.insertRow(i) item1 = QtGui.QTableWidgetItem() item2 = QtGui.QTableWidgetItem() item3 = QtGui.QTableWidgetItem() item4 = QtGui.QTableWidgetItem() wdg1 = QtGui.QLineEdit() wdg2 = QtGui.QComboBox() wdg3 = QtGui.QLineEdit() wdg4 = QtGui.QLineEdit() wdg2.addItems(list(set(self.patches) - set(self.emptys))) wdg2.addItem('box') wdg2.setObjectName(str(i)) wdg1.setText(str(self.tracersData[i]['startTime'])) wdg2.setCurrentIndex( wdg2.findText(self.tracersData[i]['patchName'])) #TODO: Hay que ver como cagarlo del archivo, preguntar a juan wdg3.setText(str(self.tracersData[i]['p0'])) if self.tracersData[ i]['patchName'] == 'box' else wdg3.setText("(0 0 0)") wdg4.setText(str(self.tracersData[i]['p1'])) if self.tracersData[ i]['patchName'] == 'box' else wdg4.setText("(0 0 0)") wdg3.setEnabled(False) if self.tracersData[i][ 'patchName'] != 'box' else wdg3.setEnabled(True) wdg4.setEnabled(False) if self.tracersData[i][ 'patchName'] != 'box' else wdg4.setEnabled(True) QtCore.QObject.connect( wdg2, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.change_combobox) wdg3.setValidator( QtGui.QRegExpValidator( QtCore.QRegExp( "\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}" ))) wdg4.setValidator( QtGui.QRegExpValidator( QtCore.QRegExp( "\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}" ))) QtCore.QObject.connect( wdg1, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect( wdg2, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.checkAccept) QtCore.QObject.connect( wdg3, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect( wdg4, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) self.tableWidget.setItem(i, 0, item1) self.tableWidget.setCellWidget(i, 0, wdg1) self.tableWidget.setItem(i, 1, item2) self.tableWidget.setCellWidget(i, 1, wdg2) self.tableWidget.setItem(i, 2, item3) self.tableWidget.setCellWidget(i, 2, wdg3) self.tableWidget.setItem(i, 3, item4) self.tableWidget.setCellWidget(i, 3, wdg4) self.pushButton_3.setEnabled(True) def refreshTimeline(self): if not self.firstPlot: self.figureLayout.removeWidget(self.canvas) self.canvas.destroy() self.canvas.close() self.firstPlot = False fig = Figure((2.0, 1.5), dpi=100) self.canvas = FigureCanvas(fig) #self.canvas.setParent(self) self.ax = fig.add_subplot(111) self.ax.clear() #levantar el controlDict y ver los tracers Tf = float(self.parsedData['endTime']) T = float(self.currtime) dT = float(self.parsedData['deltaT']) self.ax.set_ylim(0, 1.1) self.ax.set_xlim(-10 * dT, Tf) self.ax.plot([0, T - dT, T, T + dT, Tf], [0, 0, 1, 0, 0], 'k', marker='o', label='Current Time') i = 0 for itracer in self.tracersData: Tini = float(itracer['startTime']) if float(itracer['startTime']) < T: Tini = T self.ax.plot([0, Tini, Tini + dT, Tf], [0, 0, 1, 1], self.colors[i % 6], label=itracer['name']) i = i + 1 self.ax.set_title('Timeline') self.ax.set_xlabel('Time [s]') self.ax.set_ylabel('Event') self.ax.legend(loc=0, fontsize='small') self.figureLayout.addWidget(self.canvas) self.pushButton_3.setEnabled(True) return def change_combobox(self): name = str(self.sender().objectName()) c1 = self.tableWidget.cellWidget(int(name), 2) c2 = self.tableWidget.cellWidget(int(name), 3) if self.sender().currentText() == 'box': c1.setEnabled(True) c2.setEnabled(True) else: c1.setEnabled(False) c2.setEnabled(False) print 'done' return def newTracer(self): i = self.tableWidget.rowCount() self.tableWidget.insertRow(i) item1 = QtGui.QTableWidgetItem() item2 = QtGui.QTableWidgetItem() item3 = QtGui.QTableWidgetItem() item4 = QtGui.QTableWidgetItem() wdg1 = QtGui.QLineEdit() wdg2 = QtGui.QComboBox() wdg3 = QtGui.QLineEdit() wdg4 = QtGui.QLineEdit() wdg2.addItems(list(set(self.patches) - set(self.emptys))) wdg2.addItem('box') wdg2.setObjectName(str(i)) wdg3.setEnabled(False) wdg4.setEnabled(False) wdg1.setText('0') wdg3.setText('(0 0 0)') wdg4.setText('(0 0 0)') QtCore.QObject.connect( wdg2, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.change_combobox) wdg3.setValidator( QtGui.QRegExpValidator( QtCore.QRegExp( "\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}" ))) wdg4.setValidator( QtGui.QRegExpValidator( QtCore.QRegExp( "\({1}-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\s-?\d+\.?\d*(e-?\d)?\){1}" ))) QtCore.QObject.connect( wdg1, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect( wdg2, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.checkAccept) QtCore.QObject.connect( wdg3, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) QtCore.QObject.connect( wdg4, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.checkAccept) self.tableWidget.setItem(i, 0, item1) self.tableWidget.setCellWidget(i, 0, wdg1) self.tableWidget.setItem(i, 1, item2) self.tableWidget.setCellWidget(i, 1, wdg2) self.tableWidget.setItem(i, 2, item3) self.tableWidget.setCellWidget(i, 2, wdg3) self.tableWidget.setItem(i, 3, item4) self.tableWidget.setCellWidget(i, 3, wdg4) self.pushButton_3.setEnabled(True) def removeTracer(self): ii = self.tableWidget.currentRow() if ii == -1: QtGui.QMessageBox.about(self, "ERROR", "No tracer selected") return w = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Removing", "Do you want to remove tracer data?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) ret = w.exec_() if (QtGui.QMessageBox.Yes == ret): self.tableWidget.removeRow(ii) self.drawTracers() self.pushButton_3.setEnabled(False) return def saveCaseData(self): saved = self.drawTracers(True) if saved: self.pushButton_3.setEnabled(False) def drawTracers(self, doTopoSet=False): #Estoy obligado a hacer esto antes porque si lo hago durante la escritura #de datos, me pueden quedar datos a mitad de escritura y corruptos for i in range(self.tableWidget.rowCount()): patchName = str(self.tableWidget.cellWidget(i, 1).currentText()) if patchName == 'box': if str(self.tableWidget.cellWidget( i, 2).text())[-1] != ')' or str( self.tableWidget.cellWidget(i, 3).text())[-1] != ')': tracer = 'T%s' % str(i) QtGui.QMessageBox.about( self, "Error", "Wrong regular expression in " + tracer + "!") return False for dd in self.tracersData: del self.parsedData['functions'][dd['name']] if 'functions' not in self.parsedData.getValueDict().keys(): self.parsedData['functions'] = {} patches = [] for i in range(self.tableWidget.rowCount()): patchName = str(self.tableWidget.cellWidget(i, 1).currentText()) newkey = 'T%s' % str(i) cellsetname = '%s_c' % newkey tracer = copy.deepcopy(dicc) tracer['fvOptions']['S']['timeStart'] = str( self.tableWidget.cellWidget(i, 0).text()) tracer['fvOptions']['S']['cellSet'] = cellsetname tracer['patchName'] = patchName if patchName == 'box': tracer['fvOptions']['S']['p0'] = {} if 'p0' not in tracer[ 'fvOptions']['S'].keys() else None tracer['fvOptions']['S']['p1'] = {} if 'p1' not in tracer[ 'fvOptions']['S'].keys() else None #TODO: Verificar que sea correcto el punto tracer['fvOptions']['S']['p0'] = str( self.tableWidget.cellWidget(i, 2).text()) tracer['fvOptions']['S']['p1'] = str( self.tableWidget.cellWidget(i, 3).text()) del tracer['fvOptions']['S']['scalarExplicitSetValueCoeffs'][ 'injectionRate']['T0'] tracer['fvOptions']['S']['scalarExplicitSetValueCoeffs'][ 'injectionRate'][newkey] = '1' self.parsedData['functions'][newkey] = tracer patches.append(patchName) self.parsedData.writeFile() if doTopoSet: ii = 0 cmd = 'cp %s/caseDicts/topoSetDict %s/system/.' % (os.path.dirname( os.path.realpath(__file__)), self.currentFolder) os.system(cmd) filename = '%s/system/topoSetDict' % self.currentFolder topoSetData = ParsedParameterFile(filename, createZipped=False) #armo el topoSet de manera de generar los cellSet deseados for i in range(self.tableWidget.rowCount()): newkey = 'T%s' % str(i) patchName = str( self.tableWidget.cellWidget(i, 1).currentText()) cellsetname = '%s_c' % newkey facesetname = '%s_f' % newkey if patchName != 'box': topoSetData['actions'].append(dic_patchToFace) topoSetData['actions'].append(dic_faceToCell) topoSetData['actions'][ii]['name'] = facesetname topoSetData['actions'][ii]['sourceInfo'][ 'name'] = patchName topoSetData['actions'][ii + 1]['name'] = cellsetname topoSetData['actions'][ ii + 1]['sourceInfo']['set'] = facesetname ii = ii + 2 else: p0 = str(self.tableWidget.cellWidget(i, 2).text()) p1 = str(self.tableWidget.cellWidget(i, 3).text()) topoSetData['actions'].append(copy.deepcopy(dic_boxToCell)) topoSetData['actions'][ii]['name'] = cellsetname topoSetData['actions'][ii]['sourceInfo'][ 'box'] = p0 + ' ' + p1 ii = ii + 1 topoSetData.writeFile() cmd = 'topoSet -case %s > %s/run_topoSet.log &' % ( self.currentFolder, self.currentFolder) self.threadtopoSet = ExampleThread(cmd) self.connect(self.threadtopoSet, QtCore.SIGNAL("finished()"), self.verifyCells) self.connect(self.threadtopoSet, QtCore.SIGNAL("finished()"), self.threadtopoSet.terminate) self.threadtopoSet.start() self.loadCaseData() self.refreshTable() self.refreshTimeline() return True def verifyCells(self): from os import listdir from os.path import isfile, join folder = '%s/constant/polyMesh/sets' % self.currentFolder files = [f for f in listdir(folder) if isfile(join(folder, f))] empties = [] for ifile in files: if '_c' in ifile: filename = folder + '/' + ifile cmd = "grep -in '(' %s" % filename proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() out = out.replace(":(", "").replace("\n", "") out = int(out) - 1 cmd = "awk \"NR==%s\" %s" % (str(out), filename) proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() out = out.replace("\n", "") if int(out) == 0: empties.append(ifile.replace("_c", "")) if empties != []: strempties = ' '.join(empties) w = QtGui.QMessageBox( QtGui.QMessageBox.Warning, "Warning", "The tracer(s) " + strempties + " generated 0 cells!") w.exec_() return def checkAccept(self): ready = True edits = self.findChildren(QtGui.QLineEdit) for E in edits: if E.isEnabled(): if not E.text(): ready = False if ready: self.pushButton_3.setEnabled(True) else: self.pushButton_3.setEnabled(False)