def __init__(self, currentFolder): figureTracersUI.__init__(self) self.currentFolder = currentFolder self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False) [self.timedir,self.fields,bas] = currentFields(self.currentFolder) filename = '%s/system/controlDict'%self.currentFolder 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'] self.tracersData.append(tracer) for tracer in self.tracersData: item = QtGui.QListWidgetItem() item.setCheckState(QtCore.Qt.Unchecked) item.setText(tracer['name']) self.listWidget.addItem(item) from PyFoam.RunDictionary.BoundaryDict import BoundaryDict boundaries = BoundaryDict(str(self.currentFolder)) for ipatch in boundaries.getValueDict(): if boundaries[ipatch]['type'] != 'empty': self.comboBox.addItem(ipatch)
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 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, False) for ifield in fields: filename = '%s/%s'%(timedir,ifield) fieldData = ParsedParameterFile(filename,createZipped=False) fieldData['boundaryField'] = {} for ipatch in boundaries.getValueDict(): if ipatch not in fieldData['boundaryField']: if boundaries[ipatch]['nFaces']==0: continue patchDict={} if ifield in unknowns: patchDict['type'] = 'zeroGradient' else: patchDict['type'] = 'calculated' fieldData['boundaryField'][ipatch] = patchDict fieldData.writeFile() return
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 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, False) for ifield in fields: filename = '%s/%s' % (timedir, ifield) fieldData = ParsedParameterFile(filename, createZipped=False) fieldData['boundaryField'] = {} for ipatch in boundaries.getValueDict(): if ipatch not in fieldData['boundaryField']: if boundaries[ipatch]['nFaces'] == 0: continue patchDict = {} if ifield in unknowns: patchDict['type'] = 'zeroGradient' else: patchDict['type'] = 'calculated' fieldData['boundaryField'][ipatch] = patchDict fieldData.writeFile() return
def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder #filling data [timedir,self.fields,currtime] = currentFields(str(self.currentFolder)) self.field_3.addItems(self.fields) self.boundaries = BoundaryDict(str(self.currentFolder)) self.bou_3.addItems(self.boundaries.patches())
def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder #filling data self.nproc = self.window().nproc [timedir, self.fields, currtime] = currentFields(str(self.currentFolder), nproc=self.nproc) self.field_3.clear() self.field_3.addItems(self.fields) self.boundaries = BoundaryDict(str(self.currentFolder)) self.bou_3.clear() self.bou_3.addItems(self.boundaries.patches())
def updateFieldFiles(self, timedir, fields, currtime): #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) filename2 = '%s/system/changeDictionaryPetroSym' % self.currentFolder fieldData2 = [] if os.path.isfile(filename2): fieldData2 = ParsedParameterFile(filename2, createZipped=False) for ifield in fields: filename = '%s/%s' % (timedir, ifield) fieldData = ParsedParameterFile(filename, createZipped=False) 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' else: patchDict['type'] = 'zeroGradient' else: patchDict['type'] = 'calculated' if fieldData2 == []: fieldData['boundaryField'][ipatch] = patchDict else: fieldData2['dictionaryReplacement'][ifield][ 'boundaryField'][ipatch] = patchDict # poner el campo interno uniforme en cero if types[ifield] == 'scalar': if fieldData2 == []: fieldData['internalField'] = 'uniform 0' else: fieldData2['dictionaryReplacement'][ifield][ 'internalField'] = 'uniform 0' elif types[ifield] == 'vector': if fieldData2 == []: fieldData['internalField'] = 'uniform (0 0 0)' else: fieldData2['dictionaryReplacement'][ifield][ 'internalField'] = 'uniform (0 0 0)' fieldData.writeFile() if fieldData2 != []: fieldData2.writeFile() return
def __init__(self, folder, nproc): self.currentFolder = folder bcUI.__init__(self) self.icones = {} self.icones['wall'] = QtGui.QIcon() self.icones['wall'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/wall16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['empty'] = QtGui.QIcon() self.icones['empty'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/empty16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['patch'] = QtGui.QIcon() self.icones['patch'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/patch16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclic'] = QtGui.QIcon() self.icones['cyclic'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/cyclic16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclicAMI'] = QtGui.QIcon() self.icones['cyclicAMI'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/cyclicAMI16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['wedge'] = QtGui.QIcon() self.icones['wedge'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/wedge16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['symmetry'] = QtGui.QIcon() self.icones['symmetry'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/symmetry16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.boundaries = BoundaryDict(str(self.currentFolder)) self.nproc = nproc #veo los campos que tengo en el directorio inicial [self.timedir, self.fields, self.currtime] = currentFields(self.currentFolder, nproc=self.nproc) #print self.fields self.loadData() self.comboBox.setEnabled(False)
def testBoundaryWrite(self): bnd = BoundaryDict(self.dest) test1 = {"type": "wall", "nFaces": 0, "startFace": 666} bnd["testIt"] = test1 self.assertEqual(len(bnd.patches()), 6) bnd["leftWall"] = test1 self.assertEqual(len(bnd.patches()), 6) test2 = {"type": "wall", "Faces": 0, "startFace": 666} try: bnd["nix"] = test2 self.fail() except PyFoamException: pass
def testBoundaryWrite(self): bnd=BoundaryDict(self.dest) test1={"type":"wall" , "nFaces":0,"startFace":666} bnd["testIt"]=test1 self.assertEqual(len(bnd.patches()),6) bnd["leftWall"]=test1 self.assertEqual(len(bnd.patches()),6) test2={"type":"wall" , "Faces":0,"startFace":666} try: bnd["nix"]=test2 self.fail() except PyFoamException: pass
def updateFieldFiles(self,timedir,fields,currtime): #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) filename2 = '%s/system/changeDictionaryPetroSym'%self.currentFolder fieldData2 = [] if os.path.isfile(filename2): fieldData2 = ParsedParameterFile(filename2,createZipped=False) for ifield in fields: filename = '%s/%s'%(timedir,ifield) fieldData = ParsedParameterFile(filename,createZipped=False) 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' else: patchDict['type'] = 'zeroGradient' else: patchDict['type'] = 'calculated' if fieldData2==[]: fieldData['boundaryField'][ipatch] = patchDict else: fieldData2['dictionaryReplacement'][ifield]['boundaryField'][ipatch] = patchDict # poner el campo interno uniforme en cero if types[ifield] == 'scalar': if fieldData2==[]: fieldData['internalField'] = 'uniform 0' else: fieldData2['dictionaryReplacement'][ifield]['internalField'] = 'uniform 0' elif types[ifield] == 'vector': if fieldData2==[]: fieldData['internalField'] = 'uniform (0 0 0)' else: fieldData2['dictionaryReplacement'][ifield]['internalField'] = 'uniform (0 0 0)' fieldData.writeFile() if fieldData2!=[]: fieldData2.writeFile() return
def __init__(self,folder,nproc): self.currentFolder = folder bcUI.__init__(self) self.icones = {} self.icones['wall'] = QtGui.QIcon() self.icones['wall'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/wall16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['empty'] = QtGui.QIcon() self.icones['empty'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/empty16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['patch'] = QtGui.QIcon() self.icones['patch'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/patch16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclic'] = QtGui.QIcon() self.icones['cyclic'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/cyclic16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclicAMI'] = QtGui.QIcon() self.icones['cyclicAMI'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/cyclicAMI16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['wedge'] = QtGui.QIcon() self.icones['wedge'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/wedge16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['symmetry'] = QtGui.QIcon() self.icones['symmetry'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/symmetry16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.boundaries = BoundaryDict(str(self.currentFolder)) self.nproc = nproc #veo los campos que tengo en el directorio inicial [self.timedir,self.fields,self.currtime] = currentFields(self.currentFolder,nproc=self.nproc) #print self.fields self.loadData() self.comboBox.setEnabled(False)
def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder # filling data self.nproc = self.window().nproc [timedir, self.fields, currtime] = currentFields(str(self.currentFolder), nproc=self.nproc) self.field_3.clear() self.field_3.addItems(self.fields) self.boundaries = BoundaryDict(str(self.currentFolder)) self.bou_3.clear() self.bou_3.addItems(self.boundaries.patches())
def boundary_dict_path(self): return BoundaryDict(self.path).realName()
def boundary_dict(self): return BoundaryDict(self.path)
def testBoundaryRead(self): bnd=BoundaryDict(self.dest) self.assertEqual(bnd["walls"]["type"],"wall") self.assertEqual(bnd["walls"]["nFaces"],78) self.assertEqual(len(bnd.patches()),4) self.assertEqual(len(bnd.patches(patchType="patch")),2)
def run(self): fName=self.parser.getArgs()[0] try: dictFile=ParsedParameterFile(fName,backup=False) except IOError: e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e' self.error("Problem with file",fName,":",e) fName=path.abspath(fName) case=path.dirname(path.dirname(fName)) region=None if not SolutionDirectory(case,archive=None,paraviewLink=False).isValid(): # checking for a multi-region case case=path.dirname(case) region=path.basename(path.dirname(fName)) print_(case,region) if region not in SolutionDirectory(case,archive=None,paraviewLink=False).getRegions(): self.error(region,"is not a valid region in the case",case) if self.opts.filter==None: flter=re.compile(".+") else: flter=re.compile(self.opts.filter) boundaries=dictFile["boundaryField"] try: bFile=BoundaryDict(case,region=region) except IOError: e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e' self.error("Problem reading the boundary file:",e) if self.opts.clear: for b in list(boundaries.keys()): if b not in bFile.patches(): if self.opts.verbose: print_("Deleting patch",b) del boundaries[b] if not self.opts.nocheck: for p in bFile.patches(): if p in boundaries: typ=boundaries[p]["type"] pTyp=bFile[p]["type"] if pTyp!="patch" and pTyp!="wall" and pTyp!=typ: if self.opts.fixtypes: if self.opts.verbose: print_("Fixing wall/patch patch",p) del boundaries[p] continue else: self.error("Inconsistent type for ",p,": Is",typ,"but should be",pTyp) if typ in ["symmetryPlane","empty","wedge","cyclic","processor"] and pTyp!=typ: if self.opts.fixtypes: if self.opts.verbose: print_("Fixing special patch",p) del boundaries[p] continue else: self.error("Inconsistent type for ",p,": Is",typ,"but should be some kind of patch type") for p in bFile.patches(): if (not p in boundaries or self.opts.overwrite) and flter.match(p): pTyp=bFile[p]["type"] if pTyp!="patch" and pTyp!="wall": tmp={"type":pTyp} else: tmp=eval(self.opts.default) if self.opts.verbose: print_("Writing",tmp,"to patch",p) boundaries[p]=tmp; if self.opts.test: print_(str(dictFile)) else: dictFile.writeFile() self.addToCaseLog(case)
def testBoundaryRead(self): bnd = BoundaryDict(self.dest) self.assertEqual(bnd["leftWall"]["type"], "wall") self.assertEqual(bnd["leftWall"]["nFaces"], 50) self.assertEqual(len(bnd.patches()), 5) self.assertEqual(len(bnd.patches(patchType="wall")), 3)
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 postproWidget(postproUI): def __init__(self, currentFolder): postproUI.__init__(self) def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder #filling data self.nproc = self.window().nproc [timedir, self.fields, currtime] = currentFields(str(self.currentFolder), nproc=self.nproc) self.field_3.clear() self.field_3.addItems(self.fields) self.boundaries = BoundaryDict(str(self.currentFolder)) self.bou_3.clear() self.bou_3.addItems(self.boundaries.patches()) def openParaview(self): os.system('paraFoam -builtin -case %s &' % self.currentFolder) def exportData(self): if self.nproc > 1: w = QtGui.QMessageBox( QtGui.QMessageBox.Information, "Error", "Data only can be exported in reconstructed cases") w.exec_() return tt = '' if self.time_4.currentText() == 'Latest Time': tt = '-latestTime' opt = str(self.comboBox.currentText()) filename = '%s/export.log' % self.currentFolder self.window().newLogTab('Export', filename) if opt == 'VTK': action = 'foamToVTK -case %s %s > %s &' % (self.currentFolder, tt, filename) elif opt == 'Fluent': action = 'foamMeshToFluent -case %s &' % (self.currentFolder) os.system(action) action = 'cp %s/caseDicts/foamDataToFluentDict %s/system/foamDataToFluentDict' % ( os.path.dirname( os.path.realpath(__file__)), self.currentFolder) os.system(action) parsedData = ParsedParameterFile('%s/system/foamDataToFluentDict' % self.currentFolder, createZipped=False) ii = 10 for ifield in self.fields: if ifield not in parsedData.getValueDict().keys(): parsedData[ifield] = ii ii = ii + 1 action = 'foamDataToFluent -case %s %s > %s &' % ( self.currentFolder, tt, filename) elif opt == 'Ensight': action = 'foamToEnsight -case %s %s > %s &' % (self.currentFolder, tt, filename) os.system(action) return def calculate1(self): tt = '' if self.time_1.currentText() == 'Latest Time': tt = '-latestTime' filename = '%s/field_calculation.log' % self.currentFolder self.window().newLogTab('Postpro Field', filename) if self.nproc <= 1: action = '%s -case %s %s > %s' % (apps[str( self.field_1.currentText())], self.currentFolder, tt, filename) else: action = 'mpirun -np %s %s -case %s %s -parallel > %s' % ( str(self.nproc), apps[str(self.field_1.currentText())], self.currentFolder, tt, filename) os.system(action) return def calculate2(self): tt = '' if self.time_2.currentText() == 'Latest Time': tt = '-latestTime' filename = '%s/walls_calculation.log' % self.currentFolder if self.field_2.currentText() == 'y Plus RAS': if not os.path.isfile( '%s/constant/RASProperties' % self.currentFolder): QtGui.QMessageBox(QtGui.QMessageBox.Information, "Caution", "Action can not be done!").exec_() return if self.field_2.currentText() == 'y Plus LES': if not os.path.isfile( '%s/constant/LESProperties' % self.currentFolder): QtGui.QMessageBox(QtGui.QMessageBox.Information, "Caution", "Action can not be done!").exec_() return self.window().newLogTab('Postpro Wall', filename) if self.nproc <= 1: action = '%s -case %s %s > %s' % (apps[str( self.field_2.currentText())], self.currentFolder, tt, filename) else: action = 'mpirun -np %s %s -case %s %s -parallel > %s' % ( str(self.nproc), apps[str(self.field_2.currentText())], self.currentFolder, tt, filename) os.system(action) return def calculate3(self): tt = '' if self.time_3.currentText() == 'Latest Time': tt = '-latestTime' filename = '%s/patch_calculation.log' % self.currentFolder self.window().newLogTab('Postpro Patch', filename) fieldName = str(self.field_3.currentText()) patchName = str(self.bou_3.currentText()) if self.nproc <= 1: action = '%s -case %s %s %s %s > %s &' % (apps[str( self.type_3.currentText())], self.currentFolder, tt, fieldName, patchName, filename) else: action = 'mpirun -np %s %s -case %s %s %s %s -parallel > %s &' % ( str(self.nproc), apps[str(self.type_3.currentText())], self.currentFolder, tt, fieldName, patchName, filename) os.system(action) return
""" from PyFoam.Basics.FoamOptionParser import FoamOptionParser from os import path import sys from PyFoam.RunDictionary.BoundaryDict import BoundaryDict from PyFoam.RunDictionary.MeshInformation import MeshInformation parse=FoamOptionParser(description=description,usage="%prog <caseDirectory> <boundaryName>") parse.parse(nr=2) fName=parse.getArgs()[0] bName=parse.getArgs()[1] boundary=BoundaryDict(fName) lastFace=MeshInformation(fName).nrOfFaces() if bName in boundary.patches(): print "Patch",bName,"already exists in file" sys.exit(-1) val={} val["type"]="wall" val["nFaces"]="0" val["startFace"]=str(lastFace) boundary[bName]=val boundary.writeFile()
from PyFoam.Basics.FoamOptionParser import FoamOptionParser from os import path import sys from PyFoam.RunDictionary.BoundaryDict import BoundaryDict from PyFoam.RunDictionary.MeshInformation import MeshInformation from PyFoam.ThirdParty.six import print_ parse=FoamOptionParser(description=description,usage="%prog <caseDirectory>") parse.parse(nr=1) fName=parse.getArgs()[0] boundary=BoundaryDict(fName) cleared=[] for b in boundary.patches(): if boundary[b]["nFaces"]==0: cleared.append(b) del boundary[b] if len(cleared)>0: print_("Cleared boundaries",", ".join(cleared)) boundary.writeFile() else: print_("No empty boundaries") # Should work with Python3 and Python2
class postproWidget(postproUI): def __init__(self, currentFolder): postproUI.__init__(self) def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder # filling data self.nproc = self.window().nproc [timedir, self.fields, currtime] = currentFields(str(self.currentFolder), nproc=self.nproc) self.field_3.clear() self.field_3.addItems(self.fields) self.boundaries = BoundaryDict(str(self.currentFolder)) self.bou_3.clear() self.bou_3.addItems(self.boundaries.patches()) def openParaview(self): os.system("paraFoam -builtin -case %s &" % self.currentFolder) def exportData(self): if self.nproc > 1: w = QtGui.QMessageBox( QtGui.QMessageBox.Information, "Error", "Data only can be exported in reconstructed cases" ) w.exec_() return tt = "" if self.time_4.currentText() == "Latest Time": tt = "-latestTime" opt = str(self.comboBox.currentText()) filename = "%s/export.log" % self.currentFolder self.window().newLogTab("Export", filename) if opt == "VTK": action = "foamToVTK -case %s %s > %s &" % (self.currentFolder, tt, filename) elif opt == "Fluent": action = "foamMeshToFluent -case %s &" % (self.currentFolder) os.system(action) action = "cp %s/caseDicts/foamDataToFluentDict %s/system/foamDataToFluentDict" % ( os.path.dirname(os.path.realpath(__file__)), self.currentFolder, ) os.system(action) parsedData = ParsedParameterFile("%s/system/foamDataToFluentDict" % self.currentFolder, createZipped=False) ii = 10 for ifield in self.fields: if ifield not in parsedData.getValueDict().keys(): parsedData[ifield] = ii ii = ii + 1 action = "foamDataToFluent -case %s %s > %s &" % (self.currentFolder, tt, filename) elif opt == "Ensight": action = "foamToEnsight -case %s %s > %s &" % (self.currentFolder, tt, filename) os.system(action) return def calculate1(self): tt = "" if self.time_1.currentText() == "Latest Time": tt = "-latestTime" filename = "%s/field_calculation.log" % self.currentFolder self.window().newLogTab("Postpro Field", filename) if self.nproc <= 1: action = "%s -case %s %s > %s" % (apps[str(self.field_1.currentText())], self.currentFolder, tt, filename) else: action = "mpirun -np %s %s -case %s %s -parallel > %s" % ( str(self.nproc), apps[str(self.field_1.currentText())], self.currentFolder, tt, filename, ) os.system(action) return def calculate2(self): tt = "" if self.time_2.currentText() == "Latest Time": tt = "-latestTime" filename = "%s/walls_calculation.log" % self.currentFolder if self.field_2.currentText() == "y Plus RAS": if not os.path.isfile("%s/constant/RASProperties" % self.currentFolder): QtGui.QMessageBox(QtGui.QMessageBox.Information, "Caution", "Action can not be done!").exec_() return if self.field_2.currentText() == "y Plus LES": if not os.path.isfile("%s/constant/LESProperties" % self.currentFolder): QtGui.QMessageBox(QtGui.QMessageBox.Information, "Caution", "Action can not be done!").exec_() return self.window().newLogTab("Postpro Wall", filename) if self.nproc <= 1: action = "%s -case %s %s > %s" % (apps[str(self.field_2.currentText())], self.currentFolder, tt, filename) else: action = "mpirun -np %s %s -case %s %s -parallel > %s" % ( str(self.nproc), apps[str(self.field_2.currentText())], self.currentFolder, tt, filename, ) os.system(action) return def calculate3(self): tt = "" if self.time_3.currentText() == "Latest Time": tt = "-latestTime" filename = "%s/patch_calculation.log" % self.currentFolder self.window().newLogTab("Postpro Patch", filename) fieldName = str(self.field_3.currentText()) patchName = str(self.bou_3.currentText()) if self.nproc <= 1: action = "%s -case %s %s %s %s > %s &" % ( apps[str(self.type_3.currentText())], self.currentFolder, tt, fieldName, patchName, filename, ) else: action = "mpirun -np %s %s -case %s %s %s %s -parallel > %s &" % ( str(self.nproc), apps[str(self.type_3.currentText())], self.currentFolder, tt, fieldName, patchName, filename, ) os.system(action) return
polyMesh/boundaries file """ from PyFoam.Basics.FoamOptionParser import FoamOptionParser from os import path import sys from PyFoam.RunDictionary.BoundaryDict import BoundaryDict from PyFoam.RunDictionary.MeshInformation import MeshInformation parse=FoamOptionParser(description=description,usage="%prog <caseDirectory>") parse.parse(nr=1) fName=parse.getArgs()[0] boundary=BoundaryDict(fName) cleared=[] for b in boundary.patches(): if boundary[b]["nFaces"]==0: cleared.append(b) del boundary[b] if len(cleared)>0: print "Cleared boundaries",", ".join(cleared) boundary.writeFile() else: print "No empty boundaries"
def doRegion(self, theRegion): ReST = RestructuredTextHelper(defaultHeading=self.opts.headingLevel) if self.opts.allRegions: print_( ReST.buildHeading("Region: ", theRegion, level=self.opts.headingLevel - 1)) sol = SolutionDirectory(self.parser.getArgs()[0], archive=None, parallel=self.opts.parallel, paraviewLink=False, region=theRegion) if self.opts.all: self.opts.caseSize = True self.opts.shortBCreport = True self.opts.longBCreport = True self.opts.dimensions = True self.opts.internal = True self.opts.linearSolvers = True self.opts.relaxationFactors = True self.opts.processorMatrix = True self.opts.decomposition = True if self.opts.time: try: self.opts.time = sol.timeName( sol.timeIndex(self.opts.time, minTime=True)) except IndexError: error("The specified time", self.opts.time, "doesn't exist in the case") print_("Using time t=" + self.opts.time + "\n") needsPolyBoundaries = False needsInitialTime = False if self.opts.longBCreport: needsPolyBoundaries = True needsInitialTime = True if self.opts.shortBCreport: needsPolyBoundaries = True needsInitialTime = True if self.opts.dimensions: needsInitialTime = True if self.opts.internal: needsInitialTime = True if self.opts.decomposition: needsPolyBoundaries = True defaultProc = None if self.opts.parallel: defaultProc = 0 if needsPolyBoundaries: proc = None boundary = BoundaryDict( sol.name, region=theRegion, time=self.opts.time, treatBinaryAsASCII=self.opts.boundaryTreatBinaryAsASCII, processor=defaultProc) boundMaxLen = 0 boundaryNames = [] for b in boundary: if b.find("procBoundary") != 0: boundaryNames.append(b) if self.opts.patches != None: tmp = boundaryNames boundaryNames = [] for b in tmp: for p in self.opts.patches: if fnmatch(b, p): boundaryNames.append(b) break if self.opts.expatches != None: tmp = boundaryNames boundaryNames = [] for b in tmp: keep = True for p in self.opts.expatches: if fnmatch(b, p): keep = False break if keep: boundaryNames.append(b) for b in boundaryNames: boundMaxLen = max(boundMaxLen, len(b)) boundaryNames.sort() if self.opts.time == None: procTime = "constant" else: procTime = self.opts.time if needsInitialTime: fields = {} if self.opts.time == None: try: time = sol.timeName(0) except IndexError: error("There is no timestep in the case") else: time = self.opts.time tDir = sol[time] nameMaxLen = 0 for f in tDir: try: fields[f.baseName()] = f.getContent( listLengthUnparsed=self.opts.longlist, treatBinaryAsASCII=self.opts.treatBinaryAsASCII, doMacroExpansion=self.opts.doMacros) nameMaxLen = max(nameMaxLen, len(f.baseName())) except PyFoamParserError: e = sys.exc_info()[ 1] # Needed because python 2.5 does not support 'as e' warning("Couldn't parse", f.name, "because of an error:", e, " -> skipping") fieldNames = list(fields.keys()) fieldNames.sort() if self.opts.caseSize: print_(ReST.heading("Size of the case")) nFaces = 0 nPoints = 0 nCells = 0 if self.opts.parallel: procs = list(range(sol.nrProcs())) print_("Accumulated from", sol.nrProcs(), "processors") else: procs = [None] for p in procs: info = MeshInformation(sol.name, processor=p, region=theRegion, time=self.opts.time) nFaces += info.nrOfFaces() nPoints += info.nrOfPoints() try: nCells += info.nrOfCells() except: nCells = "Not available" tab = ReST.table() tab[0] = ("Faces", nFaces) tab[1] = ("Points", nPoints) tab[2] = ("Cells", nCells) print_(tab) if self.opts.decomposition: print_(ReST.heading("Decomposition")) if sol.nrProcs() < 2: print_("This case is not decomposed") else: print_("Case is decomposed for", sol.nrProcs(), "processors") print_() nCells = [] nFaces = [] nPoints = [] for p in sol.processorDirs(): info = MeshInformation(sol.name, processor=p, region=theRegion, time=self.opts.time) nPoints.append(info.nrOfPoints()) nFaces.append(info.nrOfFaces()) nCells.append(info.nrOfCells()) digits = int( ceil( log10( max(sol.nrProcs(), max(nCells), max(nFaces), max(nPoints))))) + 2 nameLen = max(len("Points"), boundMaxLen) tab = ReST.table() tab[0] = ["CPU"] + list(range(sol.nrProcs())) tab.addLine() tab[1] = ["Points"] + nPoints tab[2] = ["Faces"] + nFaces tab[3] = ["Cells"] + nCells tab.addLine(head=True) nr = 3 for b in boundaryNames: nr += 1 tab[(nr, 0)] = b for i, p in enumerate(sol.processorDirs()): try: nFaces = ParsedBoundaryDict( sol.boundaryDict(processor=p, region=theRegion, time=self.opts.time), treatBinaryAsASCII=self.opts. boundaryTreatBinaryAsASCII)[b]["nFaces"] except IOError: nFaces = ParsedBoundaryDict( sol.boundaryDict(processor=p, region=theRegion), treatBinaryAsASCII=self.opts. boundaryTreatBinaryAsASCII)[b]["nFaces"] except KeyError: nFaces = 0 tab[(nr, i + 1)] = nFaces print_(tab) if self.opts.longBCreport: print_(ReST.heading("The boundary conditions for t =", time)) for b in boundaryNames: print_( ReST.buildHeading("Boundary: ", b, level=self.opts.headingLevel + 1)) bound = boundary[b] print_(":Type:\t", bound["type"]) if "physicalType" in bound: print_(":Physical:\t", bound["physicalType"]) print_(":Faces:\t", bound["nFaces"]) print_() heads = ["Field", "type"] tab = ReST.table() tab[0] = heads tab.addLine(head=True) for row, fName in enumerate(fieldNames): tab[(row + 1, 0)] = fName f = fields[fName] if "boundaryField" not in f: tab[(row + 1, 1)] = "Not a field file" elif b not in f["boundaryField"]: tab[(row + 1, 1)] = "MISSING !!!" else: bf = f["boundaryField"][b] for k in bf: try: col = heads.index(k) except ValueError: col = len(heads) tab[(0, col)] = k heads.append(k) cont = str(bf[k]) if type(bf[k]) == Field: if bf[k].isBinary(): cont = bf[k].binaryString() if cont.find("\n") >= 0: tab[(row + 1, col)] = cont[:cont.find("\n")] + "..." else: tab[(row + 1, col)] = cont print_(tab) if self.opts.shortBCreport: print_(ReST.heading("Table of boundary conditions for t =", time)) types = {} hasPhysical = False for b in boundary: if "physicalType" in boundary[b]: hasPhysical = True types[b] = {} for fName in fields: f = fields[fName] try: if b not in f["boundaryField"]: types[b][fName] = "MISSING" else: types[b][fName] = f["boundaryField"][b]["type"] except KeyError: types[b][fName] = "Not a field" tab = ReST.table() tab[0] = [""] + boundaryNames tab.addLine() tab[(1, 0)] = "Patch Type" for i, b in enumerate(boundaryNames): tab[(1, i + 1)] = boundary[b]["type"] nr = 2 if hasPhysical: tab[(nr, 0)] = "Physical Type" for i, b in enumerate(boundaryNames): if "physicalType" in boundary[b]: tab[(nr, i + 1)] = boundary[b]["physicalType"] nr += 1 tab[(nr, 0)] = "Length" for i, b in enumerate(boundaryNames): tab[(nr, i + 1)] = boundary[b]["nFaces"] nr += 1 tab.addLine(head=True) for fName in fieldNames: tab[(nr, 0)] = fName for i, b in enumerate(boundaryNames): tab[(nr, i + 1)] = types[b][fName] nr += 1 print_(tab) if self.opts.dimensions: print_(ReST.heading("Dimensions of fields for t =", time)) tab = ReST.table() tab[0] = ["Name"] + "[ kg m s K mol A cd ]".split()[1:-1] tab.addLine(head=True) for i, fName in enumerate(fieldNames): f = fields[fName] try: dim = str(f["dimensions"]).split()[1:-1] except KeyError: dim = ["-"] * 7 tab[i + 1] = [fName] + dim print_(tab) if self.opts.internal: print_(ReST.heading("Internal value of fields for t =", time)) tab = ReST.table() tab[0] = ["Name", "Value"] tab.addLine(head=True) for i, fName in enumerate(fieldNames): f = fields[fName] try: if f["internalField"].isBinary(): val = f["internalField"].binaryString() else: cont = str(f["internalField"]) if cont.find("\n") >= 0: val = cont[:cont.find("\n")] + "..." else: val = cont except KeyError: val = "Not a field file" tab[i + 1] = [fName, val] print_(tab) if self.opts.processorMatrix: print_(ReST.heading("Processor matrix")) if sol.nrProcs() < 2: print_("This case is not decomposed") else: matrix = [[ 0, ] * sol.nrProcs() for i in range(sol.nrProcs())] for i, p in enumerate(sol.processorDirs()): try: bound = ParsedBoundaryDict( sol.boundaryDict(processor=p, region=theRegion, time=self.opts.time), treatBinaryAsASCII=self.opts. boundaryTreatBinaryAsASCII) except IOError: bound = ParsedBoundaryDict( sol.boundaryDict(processor=p, treatBinaryAsASCII=self.opts. boundaryTreatBinaryAsASCII, region=theRegion), treatBinaryAsASCII=self.opts. boundaryTreatBinaryAsASCII) for j in range(sol.nrProcs()): name = "procBoundary%dto%d" % (j, i) name2 = "procBoundary%dto%d" % (i, j) if name in bound: matrix[i][j] = bound[name]["nFaces"] if name2 in bound: matrix[i][j] = bound[name2]["nFaces"] print_("Matrix of processor interactions (faces)") print_() tab = ReST.table() tab[0] = ["CPU"] + list(range(sol.nrProcs())) tab.addLine(head=True) for i, col in enumerate(matrix): tab[i + 1] = [i] + matrix[i] print_(tab) if self.opts.linearSolvers: print_(ReST.heading("Linear Solvers")) linTable = ReST.table() fvSol = ParsedParameterFile( path.join(sol.systemDir(), "fvSolution"), treatBinaryAsASCII=self.opts.treatBinaryAsASCII) allInfo = {} for sName in fvSol["solvers"]: raw = fvSol["solvers"][sName] info = {} if type(raw) in [dict, DictProxy]: # fvSolution format in 1.7 try: info["solver"] = raw["solver"] except KeyError: info["solver"] = "<none>" solverData = raw else: info["solver"] = raw[0] solverData = raw[1] if type(solverData) in [dict, DictProxy]: try: info["tolerance"] = solverData["tolerance"] except KeyError: info["tolerance"] = 1. try: info["relTol"] = solverData["relTol"] except KeyError: info["relTol"] = 0. else: # the old (pre-1.5) fvSolution-format info["tolerance"] = solverData info["relTol"] = raw[2] allInfo[sName] = info linTable[0] = ["Name", "Solver", "Abs. Tolerance", "Relative Tol."] linTable.addLine(head=True) nr = 0 for n, i in iteritems(allInfo): nr += 1 linTable[nr] = (n, i["solver"], i["tolerance"], i["relTol"]) print_(linTable) if self.opts.relaxationFactors: print_(ReST.heading("Relaxation")) fvSol = ParsedParameterFile( path.join(sol.systemDir(), "fvSolution"), treatBinaryAsASCII=self.opts.treatBinaryAsASCII) if "relaxationFactors" in fvSol: relax = fvSol["relaxationFactors"] tab = ReST.table() tab[0] = ["Name", "Factor"] tab.addLine(head=True) nr = 0 if "fields" in relax or "equations" in relax: # New syntax for k in ["fields", "equations"]: if k in relax: for n, f in iteritems(relax[k]): nr += 1 tab[nr] = [k + ": " + n, f] else: for n, f in iteritems(relax): nr += 1 tab[nr] = [n, f] print_(tab) else: print_("No relaxation factors defined for this case")
from os import path import sys from PyFoam.RunDictionary.BoundaryDict import BoundaryDict from PyFoam.RunDictionary.MeshInformation import MeshInformation from PyFoam.ThirdParty.six import print_ parse = FoamOptionParser(description=description, usage="%prog <caseDirectory> <boundaryName>") parse.parse(nr=2) fName = parse.getArgs()[0] bName = parse.getArgs()[1] boundary = BoundaryDict(fName) lastFace = MeshInformation(fName).nrOfFaces() if bName in boundary.patches(): print_("Patch", bName, "already exists in file") sys.exit(-1) val = {} val["type"] = "wall" val["nFaces"] = "0" val["startFace"] = str(lastFace) boundary[bName] = val boundary.writeFile()
class postproWidget(postproUI): def __init__(self,currentFolder): postproUI.__init__(self) def setCurrentFolder(self, currentFolder): self.currentFolder = currentFolder #filling data [timedir,self.fields,currtime] = currentFields(str(self.currentFolder)) self.field_3.clear() self.field_3.addItems(self.fields) self.boundaries = BoundaryDict(str(self.currentFolder)) self.bou_3.clear() self.bou_3.addItems(self.boundaries.patches()) def openParaview(self): os.system('paraFoam -builtin -case %s &'%self.currentFolder) def exportData(self): opt = str(self.comboBox.currentText()) filename = '%s/export.log'%self.currentFolder self.window().newLogTab('Export',filename) if opt=='VTK': action = 'foamToVTK -case %s > %s &' %(self.currentFolder,filename) elif opt=='Fluent': action = 'foamMeshToFluent -case %s &' %(self.currentFolder) os.system(action) 'cp caseDicts/foamDataToFluentDict %s/system/foamDataToFluentDict'%self.currentFolder os.system(action) parsedData = ParsedParameterFile('%s/system/foamDataToFluentDict'%self.currentFolder,createZipped=False) ii = 10 for ifield in self.fields: if ifield not in parsedData.getValueDict().keys(): parsedData[ifield] = ii ii = ii + 1 action = 'foamDataToFluent -case %s > %s &' %(self.currentFolder,filename) elif opt=='Ensight': action = 'foamToEnsight -case %s > %s &' %(self.currentFolder,filename) os.system(action) return def calculate1(self): tt = '' if self.time_1.currentText()=='Latest Time': tt = '-latestTime' filename = '%s/field_calculation.log'%self.currentFolder self.window().newLogTab('Postpro Field',filename) action = '%s -case %s %s > %s'%(apps[str(self.field_1.currentText())],self.currentFolder, tt, filename) os.system(action) return def calculate2(self): tt = '' if self.time_2.currentText()=='Latest Time': tt = '-latestTime' filename = '%s/walls_calculation.log'%self.currentFolder if self.field_2.currentText()=='y Plus RAS': if not os.path.isfile('%s/constant/RASProperties'%self.currentFolder): QtGui.QMessageBox(QtGui.QMessageBox.Information, "Caution", "Action can not be done!").exec_() return if self.field_2.currentText()=='y Plus LES': if not os.path.isfile('%s/constant/LESProperties'%self.currentFolder): QtGui.QMessageBox(QtGui.QMessageBox.Information, "Caution", "Action can not be done!").exec_() return self.window().newLogTab('Postpro Wall',filename) action = '%s -case %s %s > %s'%(apps[str(self.field_2.currentText())],self.currentFolder, tt, filename) os.system(action) return def calculate3(self): tt = '' if self.time_3.currentText()=='Latest Time': tt = '-latestTime' filename = '%s/patch_calculation.log'%self.currentFolder self.window().newLogTab('Postpro Patch',filename) fieldName = str(self.field_3.currentText()) patchName = str(self.bou_3.currentText()) action = '%s -case %s %s %s %s > %s &' %(apps[str(self.type_3.currentText())],self.currentFolder,tt,fieldName,patchName,filename) os.system(action) return
def testBoundaryRead(self): bnd = BoundaryDict(self.dest) self.assertEqual(bnd["walls"]["type"], "wall") self.assertEqual(bnd["walls"]["nFaces"], 78) self.assertEqual(len(bnd.patches()), 4) self.assertEqual(len(bnd.patches(patchType="patch")), 2)
class bcWidget(bcUI): def __init__(self,folder,nproc): self.currentFolder = folder bcUI.__init__(self) self.icones = {} self.icones['wall'] = QtGui.QIcon() self.icones['wall'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/wall16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['empty'] = QtGui.QIcon() self.icones['empty'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/empty16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['patch'] = QtGui.QIcon() self.icones['patch'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/patch16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclic'] = QtGui.QIcon() self.icones['cyclic'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/cyclic16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclicAMI'] = QtGui.QIcon() self.icones['cyclicAMI'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/cyclicAMI16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['wedge'] = QtGui.QIcon() self.icones['wedge'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/wedge16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['symmetry'] = QtGui.QIcon() self.icones['symmetry'].addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/symmetry16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.boundaries = BoundaryDict(str(self.currentFolder)) self.nproc = nproc #veo los campos que tengo en el directorio inicial [self.timedir,self.fields,self.currtime] = currentFields(self.currentFolder,nproc=self.nproc) #print self.fields self.loadData() self.comboBox.setEnabled(False) def loadData(self): self.listWidget.clear() for ipatch in self.boundaries.patches(): Item = QtGui.QListWidgetItem() Item.setIcon(self.icones[self.boundaries[ipatch]['type']]) Item.setText(_translate("bcWidget", ipatch, None)) self.listWidget.addItem(Item) self.pushButton.setEnabled(False) self.addTabs() def changeSelection(self): ipatch = str(self.listWidget.currentItem().text()) self.comboBox.clear() self.comboBox.addItems(prototypes[self.boundaries[ipatch]['type']]) self.addTabs(ipatch) return 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() fileDict = '%s/system/changeDictionaryPetroSym'%self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict,createZipped=False) for ifield in self.fields: if ifield not in unknowns: continue widget = QtGui.QWidget() layout = QtGui.QVBoxLayout(widget) if ipatch: if dictDict==[]: filename = '%s/%s'%(self.timedir,ifield) parsedData = ParsedParameterFile(filename,listLengthUnparsed=20,createZipped=False) thisPatch = parsedData['boundaryField'][ipatch] else: thisPatch = dictDict['dictionaryReplacement'][ifield]['boundaryField'][ipatch] newComboBox = QtGui.QComboBox() newComboBox.addItems(types[self.boundaries[ipatch]['type']][ifield]) #aca hay que llamar a este evento solo si se cambia index = newComboBox.findText(thisPatch['type']) newComboBox.setCurrentIndex(index) if index!=-1 else None layout.addWidget(newComboBox) extraInfo = extras[ifield][thisPatch['type']] self.addExtraInfo(layout,extraInfo) QtCore.QObject.connect(newComboBox, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.onChangeComboType) #cargo los datos desde el diccionario L = range(layout.count()) L = L[1:-1] iExtra = 0 for l in L: layout2 = layout.itemAt(l).layout() if layout2: if layout2.itemAt(1).widget().currentText() != 'table': data = str(thisPatch[extraInfo[iExtra*4]]) data = data.replace('(','').replace(')','').replace('[','').replace(']','').replace(',','').replace('\'','').split() if layout2.count()==3: layout2.itemAt(1).widget().setCurrentIndex(layout2.itemAt(1).widget().findText(data[0])) layout2.itemAt(2).widget().setText(data[1]) else: layout2.itemAt(1).widget().setCurrentIndex(layout2.itemAt(1).widget().findText(data[0])) layout2.itemAt(2).widget().setText(data[1]) layout2.itemAt(3).widget().setText(data[2]) layout2.itemAt(4).widget().setText(data[3]) else: None #determinar que hacer si quiero cargar una table!!! #('table', [[0, 0.0], [1e6-0.01, 0.0], [1e6, 1.0], [1e6, 1.0]]) #tabla = self.getTabla(itab) #parsedData['boundaryField'][ipatch][extraInfo[iExtra*4]] = ('table',tabla) iExtra = iExtra+1 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 onChangeComboType(self): ii = self.tabWidget.currentIndex() ifield = str(self.tabWidget.tabText(ii)) widget = self.tabWidget.currentWidget() if widget: itype = str(widget.findChildren(QtGui.QComboBox)[0].currentText()) layout = widget.findChildren(QtGui.QVBoxLayout)[0] self.clearLayout(layout, 1) self.addExtraInfo(layout,extras[ifield][itype]) self.checkData() def onEditValue(self): return 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 addExtraInfo(self,layout,extraInfo): if extraInfo != []: for i in range(len(extraInfo)/4): layout2 = QtGui.QHBoxLayout() label = QtGui.QLabel() label.setText('%s %s'%(extraInfo[i*4],extraInfo[i*4+1])) layout2.addWidget(label) if extraInfo[i*4+2]: cb = QtGui.QComboBox() cb.addItems(extraInfo[i*4+2]) layout2.addWidget(cb) for j in range(extraInfo[i*4+3]): ledit = QtGui.QLineEdit() ledit.setValidator(QtGui.QDoubleValidator()) layout2.addWidget(ledit) QtCore.QObject.connect(ledit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.checkData) layout.addLayout(layout2) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) layout.addItem(spacerItem) def changePrototype(self): return def saveBCs(self): ipatch = str(self.listWidget.currentItem().text()) fileDict = '%s/system/changeDictionaryPetroSym'%self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict,createZipped=False) for itab in range(self.tabWidget.count()): ifield = str(self.tabWidget.tabText(itab)) itype = str(self.tabWidget.widget(itab).findChildren(QtGui.QComboBox)[0].currentText()) layout = self.tabWidget.widget(itab).findChildren(QtGui.QVBoxLayout)[0] if dictDict == []: filename = '%s/%s'%(self.timedir,ifield) parsedData = ParsedParameterFile(filename,listLengthUnparsed=20,createZipped=False) thisPatch = parsedData['boundaryField'][ipatch] else: thisPatch = dictDict['dictionaryReplacement'][ifield]['boundaryField'][ipatch] thisPatch = {} thisPatch['type'] = itype if itype == 'zeroGradient': thisPatch['ZZvalue'] = '0' #debo tomar los valores extras, si los tiene extraInfo = extras[ifield][itype] L = range(layout.count()) L = L[1:-1] iExtra = 0 #print ipatch for l in L: layout2 = layout.itemAt(l).layout() if layout2: if layout2.itemAt(1).widget().currentText() != 'table': if layout2.count()==3: thisPatch[extraInfo[iExtra*4]] = '%s %s' %(layout2.itemAt(1).widget().currentText(),layout2.itemAt(2).widget().text()) else: thisPatch[extraInfo[iExtra*4]] = '%s (%s %s %s)' %(layout2.itemAt(1).widget().currentText(),layout2.itemAt(2).widget().text(),layout2.itemAt(3).widget().text(),layout2.itemAt(4).widget().text()) else: #determinar que hacer si quiero cargar una table!!! #('table', [[0, 0.0], [1e6-0.01, 0.0], [1e6, 1.0], [1e6, 1.0]]) tabla = self.getTabla(itab) thisPatch[extraInfo[iExtra*4]] = ('table',tabla) iExtra = iExtra+1 if dictDict == []: parsedData['boundaryField'][ipatch] = thisPatch parsedData.writeFile() else: dictDict['dictionaryReplacement'][ifield]['boundaryField'][ipatch] = thisPatch 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] = {} dictDictBak['dictionaryReplacement'][ikey]['boundaryField'] = dictDict['dictionaryReplacement'][ikey]['boundaryField'] 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.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) self.pushButton.setEnabled(False) return def getTable(self,itab): table = [[0, 0],[1, 0]] return table 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) def changePatchType(self,item): texto = str(item.text()) w = bcPatch(self.boundaries[texto]['type']) result = w.exec_() if result: patchType = w.getPatchType() self.boundaries[texto]['type'] = patchType self.boundaries.writeFile() fileDict = '%s/system/changeDictionaryPetroSym'%self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict,createZipped=False) for ifield in self.fields: if dictDict==[]: filename = '%s/%s'%(self.timedir,ifield) fieldData = ParsedParameterFile(filename,listLengthUnparsed=20,createZipped=False) else: fieldData = dictDict['dictionaryReplacement'][ifield] newDict = {} if patchType == 'empty': newDict['type'] = 'empty' newDict['ZZvalue'] = '0' else: if ifield in unknowns: newDict['type'] = 'zeroGradient' newDict['ZZvalue'] = '0' else: newDict['type'] = 'calculated' newDict['ZZvalue'] = '0' fieldData['boundaryField'][texto] = newDict if dictDict==[]: fieldData.writeFile() else: dictDict['dictionaryReplacement'][ifield] = fieldData 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] = {} dictDictBak['dictionaryReplacement'][ikey]['boundaryField'] = dictDict['dictionaryReplacement'][ikey]['boundaryField'] 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.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) self.loadData()
def testBoundaryRead(self): bnd=BoundaryDict(self.dest) self.assertEqual(bnd["leftWall"]["type"],"wall") self.assertEqual(bnd["leftWall"]["nFaces"],50) self.assertEqual(len(bnd.patches()),5) self.assertEqual(len(bnd.patches(patchType="wall")),3)
class bcWidget(bcUI): def __init__(self, folder, nproc): self.currentFolder = folder bcUI.__init__(self) self.icones = {} self.icones['wall'] = QtGui.QIcon() self.icones['wall'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/wall16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['empty'] = QtGui.QIcon() self.icones['empty'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/empty16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['patch'] = QtGui.QIcon() self.icones['patch'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/patch16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclic'] = QtGui.QIcon() self.icones['cyclic'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/cyclic16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['cyclicAMI'] = QtGui.QIcon() self.icones['cyclicAMI'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/cyclicAMI16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['wedge'] = QtGui.QIcon() self.icones['wedge'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/wedge16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icones['symmetry'] = QtGui.QIcon() self.icones['symmetry'].addPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/symmetry16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.boundaries = BoundaryDict(str(self.currentFolder)) self.nproc = nproc #veo los campos que tengo en el directorio inicial [self.timedir, self.fields, self.currtime] = currentFields(self.currentFolder, nproc=self.nproc) #print self.fields self.loadData() self.comboBox.setEnabled(False) def loadData(self): self.listWidget.clear() for ipatch in self.boundaries.patches(): Item = QtGui.QListWidgetItem() Item.setIcon(self.icones[self.boundaries[ipatch]['type']]) Item.setText(_translate("bcWidget", ipatch, None)) self.listWidget.addItem(Item) self.pushButton.setEnabled(False) self.addTabs() def changeSelection(self): ipatch = str(self.listWidget.currentItem().text()) self.comboBox.clear() self.comboBox.addItems(prototypes[self.boundaries[ipatch]['type']]) self.addTabs(ipatch) return 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() fileDict = '%s/system/changeDictionaryPetroSym' % self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict, createZipped=False) for ifield in self.fields: if ifield not in unknowns: continue widget = QtGui.QWidget() layout = QtGui.QVBoxLayout(widget) if ipatch: if dictDict == []: filename = '%s/%s' % (self.timedir, ifield) parsedData = ParsedParameterFile(filename, listLengthUnparsed=20, createZipped=False) thisPatch = parsedData['boundaryField'][ipatch] else: thisPatch = dictDict['dictionaryReplacement'][ifield][ 'boundaryField'][ipatch] newComboBox = QtGui.QComboBox() newComboBox.addItems( types[self.boundaries[ipatch]['type']][ifield]) #aca hay que llamar a este evento solo si se cambia index = newComboBox.findText(thisPatch['type']) newComboBox.setCurrentIndex(index) if index != -1 else None layout.addWidget(newComboBox) extraInfo = extras[ifield][thisPatch['type']] self.addExtraInfo(layout, extraInfo) QtCore.QObject.connect( newComboBox, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.onChangeComboType) #cargo los datos desde el diccionario L = range(layout.count()) L = L[1:-1] iExtra = 0 for l in L: layout2 = layout.itemAt(l).layout() if layout2: if layout2.itemAt(1).widget().currentText() != 'table': data = str(thisPatch[extraInfo[iExtra * 4]]) data = data.replace('(', '').replace( ')', '').replace('[', '').replace(']', '').replace( ',', '').replace('\'', '').split() if layout2.count() == 3: layout2.itemAt(1).widget().setCurrentIndex( layout2.itemAt(1).widget().findText( data[0])) layout2.itemAt(2).widget().setText(data[1]) else: layout2.itemAt(1).widget().setCurrentIndex( layout2.itemAt(1).widget().findText( data[0])) layout2.itemAt(2).widget().setText(data[1]) layout2.itemAt(3).widget().setText(data[2]) layout2.itemAt(4).widget().setText(data[3]) else: None #determinar que hacer si quiero cargar una table!!! #('table', [[0, 0.0], [1e6-0.01, 0.0], [1e6, 1.0], [1e6, 1.0]]) #tabla = self.getTabla(itab) #parsedData['boundaryField'][ipatch][extraInfo[iExtra*4]] = ('table',tabla) iExtra = iExtra + 1 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 onChangeComboType(self): ii = self.tabWidget.currentIndex() ifield = str(self.tabWidget.tabText(ii)) widget = self.tabWidget.currentWidget() if widget: itype = str(widget.findChildren(QtGui.QComboBox)[0].currentText()) layout = widget.findChildren(QtGui.QVBoxLayout)[0] self.clearLayout(layout, 1) self.addExtraInfo(layout, extras[ifield][itype]) self.checkData() def onEditValue(self): return 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 addExtraInfo(self, layout, extraInfo): if extraInfo != []: for i in range(len(extraInfo) / 4): layout2 = QtGui.QHBoxLayout() label = QtGui.QLabel() label.setText('%s %s' % (extraInfo[i * 4], extraInfo[i * 4 + 1])) layout2.addWidget(label) if extraInfo[i * 4 + 2]: cb = QtGui.QComboBox() cb.addItems(extraInfo[i * 4 + 2]) layout2.addWidget(cb) for j in range(extraInfo[i * 4 + 3]): ledit = QtGui.QLineEdit() ledit.setValidator(QtGui.QDoubleValidator()) layout2.addWidget(ledit) QtCore.QObject.connect( ledit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.checkData) layout.addLayout(layout2) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) layout.addItem(spacerItem) def changePrototype(self): return def saveBCs(self): ipatch = str(self.listWidget.currentItem().text()) fileDict = '%s/system/changeDictionaryPetroSym' % self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict, createZipped=False) for itab in range(self.tabWidget.count()): ifield = str(self.tabWidget.tabText(itab)) itype = str( self.tabWidget.widget(itab).findChildren( QtGui.QComboBox)[0].currentText()) layout = self.tabWidget.widget(itab).findChildren( QtGui.QVBoxLayout)[0] if dictDict == []: filename = '%s/%s' % (self.timedir, ifield) parsedData = ParsedParameterFile(filename, listLengthUnparsed=20, createZipped=False) thisPatch = parsedData['boundaryField'][ipatch] else: thisPatch = dictDict['dictionaryReplacement'][ifield][ 'boundaryField'][ipatch] thisPatch = {} thisPatch['type'] = itype if itype == 'zeroGradient': thisPatch['ZZvalue'] = '0' #debo tomar los valores extras, si los tiene extraInfo = extras[ifield][itype] L = range(layout.count()) L = L[1:-1] iExtra = 0 #print ipatch for l in L: layout2 = layout.itemAt(l).layout() if layout2: if layout2.itemAt(1).widget().currentText() != 'table': if layout2.count() == 3: thisPatch[extraInfo[iExtra * 4]] = '%s %s' % ( layout2.itemAt(1).widget().currentText(), layout2.itemAt(2).widget().text()) else: thisPatch[extraInfo[ iExtra * 4]] = '%s (%s %s %s)' % ( layout2.itemAt(1).widget().currentText(), layout2.itemAt(2).widget().text(), layout2.itemAt(3).widget().text(), layout2.itemAt(4).widget().text()) else: #determinar que hacer si quiero cargar una table!!! #('table', [[0, 0.0], [1e6-0.01, 0.0], [1e6, 1.0], [1e6, 1.0]]) tabla = self.getTabla(itab) thisPatch[extraInfo[iExtra * 4]] = ('table', tabla) iExtra = iExtra + 1 if dictDict == []: parsedData['boundaryField'][ipatch] = thisPatch parsedData.writeFile() else: dictDict['dictionaryReplacement'][ifield]['boundaryField'][ ipatch] = thisPatch 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] = {} dictDictBak['dictionaryReplacement'][ikey][ 'boundaryField'] = dictDict[ 'dictionaryReplacement'][ikey]['boundaryField'] 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.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) self.pushButton.setEnabled(False) return def getTable(self, itab): table = [[0, 0], [1, 0]] return table 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) def changePatchType(self, item): texto = str(item.text()) w = bcPatch(self.boundaries[texto]['type']) result = w.exec_() if result: patchType = w.getPatchType() self.boundaries[texto]['type'] = patchType self.boundaries.writeFile() fileDict = '%s/system/changeDictionaryPetroSym' % self.currentFolder dictDict = [] if os.path.isfile(fileDict): dictDict = ParsedParameterFile(fileDict, createZipped=False) for ifield in self.fields: if dictDict == []: filename = '%s/%s' % (self.timedir, ifield) fieldData = ParsedParameterFile(filename, listLengthUnparsed=20, createZipped=False) else: fieldData = dictDict['dictionaryReplacement'][ifield] newDict = {} if patchType == 'empty': newDict['type'] = 'empty' newDict['ZZvalue'] = '0' else: if ifield in unknowns: newDict['type'] = 'zeroGradient' newDict['ZZvalue'] = '0' else: newDict['type'] = 'calculated' newDict['ZZvalue'] = '0' fieldData['boundaryField'][texto] = newDict if dictDict == []: fieldData.writeFile() else: dictDict['dictionaryReplacement'][ifield] = fieldData 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] = {} dictDictBak['dictionaryReplacement'][ikey][ 'boundaryField'] = dictDict[ 'dictionaryReplacement'][ikey]['boundaryField'] 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.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) self.loadData()
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