def resetCase(self): [self.timedir,self.fields,self.currtime] = currentFields(self.currentFolder,nproc=self.window().nproc) w = reset() result = w.exec_() if result: self.window().nproc = 1 command = 'pyFoamClearCase.py %s %s'%(w.getParams(), self.currentFolder) os.system(command) #if w.deleteSnapshots(): # command = 'rm -rf %s/postProcessing/snapshots'%self.currentFolder # os.system(command) if w.resetFigures(): self.window().resetFigures(w.deletePostpro(),True) filename = '%s/system/controlDict'%self.currentFolder parsedData = ParsedParameterFile(filename,createZipped=False) parsedData['startFrom'] = 'startTime' parsedData['startTime'] = '0' parsedData.writeFile() self.window().typeFile = {} self.window().pending_files = [] self.window().pending_dirs = [] self.window().updateLogFiles() self.type_serial.setChecked(True) self.type_parallel.setChecked(False) self.changeType() self.window().save_config()
def run(self): fName=self.parser.getArgs()[0] destPatches=self.parser.getArgs()[1:] if self.opts.patch==None and self.opts.value==None: self.error("Either a patch or a value must be specified") if self.opts.patch!=None and self.opts.value!=None: self.error("Only a patch or a value can be specified") try: fieldFile=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) value="" if self.opts.patch: value=fieldFile["boundaryField"][self.opts.patch][self.opts.srckey] else: value="uniform "+self.opts.value for destPatch in destPatches: fieldFile["boundaryField"][destPatch][self.opts.destkey]=value if self.opts.test: print_(str(fieldFile)) else: fieldFile.writeFile()
def aplicar(self): filename = '%s/system/controlDict' % self.currentFolder parsedData = ParsedParameterFile(filename, createZipped=False) parsedData['startFrom'] = self.cb_start_from_iinv[ self.cb_start_from.currentIndex()] parsedData['startTime'] = str(self.start_from.text()) parsedData['endTime'] = str(self.end_time.text()) parsedData['deltaT'] = str(self.delta_time.text()) if self.adjustable.isChecked(): parsedData['adjustTimeStep'] = 'yes' else: parsedData['adjustTimeStep'] = 'no' parsedData['maxCo'] = str(self.max_cfl.text()) parsedData['maxAlphaCo'] = str(self.max_cfl_alpha.text()) parsedData['maxDeltaT'] = str(self.max_deltat.text()) parsedData['writeControl'] = self.cb_write_control_iinv[ self.cb_write_control.currentIndex()] parsedData['writeInterval'] = str(self.write_control.text()) parsedData['purgeWrite'] = str(self.purge.value()) parsedData['writePrecision'] = str(self.precision.value()) parsedData['writeFormat'] = self.format_iinv[ self.format.currentIndex()] parsedData['timePrecision'] = str(self.precision_time.value()) parsedData['writeCompression'] = self.compression_iinv[ self.compression.currentIndex()] parsedData['stopAt'] = 'endTime' parsedData.writeFile() self.pushButton.setEnabled(False) self.window().updateLogFiles() return
def accept(self): filename = '%s/system/controlDict' % (self.currentFolder) parsedData = ParsedParameterFile(filename, createZipped=False) if 'functions' not in parsedData.getValueDict().keys(): parsedData['functions'] = {} if str(self.name.text()) not in parsedData['functions'].keys(): parsedData['functions'][str(self.name.text())] = {} parsedData['functions'][str(self.name.text())]['type'] = 'residuals' parsedData['functions'][str( self.name.text())]['outputControl'] = 'timeStep' parsedData['functions'][str( self.name.text())]['outputInterval'] = self.spinBox.value() parsedData['functions'][str( self.name.text())]['functionObjectLibs'] = [ '"libutilityFunctionObjects.so"' ] fields = [] for i in range(self.listWidget.count()): if self.listWidget.item(i).checkState() == QtCore.Qt.Checked: fields.append(str(self.listWidget.item(i).text())) parsedData['functions'][str(self.name.text())]['fields'] = fields parsedData.writeFile() self.done(self.Accepted)
class WriteAllTrigger: def __init__(self,sol,writeAll,purge,until): self.control=ParsedParameterFile(path.join(sol.systemDir(),"controlDict"), backup=True, doMacroExpansion=True) self.fresh=True try: if writeAll: self.control["writeControl"]="timeStep" self.control["writeInterval"]="1" if purge!=None: self.control["purgeWrite"]=purge if until!=None: self.control["endTime"]=until self.control.writeFile() except Exception: e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e' warning("Restoring defaults") self.control.restore() raise e def resetIt(self): if self.fresh: warning("Trigger called: Resetting the controlDict") self.control.restore() self.fresh=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() for ifield in self.fields: filename = '%s/%s'%(self.timedir,ifield) fieldData = ParsedParameterFile(filename,listLengthUnparsed=20,createZipped=False) newDict = {} if patchType == 'empty': newDict['type'] = 'empty' else: if ifield in unknowns: newDict['type'] = 'zeroGradient' else: newDict['type'] = 'calculated' fieldData['boundaryField'][texto] = newDict fieldData.writeFile() self.loadData()
def saveBCs(self): ipatch = str(self.listWidget.currentItem().text()) 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] filename = '%s/%s'%(self.timedir,ifield) parsedData = ParsedParameterFile(filename,listLengthUnparsed=20,createZipped=False) parsedData['boundaryField'][ipatch] = {} parsedData['boundaryField'][ipatch]['type'] = itype #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: parsedData['boundaryField'][ipatch][extraInfo[iExtra*4]] = '%s %s' %(layout2.itemAt(1).widget().currentText(),layout2.itemAt(2).widget().text()) else: parsedData['boundaryField'][ipatch][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) parsedData['boundaryField'][ipatch][extraInfo[iExtra*4]] = ('table',tabla) iExtra = iExtra+1 parsedData.writeFile() self.pushButton.setEnabled(False) return
def write_read_turbulence_coefficients(case_number, case_i_dir, turb_coeffs, turb_coeffs_values, delta_turb_coeffs): if case_number == 1: turb = ParsedParameterFile(case_i_dir + "/constant/turbulenceProperties") for k in turb_coeffs: turb_coeffs_values[k].append(turb['RAS']['kOmegaSSTCoeffs'][k]) print "\nTurbulence coefficients:" for l in turb_coeffs: print l + ": %.4f" % (turb_coeffs_values[l][0]) else: turb = ParsedParameterFile(case_i_dir + "/constant/turbulenceProperties") for m in turb_coeffs: turb['RAS']['kOmegaSSTCoeffs'][m] += delta_turb_coeffs['delta_' + m] turb.writeFile() for n in turb_coeffs: turb_coeffs_values[n].append(turb['RAS']['kOmegaSSTCoeffs'][n]) print "\nTurbulence coefficients:" for o in turb_coeffs: print o + ": %.4f" % (turb_coeffs_values[o][case_number - 1]) return turb_coeffs_values
def saveUserLibrary(self): filename = 'caseDicts/materialProperties.incompressible' parsedData = ParsedParameterFile(filename,createZipped=False) parsedData['userLibrary'] = self.userLibrary parsedData.writeFile() return
def setDict(dict_file, key, value): """all parameters are string type, accept, None or empty string dict_file: file must exist, checked by caller key: create the key if not existent value: None or empty string will delet such key """ if isinstance(key, string_types) and key.find('/')>=0: group = [k for k in key.split('/') if k] elif isinstance(key, list) or isinstance(key, tuple): group = [s for s in key if isinstance(s, string_types)] else: print("Warning: input key is not string or sequence type, so do nothing but return".format(key)) return f = ParsedParameterFile(dict_file) if len(group) == 3: d = f[group[0]][group[1]] # at most 3 levels, assuming it will auto create not existent key elif len(group) == 2: d = f[group[0]] else: d = f k = group[-1] if value: # d[k] = value elif key in d: del d[k] #if None, or empty string is specified, delete this key else: print('Warning: check parameters for set_dict() key={} value={}'.format(key, value)) f.writeFile()
def modifyDicts(self, parserArgs): if parserArgs.airspeed: file = ParsedParameterFile(os.path.join(self.casePath, "0", "U")) file["internalField"].val.vals[0] = parserArgs.airspeed file.writeFile() file = ParsedParameterFile(os.path.join(self.casePath, "system", "controlDict")) file["functions"]["forces"]["magUInf"] = parserArgs.airspeed file["functions"]["forceCoeffs1"]["magUInf"] = parserArgs.airspeed file.writeFile() if parserArgs.cofg: file = ParsedParameterFile(os.path.join(self.casePath, "system", "controlDict")) file["functions"]["forces"]["CofR"].vals[0] = parserArgs.cofg file["functions"]["forceCoeffs1"]["CofR"].vals[0] = parserArgs.cofg file.writeFile() if parserArgs.refarea: file = ParsedParameterFile(os.path.join(self.casePath, "system", "controlDict")) file["functions"]["forces"]["Aref"] = parserArgs.refarea file["functions"]["forceCoeffs1"]["Aref"] = parserArgs.refarea file.writeFile() # if parserArgs.Lref: # file = ParsedParameterFile(os.path.join(self.casePath,'system','controlDict')) # file['functions']['forces']['CofR'].vals[0] = parserArgs.cofg # file['functions']['forceCoeffs1']['CofR'].vals[0] = parserArgs.cofg # file.writeFile() if parserArgs.convergence: file = ParsedParameterFile(os.path.join(self.casePath, "system", "fvSolution")) for i in file["SIMPLE"]["residualControl"]: file["SIMPLE"]["residualControl"][i] = parserArgs.convergence file.writeFile()
def saveUserLibrary(self): filename = 'caseDicts/materialProperties.incompressible' parsedData = ParsedParameterFile(filename, createZipped=False) parsedData['userLibrary'] = self.userLibrary parsedData.writeFile() return
class LibFunctionTrigger: def __init__(self,sol,libs,funs): self.control=ParsedParameterFile(path.join(sol.systemDir(),"controlDict"), backup=True, doMacroExpansion=True) self.fresh=False try: if libs and ("libs" in self.control): warning("Temporarily removing the libs-entry from the controlDict") del self.control["libs"] self.fresh=True if funs and ("functions" in self.control): warning("Temporarily removing the functions-entry from the controlDict") del self.control["functions"] self.fresh=True if self.fresh: self.control.writeFile() else: self.control.restore() except Exception: e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e' warning("Restoring defaults") self.control.restore() raise e def resetIt(self): if self.fresh: warning("Trigger called: Resetting controlDict") self.control.restore() self.fresh=False
def write(self): """ Updates the values for the turbulent flow properties and writes all **turbulent** boundary files. Wallfunctions, if used, are updated as well. """ for bcI in self.turbBC: for inletPatchI in self.case.inletPatch: bcFile = ParsedParameterFile( join( self.case.name, self.case.first, bcI ) ) # Set the internal field and the inlet patch at first bcFile['internalField'] = "uniform %f" %(self.vars[bcI]) bcFile['boundaryField'][inletPatchI]['value'] = \ "uniform %f" %(self.vars[bcI]) # Update the wallfunctions if they are used for patchI in bcFile['boundaryField']: if "allFunction" in bcFile['boundaryField'][patchI]['type']: bcFile['boundaryField'][patchI]['value'] = \ "uniform %f" %(self.vars[bcI]) # Write the current boundary file bcFile.writeFile()
class LibFunctionTrigger: def __init__(self,sol,libs,funs): self.control=ParsedParameterFile(path.join(sol.systemDir(),"controlDict"),backup=True) self.fresh=False try: if libs and ("libs" in self.control): warning("Temporarily removing the libs-entry from the controlDict") del self.control["libs"] self.fresh=True if funs and ("functions" in self.control): warning("Temporarily removing the functions-entry from the controlDict") del self.control["functions"] self.fresh=True if self.fresh: self.control.writeFile() else: self.control.restore() except Exception,e: warning("Restoring defaults") self.control.restore() raise e
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 accept(self): filename = '%s/system/controlDict' % (self.currentFolder) parsedData = ParsedParameterFile(filename, createZipped=False) if 'functions' not in parsedData.getValueDict().keys(): parsedData['functions'] = {} #Logica para evitar nombres repetidos for key in self.parsedData['functions'].keys(): if key == str(self.name.text()): w = QtGui.QMessageBox( QtGui.QMessageBox.Information, "Error", "The name of the new figure and the name of the tracer must be different. Please select another name" ) w.exec_() return dicc['outputInterval'] = self.spinBox.value() fields = [] for i in range(self.listWidget.count()): if self.listWidget.item(i).checkState() == QtCore.Qt.Checked: fields.append(str(self.listWidget.item(i).text())) dicc['fields'] = fields dicc['sourceName'] = str(self.comboBox.currentText()) parsedData['functions'][str(self.name.text())] = dicc parsedData.writeFile() self.done(self.Accepted)
def case_setup(ci): template_case = SolutionDirectory( "template", archive=None, paraviewLink=False) case = template_case.cloneCase( "{0}{1}".format(ci.name, ci.quadrature_order) ) phase_properties = ParsedParameterFile( path.join("./diffs", ci.phase_properties_name)) phase_properties["air"]["PBEDiameterCoeffs"]["QMOMCoeffs"]["quadratureOrder"] = ci.quadrature_order # manually fix bad pyfoam parsing phase_properties["blending"]["default"]["type"] = "none" phase_properties["drag"][1]["swarmCorrection"]["type"] = "none" phase_properties.writeFileAs(path.join( case.name, "constant", "phaseProperties" )) m0 = ParsedParameterFile(path.join(template_case.name, "0", "m0")) for i in range(ci.number_of_moments): m0.header["object"] = "m" + str(i) m0["internalField"].setUniform(ci.initial_moments[i]) m0["dimensions"] = "[0 {0} 0 0 0 0 0]".format(3 * i) m0.writeFileAs(path.join(case.name, "0", "m" + str(i))) controlDict = ParsedParameterFile( path.join(case.name, "system", "controlDict") ) controlDict["functions"]["probes"]["fields"] = [ "m{0}".format(m) for m in range(ci.number_of_moments)] controlDict["endTime"] = ci.end_time controlDict["deltaT"] = ci.delta_t controlDict.writeFile()
def aplicar(self): filename = '%s/system/controlDict'%self.currentFolder parsedData = ParsedParameterFile(filename,createZipped=False) parsedData['startFrom'] = self.cb_start_from_iinv[self.cb_start_from.currentIndex()] parsedData['startTime'] = str(self.start_from.text()) parsedData['endTime'] = str(self.end_time.text()) parsedData['deltaT'] = str(self.delta_time.text()) if self.adjustable.isChecked(): parsedData['adjustTimeStep'] = 'yes' else: parsedData['adjustTimeStep'] = 'no' parsedData['maxCo'] = str(self.max_cfl.text()) parsedData['maxAlphaCo'] = str(self.max_cfl_alpha.text()) parsedData['maxDeltaT'] = str(self.max_deltat.text()) parsedData['writeControl'] = self.cb_write_control_iinv[self.cb_write_control.currentIndex()] parsedData['writeInterval'] = str(self.write_control.text()) parsedData['purgeWrite'] = str(self.purge.value()) parsedData['writePrecision'] = str(self.precision.value()) parsedData['writeFormat'] = self.format_iinv[self.format.currentIndex()] parsedData['timePrecision'] = str(self.precision_time.value()) parsedData['writeCompression'] = self.compression_iinv[self.compression.currentIndex()] parsedData['stopAt'] = 'endTime' parsedData.writeFile() self.pushButton.setEnabled(False) self.window().updateLogFiles() return
def run(self): fName=self.parser.getArgs()[0] bName=self.parser.getArgs()[1] tName=self.parser.getArgs()[2] boundaryPath=path.join(".",fName,self.opts.time,self.opts.region,"polyMesh","boundary") try: boundary=ParsedParameterFile(boundaryPath,debug=False,boundaryDict=True) except IOError: self.error("Problem opening boundary file",boundaryPath) bnd=boundary.content if type(bnd)!=list: self.error("Problem with boundary file (not a list)") found=False for val in bnd: if val==bName: found=True elif found: val["type"]=tName break if not found: self.error("Boundary",bName,"not found in",bnd[::2]) if self.opts.test: print_(boundary) else: boundary.writeFile() self.addToCaseLog(fName)
def processABoundaryFile(self,func,targetDir): """ @param func: the function that transforms the actual boundary file """ boundaryPath=path.join(targetDir,self.opts.region,"polyMesh","boundary") try: boundary=ParsedParameterFile(boundaryPath, debug=False, boundaryDict=True, treatBinaryAsASCII=True) except IOError: self.warning("Problem opening boundary file",boundaryPath) return False bnd=boundary.content if type(bnd)!=list: self.warning("Problem with boundary file (not a list)") return False boundary.content=func(bnd,targetDir) if boundary.content: if self.opts.test: print_(boundary) else: boundary.writeFile() # self.addToCaseLog(boundaryPath) return True else: self.warning(boundaryPath,"unchanged") return False
class SafeTrigger: def __init__(self,sol,factor): self.solution=ParsedParameterFile(path.join(sol.systemDir(),"fvSolution"),backup=True) self.schemes=ParsedParameterFile(path.join(sol.systemDir(),"fvSchemes"),backup=True) self.fresh=True try: relax=self.solution["relaxationFactors"] for var in relax: relax[var]*=factor cExp=re.compile("div\((.+),(.+)\)") conv=self.schemes["divSchemes"] for nm in conv: if cExp.match(nm) or nm=="default": conv[nm]="Gauss upwind" self.solution.writeFile() self.schemes.writeFile() except Exception,e: warning("Restoring defaults") self.solution.restore() self.schemes.restore() raise e
class WriteAllTrigger: def __init__(self, sol, writeAll, purge, until): self.control = ParsedParameterFile(path.join(sol.systemDir(), "controlDict"), backup=True, doMacroExpansion=True) self.fresh = True try: if writeAll: self.control["writeControl"] = "timeStep" self.control["writeInterval"] = "1" if purge != None: self.control["purgeWrite"] = purge if until != None: self.control["endTime"] = until self.control.writeFile() except Exception: e = sys.exc_info()[ 1] # Needed because python 2.5 does not support 'as e' warning("Restoring defaults") self.control.restore() raise e def resetIt(self): if self.fresh: warning("Trigger called: Resetting the controlDict") self.control.restore() self.fresh = False
def writeOFBoundaries(self): """Write boundary conditions to 0/<field> file in case directory.""" for field in self.boundaries: f = ParsedParameterFile(os.path.join(self.casename, "0/" + field)) for boundary in self.boundaries[field]: f["boundaryField"][boundary] = self.boundaries[field][boundary] f.writeFile()
def accept(self): filename = '%s/system/controlDict'%(self.currentFolder) parsedData = ParsedParameterFile(filename,createZipped=False) if 'functions' not in parsedData.getValueDict().keys(): parsedData['functions'] = {} if str(self.name.text()) not in parsedData['functions'].keys(): parsedData['functions'][str(self.name.text())] = {} parsedData['functions'][str(self.name.text())]['type'] = 'sets' parsedData['functions'][str(self.name.text())]['outputControl'] = 'timeStep' parsedData['functions'][str(self.name.text())]['outputInterval'] = self.spinBox.value() parsedData['functions'][str(self.name.text())]['setFormat'] = 'raw' parsedData['functions'][str(self.name.text())]['interpolationScheme'] = 'cellPoint' ifield = self.comboBox.currentText() if ifield not in self.fields: #significa que es un vector axis = 'distance' #ifield[-1] ifield = ifield[0:-1] else: axis = 'distance' #por las dudas parsedData['functions'][str(self.name.text())]['fields'] = [ifield] dicc = {} dicc['nPoints'] = self.nop.text() dicc['start'] = '(%s %s %s)'%(str(self.p1_x.text()),str(self.p1_y.text()),str(self.p1_z.text())) dicc['end'] = '(%s %s %s)'%(str(self.p2_x.text()),str(self.p2_y.text()),str(self.p2_z.text())) dicc['type'] = 'uniform' dicc['axis'] = axis parsedData['functions'][str(self.name.text())]['sets'] = ['data',dicc] parsedData.writeFile() self.done(self.Accepted)
def accept(self): filename = '%s/system/controlDict'%(self.currentFolder) parsedData = ParsedParameterFile(filename,createZipped=False) if 'functions' not in parsedData.getValueDict().keys(): parsedData['functions'] = {} #Logica para evitar nombres repetidos for key in self.parsedData['functions'].keys(): if key == str(self.name.text()): w = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Error", "The name of the new figure and the name of the tracer must be different. Please select another name") w.exec_() return dicc['outputInterval'] = self.spinBox.value() fields = [] for i in range(self.listWidget.count()): if self.listWidget.item(i).checkState() == QtCore.Qt.Checked: fields.append(str(self.listWidget.item(i).text())) dicc['fields'] = fields dicc['sourceName'] = str(self.comboBox.currentText()) parsedData['functions'][str(self.name.text())] = dicc parsedData.writeFile() self.done(self.Accepted)
def saveUserLibrary(self): filename = '%s/.config/petroSym/materialProperties.incompressible'%self.home #Path en home parsedData = ParsedParameterFile(filename,createZipped=False) parsedData['userLibrary'] = self.userLibrary parsedData.writeFile() return
def changePatchType(self, item): w = bcPatch(self.boundaries[item.text()]['type']) result = w.exec_() if result: patchType = w.getPatchType() self.boundaries[item.text()]['type'] = patchType self.boundaries.writeFile() for ifield in self.fields: filename = '%s/%s' % (self.timedir, ifield) fieldData = ParsedParameterFile(filename, createZipped=False) newDict = {} if patchType == 'empty': newDict['type'] = 'empty' else: if ifield in unknowns: newDict['type'] = 'zeroGradient' else: newDict['type'] = 'calculated' fieldData['boundaryField'][item.text()] = newDict fieldData.writeFile() 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, 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 execute(self, para, log): f = replaceValues(self.filename, para) v = replaceValues(self.value, para) s = replaceValues(self.subexpression, para) k = replaceValues(self.key, para) try: dictFile = ParsedParameterFile(f, backup=True) val = dictFile[k] except KeyError: self.error("Key: ", k, "not existing in File", f) except IOError: e = sys.exc_info()[ 1] # Needed because python 2.5 does not support 'as e' self.error("Problem with file", k, ":", e) try: exec_("dictFile[k]" + s + "=v") except Exception: e = sys.exc_info()[ 1] # Needed because python 2.5 does not support 'as e' error("Problem with subexpression:", sys.exc_info()[0], ":", e) dictFile.writeFile() return True, None
def accept(self): filename = '%s/system/controlDict'%(self.currentFolder) parsedData = ParsedParameterFile(filename,createZipped=False) if 'functions' not in parsedData.getValueDict().keys(): parsedData['functions'] = {} #Logica para evitar que se llamen T* (como los tracers) # if len(str(self.name.text()))>=2 and self.name.text()[0]=='T': # for i in range(1,len(str(self.name.text()))): # if () #Logica para evitar nombres repetidos for key in parsedData['functions'].keys(): if key == str(self.name.text()): w = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Error", "The name of the new figure and the name of the field must be different. Please select another name") w.exec_() return if str(self.name.text()) not in parsedData['functions'].keys(): parsedData['functions'][str(self.name.text())] = {} parsedData['functions'][str(self.name.text())]['type'] = 'residuals' parsedData['functions'][str(self.name.text())]['outputControl'] = 'timeStep' parsedData['functions'][str(self.name.text())]['outputInterval'] = self.spinBox.value() parsedData['functions'][str(self.name.text())]['functionObjectLibs'] = ['"libutilityFunctionObjects.so"'] fields = [] for i in range(self.listWidget.count()): if self.listWidget.item(i).checkState() == QtCore.Qt.Checked: fields.append(str(self.listWidget.item(i).text())) parsedData['functions'][str(self.name.text())]['fields'] = fields parsedData.writeFile() self.done(self.Accepted)
def case_setup(ci): template_case = SolutionDirectory( "template", archive=None, paraviewLink=False) case = template_case.cloneCase( "{0}NC{1}".format(ci.name, ci.nr_classes) ) phase_properties = ParsedParameterFile( path.join(template_case.name, "constant", "phaseProperties")) phase_properties["oil"]["PBEDiameterCoeffs"]["MOCCoeffs"]["numberOfClasses"] = ci.nr_classes phase_properties["oil"]["PBEDiameterCoeffs"]["MOCCoeffs"]["xi1"] = ci.dv # manually fix bad pyfoam parsing phase_properties["blending"]["default"]["type"] = "none" phase_properties["drag"][1]["swarmCorrection"]["type"] = "none" phase_properties.writeFileAs(path.join( case.name, "constant", "phaseProperties" )) n0 = ParsedParameterFile(path.join(template_case.name, "0", "n0")) for i in range(ci.nr_classes): n0.header["object"] = "n" + str(i) n0["internalField"].setUniform(ci.Ninit[i]) n0.writeFileAs(path.join(case.name, "0", "n" + str(i))) controlDict = ParsedParameterFile( path.join(case.name, "system", "controlDict") ) controlDict["functions"]["probes"]["fields"] = [ "n{0}".format(n) for n in range(ci.nr_classes)] controlDict.writeFile()
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 processABoundaryFile(self,func,targetDir): """ :param func: the function that transforms the actual boundary file """ boundaryPath=path.join(targetDir,"polyMesh","boundary") try: boundary=ParsedParameterFile(boundaryPath, debug=False, boundaryDict=True, treatBinaryAsASCII=True) except IOError: self.warning("Problem opening boundary file",boundaryPath) return False bnd=boundary.content if type(bnd)!=list: self.warning("Problem with boundary file (not a list)") return False boundary.content=func(bnd,targetDir) if boundary.content: if self.opts.test: print_(boundary) else: boundary.writeFile() # self.addToCaseLog(boundaryPath) return True else: self.warning(boundaryPath,"unchanged") return False
def run(self): fName = self.parser.getArgs()[0] destPatches = self.parser.getArgs()[1:] if self.opts.patch == None and self.opts.value == None: self.error("Either a patch or a value must be specified") if self.opts.patch != None and self.opts.value != None: self.error("Only a patch or a value can be specified") try: fieldFile = 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) value = "" if self.opts.patch: value = fieldFile["boundaryField"][self.opts.patch][ self.opts.srckey] else: value = "uniform " + self.opts.value for destPatch in destPatches: fieldFile["boundaryField"][destPatch][self.opts.destkey] = value if self.opts.test: print_(str(fieldFile)) else: fieldFile.writeFile()
class SafeTrigger: def __init__(self,sol,factor): self.solution=ParsedParameterFile(path.join(sol.systemDir(),"fvSolution"),backup=True) self.schemes=ParsedParameterFile(path.join(sol.systemDir(),"fvSchemes"),backup=True) self.fresh=True try: relax=self.solution["relaxationFactors"] for var in relax: relax[var]*=factor cExp=re.compile("div\((.+),(.+)\)") conv=self.schemes["divSchemes"] for nm in conv: if cExp.match(nm) or nm=="default": conv[nm]="Gauss upwind" self.solution.writeFile() self.schemes.writeFile() except Exception: e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e' warning("Restoring defaults") self.solution.restore() self.schemes.restore() raise e def resetIt(self): if self.fresh: warning("Trigger called: Resetting fvSchemes and fvSolution") self.solution.restore() self.schemes.restore() self.fresh=False
def writeOFBoundaries(self): """Write boundary conditions to 0/<field> file in case directory.""" for field in self.boundaries: f = ParsedParameterFile(os.path.join(self.casename, "0/" + field)) for boundary in self.boundaries[field]: f["boundaryField"][boundary] = self.boundaries[field][boundary] f.writeFile()
def run(self): fName=self.parser.getArgs()[0] bName=self.parser.getArgs()[1] tName=self.parser.getArgs()[2] boundaryPath=path.join(".",fName,self.opts.time,self.opts.region,"polyMesh","boundary") try: boundary=ParsedParameterFile(boundaryPath,debug=False,boundaryDict=True) except IOError: self.error("Problem opening boundary file",boundaryPath) bnd=boundary.content if type(bnd)!=list: self.error("Problem with boundary file (not a list)") found=False for val in bnd: if val==bName: found=True elif found: val["type"]=tName break if not found: self.error("Boundary",bName,"not found in",bnd[::2]) if self.opts.test: print_(boundary) else: boundary.writeFile() self.addToCaseLog(fName)
def main(args): # 0 - reading input cwd = os.getcwd() os.chdir(args.target) if len(glob.glob("*.map")) > 1: print "error: more then a single map file in the directory, please delete all except one" raise SystemExit mapFileName = glob.glob("*.map")[0] remove_extra_spaces(mapFileName) from pdb import set_trace #set_trace() # 0.5 creating z0 dummy file os.system("cp -r 0/p 0/z0") z0Dict = ParsedParameterFile("0/z0") z0Dict.header["object"] = "z0" for b in z0Dict["boundaryField"]: print b if type(b) is str: if b.find("terrain") > -1 or b.find("ground") > -1: print "found terrain/ground in z0 at patch " + b z0Dict["boundaryField"][b]["value"] = "uniform 0" z0Dict["boundaryField"][b]["type"] = "fixedValue" z0Dict["dimensions"] = "[ 0 1 0 0 0 0 0]" z0Dict.writeFile() # 1 - running roughnessToFoam.C callString = "( echo %s; echo %d; echo %d; echo %d; echo %d; echo %d; echo %d) | roughnessToFoam" % ( mapFileName, args.offsetX, args.offsetY, args.point_ax, args.point_ay, args.point_bx, args.point_by) os.system(callString) # 2 - reading modified z0 file - made with roughnessToFoam.C z0Dict = ParsedParameterFile("0/z0") for b in z0Dict["boundaryField"]: if type(b) is str: if b.find("terrain") > -1: # TODO - save each different *terrain*'s z0 and place in matching nut *terrain*. at the moment - only one patch with "terrain" in it is expected, and one with "ground". z0Terrain = z0Dict["boundaryField"][b]["value"] print "taken *terrain* z0 from %s" % b if b.find("ground") > -1: z0Ground = z0Dict["boundaryField"][b]["value"] print "taken *ground* z0 from %s" % b # 3 - writing z0 into nut file nutDict = ParsedParameterFile("0/nut") for b in nutDict["boundaryField"]: if type(b) is str: for c in nutDict["boundaryField"][b]: if "z0" in c: if b.find("terrain") > -1: nutDict["boundaryField"][b]["z0"] = z0Terrain if b.find("ground") > -1: nutDict["boundaryField"][b]["z0"] = 0 nutDict["boundaryField"][b]["z0"] = z0Ground nutDict.writeFile() os.chdir(cwd)
def edit_velocity(dictionary, domain_json, velocity=1): """ Edit the initial velocity file for CFD simulation :param str dictionary: File path of the velocity dictionary, (0/U) :param str domain_json: File path of vessel inlet description json :param float velocity: Inlet velocity magnitude (cm/s) """ try: tqdm.write("{}: Editing velocity file: {}".format( datetime.datetime.now(), dictionary)) velocityDict = ParsedParameterFile(dictionary) with open(domain_json, 'r') as f: domain_dict = json.load(f) boundaryField = { "vessel": { "type": "noSlip" }, "walls": { "type": "empty" } } for key, value in domain_dict.items(): try: if value["type"] == "inlet": boundaryField.update({key: { "type": "fixedValue", "value": "uniform (" +\ str(value["tangent"][0]/100*velocity) + " " + \ str(value["tangent"][1]/100*velocity) + " " + \ str(value["tangent"][2]/100*velocity) + ")"}}) elif value["type"] == "outlet": boundaryField.update({ key: { "type": "inletOutlet", "inletValue": "uniform (0 0 0)", "value": "uniform (0 0 0)" } }) else: continue except: continue velocityDict["boundaryField"] = boundaryField try: velocityDict.writeFile() except IOError: tqdm.write("Can't write file. Content would have been:") tqdm.write(velocityDict) except IOError: tqdm.write(dictionary, " does not exist") return 1
def aplicar(self): filename = '%s/system/fvSchemes' % self.currentFolder parsedData = ParsedParameterFile(filename, createZipped=False) #modify data parsedData.writeFile() self.pushButton.setEnabled(False) return
def make_injector(self): self.calc_injector() inj_file = ParsedParameterFile(Path("casedir/constant/InjectorModel")) inj_file["injector1"]["position"] = self.inj_poskey inj_file["injector1"]["direction"] = self.inj_dirkey inj_file.writeFile()
def aplicar(self): filename = '%s/system/fvSolution'%self.currentFolder parsedData = ParsedParameterFile(filename,createZipped=False) #modify data parsedData.writeFile() self.pushButton.setEnabled(False) return
def main(args): # 0 - reading input cwd = os.getcwd() os.chdir(args.target) if len(glob.glob("*.map")) > 1: print "error: more then a single map file in the directory, please delete all except one" raise SystemExit mapFileName = glob.glob("*.map")[0] remove_extra_spaces(mapFileName) from pdb import set_trace #set_trace() # 0.5 creating z0 dummy file os.system("cp -r 0/p 0/z0") z0Dict = ParsedParameterFile("0/z0") z0Dict.header["object"] = "z0" for b in z0Dict["boundaryField"]: print b if type(b) is str: if b.find("terrain")>-1 or b.find("ground")>-1: print "found terrain/ground in z0 at patch " + b z0Dict["boundaryField"][b]["value"]="uniform 0" z0Dict["boundaryField"][b]["type"]="fixedValue" z0Dict["dimensions"] = "[ 0 1 0 0 0 0 0]" z0Dict.writeFile() # 1 - running roughnessToFoam.C callString = "( echo %s; echo %d; echo %d; echo %d; echo %d; echo %d; echo %d) | roughnessToFoam" % (mapFileName, args.offsetX, args.offsetY, args.point_ax, args.point_ay, args.point_bx, args.point_by) os.system(callString) # 2 - reading modified z0 file - made with roughnessToFoam.C z0Dict = ParsedParameterFile("0/z0") for b in z0Dict["boundaryField"]: if type(b) is str: if b.find("terrain")>-1: # TODO - save each different *terrain*'s z0 and place in matching nut *terrain*. at the moment - only one patch with "terrain" in it is expected, and one with "ground". z0Terrain = z0Dict["boundaryField"][b]["value"] print "taken *terrain* z0 from %s" % b if b.find("ground")>-1: z0Ground = z0Dict["boundaryField"][b]["value"] print "taken *ground* z0 from %s" % b # 3 - writing z0 into nut file nutDict = ParsedParameterFile("0/nut") for b in nutDict["boundaryField"]: if type(b) is str: for c in nutDict["boundaryField"][b]: if "z0" in c: if b.find("terrain")>-1: nutDict["boundaryField"][b]["z0"] = z0Terrain if b.find("ground")>-1: nutDict["boundaryField"][b]["z0"] = 0 nutDict["boundaryField"][b]["z0"] = z0Ground nutDict.writeFile() os.chdir(cwd)
def saveCaseData(self, doTopoSet=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) tracer = copy.deepcopy(dicc) cellsetname = '%s_c'%patchName tracer['fvOptions']['S']['timeStart'] = str(self.tableWidget.cellWidget(i,0).text()) tracer['fvOptions']['S']['cellSet'] = cellsetname tracer['patchName'] = patchName 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() #self.parsedData.closeFile() if doTopoSet: spatches = set(patches) ii = 0 cmd = 'cp %s/caseDicts/topoSetDict %s/system/.'%(os.path.dirname(__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 ipatch in spatches: cellsetname = '%s_c'%ipatch facesetname = '%s_f'%ipatch if not os.path.isfile('%s/constant/polyMesh/sets/%s'%(self.currentFolder,cellsetname)): if ii>0: topoSetData['actions'].append(topoSetData['actions'][0]) topoSetData['actions'].append(topoSetData['actions'][1]) topoSetData['actions'][ii]['name'] = facesetname topoSetData['actions'][ii]['sourceInfo']['name'] = ipatch topoSetData['actions'][ii+1]['name'] = cellsetname topoSetData['actions'][ii+1]['sourceInfo']['set'] = facesetname ii = ii+2 topoSetData.writeFile() cmd = 'topoSet -case %s > run_topoSet.log &'%self.currentFolder os.system(cmd) else: self.loadCaseData() self.refreshTable() self.refreshTimeline() return
def reset(self): pid = self.worker_index #os.getpid() # logger_g.info(f'{pid}') self.casename = 'baseCase_'+str(pid) self.csvfile = 'progress_'+str(pid)+'.csv' orig = SolutionDirectory(origcase,archive=None,paraviewLink=False) case = orig.cloneCase(self.casename ) control_dict = ParsedParameterFile(path.join(self.casename,"system", "controlDict")) control_dict["endTime"] = self.end_time control_dict["writeInterval"] = self.write_interval control_dict.writeFile() # remove old log files with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm {self.casename}/log.*', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # remove old solution directories with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm -r {self.casename}/0.* {self.casename}/[1-9]*', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # remove old solution directories with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm -r {self.casename}/VTK', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # remove old solution directories # subprocess.run( # f'rm -r postProcessing', # shell=True, # stderr=subprocess.STDOUT # ) self.count_parameters = 0 if self.states_type == 1: #self.actions[self.count_parameters] = self.a1[0] self.state = np.array([self.a1[0]]) elif self.states_type == 2: self.state = np.hstack((self.a1,self.reward)) return np.array(self.state)
def saveCaseData(self, doTopoSet=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) tracer = copy.deepcopy(dicc) cellsetname = "%s_c" % patchName tracer["fvOptions"]["S"]["timeStart"] = str(self.tableWidget.cellWidget(i, 0).text()) tracer["fvOptions"]["S"]["cellSet"] = cellsetname tracer["patchName"] = patchName 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() # self.parsedData.closeFile() if doTopoSet: spatches = set(patches) ii = 0 cmd = "cp caseDicts/topoSetDict %s/system/." % 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 ipatch in spatches: cellsetname = "%s_c" % ipatch facesetname = "%s_f" % ipatch if not os.path.isfile("%s/constant/polyMesh/sets/%s" % (self.currentFolder, cellsetname)): if ii > 0: topoSetData["actions"].append(topoSetData["actions"][0]) topoSetData["actions"].append(topoSetData["actions"][1]) topoSetData["actions"][ii]["name"] = facesetname topoSetData["actions"][ii]["sourceInfo"]["name"] = ipatch topoSetData["actions"][ii + 1]["name"] = cellsetname topoSetData["actions"][ii + 1]["sourceInfo"]["set"] = facesetname ii = ii + 2 topoSetData.writeFile() cmd = "topoSet -case %s > run_topoSet.log &" % self.currentFolder os.system(cmd) else: self.loadCaseData() self.refreshTable() self.refreshTimeline() return
def stopRun(self): filename = '%s/system/controlDict'%self.currentFolder parsedData = ParsedParameterFile(filename,createZipped=False) parsedData['stopAt'] = 'writeNow' parsedData.writeFile() time.sleep(0.1) self.findChild(QtGui.QPushButton,'pushButton_3').setEnabled(False) # while 1: # command = 'ps | cut -d " " -f 7 | grep Foam > %s/runningNow'%self.currentFolder # os.system(command) # f = open('%s/runningNow'%self.currentFolder, 'r') # if not f.read(): # break # f.close() # time.sleep(0.1) import psutil import utils self.progress = QtGui.QProgressBar() self.progress.setWindowTitle("Saving the current data... Hold tight") resolution = utils.get_screen_resolutions() self.progress.setGeometry(int(resolution[0])/2 - 175,int(resolution[1])/2,350,30) self.progress.show() i=0 while psutil.pid_exists(self.window().runningpid): #retraso un minuto la edicion del control dict tt = list(localtime()) tt[4] = (tt[4]+1)%60 #Agrego el modulo porque cuando el min es 0, 0-1 = -1 command = 'touch -d "%s" %s'%(strftime("%Y-%m-%d %H:%M:%S", struct_time(tuple(tt))),filename) os.system(command) self.progress.setValue(i) QtGui.QApplication.processEvents() i=i+0.1 time.sleep(0.1) self.progress.setValue(100) self.progress.close() if psutil.pid_exists(self.window().runningpid): command = 'kill %s'%self.window().runningpid os.system(command) self.window().runningpid = -1 self.window().save_config() self.window().runW.pushButton_run.setEnabled(True) self.window().runW.pushButton_reset.setEnabled(True) self.window().tab_mesh.setEnabled(True) self.window().refresh_pushButton.setEnabled(True) leave = [1,5] for i in range(self.window().treeWidget.topLevelItemCount()): if i not in leave: self.window().treeWidget.topLevelItem(i).setDisabled(False)
def writeOpenFOAMDictionaryFromDictionary(dictToWrite, pathToFile): """ Write an OpenFOAM dictionary from a python dictionary """ print "Writing to file", pathToFile # open file without reading its body and add dictionary data to it dictFile = ParsedParameterFile(pathToFile, noBody=True) for key, value in dictToWrite.iteritems(): dictFile[key] = value dictFile.writeFile()
def set_boundary(in_dict, path): boundary_dict = ParsedParameterFile(path) bf_dict = boundary_dict['boundaryField'] for bf_key in in_dict: if bf_key in bf_dict: patch_dict = bf_dict[bf_key] for val_key in patch_dict: if val_key in in_dict[bf_key]: patch_dict[val_key] = in_dict[bf_key][val_key] boundary_dict.writeFile()
def run(self): fName = self.parser.getArgs()[0] all = self.parser.getArgs()[1] if all[0] == '"': all = all[1:] if all[-1] == '"': all = all[:-1] val = self.parser.getArgs()[2] if self.opts.stripQuotes: if val[0] == '"': val = val[1:] if val[-1] == '"': val = val[:-1] match = re.compile("([a-zA-Z_][a-zA-Z0-9_]*)(.*)").match(all) if match == None: self.error("Expression", all, "not usable as an expression") key = match.group(1) sub = None if len(match.groups()) > 1: if match.group(2) != "": sub = match.group(2) if self.opts.verbatim: newValue = val else: newValue = eval(val) try: dictFile = ParsedParameterFile(fName, backup=True) val = dictFile[key] except KeyError: self.error("Key: ", key, "not existing in File", fName) except IOError: e = sys.exc_info()[ 1] # Needed because python 2.5 does not support 'as e' self.error("Problem with file", fName, ":", e) if sub == None: dictFile[key] = newValue else: try: exec_("dictFile[key]" + sub + "=newValue") except Exception: e = sys.exc_info()[ 1] # Needed because python 2.5 does not support 'as e' self.error("Problem with subexpression:", sys.exc_info()[0], ":", e) if self.opts.test: print_(str(dictFile)) else: dictFile.writeFile()
class Pyfoam_parser(Parser): """pyfoam based openfoam dict parser that modifes a file Args: Parser ([type]): abstract class """ def __init__(self, filename: str): self.filename = filename self._ppp = ParsedParameterFile(self.filename) def _nested_get(self, dic: Dict, keyword: str): key_list = keyword.split("/") key_list[:] = [x for x in key_list if x] if len(key_list) == 1: return dic[key_list[0]] for key in key_list: dic = dic[key] return dic def _nested_set(self, dic: Dict, keyword: str, value: Any): key_list = keyword.split("/") key_list[:] = [x for x in key_list if x] if len(key_list) == 1: dic[key_list[-1]] = value return for key in key_list[:-1]: dic = dic.setdefault(key, {}) dic[key_list[-1]] = value def value(self, keyword: str): """get value of key word Args: keyword (str): keyword as string e.g. application or in case of a nested dictionary dict1/subDict1/keyword1 Returns: [type]: return value """ return self._nested_get(self._ppp.content, keyword) def set(self, keyword: str, value: Any): """set value Args: keyword (str): keyword as string e.g. application or in case of a nested dictionary dict1/subDict1/keyword1 value (Any): new value """ self._nested_set(self._ppp.content, keyword, value) def writeFile(self): self._ppp.writeFile()
def runCase(self): [self.timedir,self.fields,self.currtime] = currentFields(self.currentFolder,nproc=self.window().nproc) # if self.window().nproc>1: # w = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Is the case decomposed?", "Simulation will be done only if case decompositione was done previously. Continue?", QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) # ret = w.exec_() # if(QtGui.QMessageBox.No == ret): # return #modifico el control dict porque pude haber parado la simulacion filename = '%s/system/controlDict'%self.currentFolder parsedData = ParsedParameterFile(filename,createZipped=False) parsedData['stopAt'] = 'endTime' parsedData.writeFile() self.window().removeFilesPostPro() #retraso un minuto la edicion del control dict tt = list(localtime()) tt[4] = (tt[4]-1)%60 #Agrego el modulo porque cuando el min es 0, 0-1 = -1 command = 'touch -d "%s" %s'%(strftime("%Y-%m-%d %H:%M:%S", struct_time(tuple(tt))),filename) os.system(command) filename1 = '%s/run.log'%self.currentFolder filename2 = '%s/error.log'%self.currentFolder self.window().newLogTab('Run',filename1) if self.window().nproc<=1: command = '%s -case %s 1> %s 2> %s &'%(self.solvername,self.currentFolder,filename1,filename2) else: command = 'mpirun -np %s %s -case %s -parallel 1> %s 2> %s & '%(str(self.window().nproc),self.solvername,self.currentFolder,filename1, filename2) os.system(command) if self.window().nproc<=1: command = 'pidof %s'%self.solvername else: command = 'pidof mpirun' import subprocess self.window().runningpid = subprocess.check_output(command, shell=True) self.window().runningpid.replace('\n','') #Me lo devuelve con un espacio al final self.window().runningpid = int(self.window().runningpid) #Y como string self.window().save_config() self.pushButton_run.setEnabled(False) self.pushButton_reset.setEnabled(False) self.window().tab_mesh.setEnabled(False) self.window().refresh_pushButton.setEnabled(False) leave = [1,5] for i in range(self.window().treeWidget.topLevelItemCount()): if i not in leave: self.window().treeWidget.topLevelItem(i).setDisabled(True) self.window().findChild(logTab,'%s/run.log'%self.currentFolder).findChild(QtGui.QPushButton,'pushButton_3').setEnabled(True) self.window().updateLogFiles()
def make_windfield(self): self.calc_windfield() wind_file = ParsedParameterFile(Path("casedir/0/U.air")) wind_file["internalField"] = self.wind_key for boundary in wind_file["boundaryField"]: if "ground" not in boundary: wind_file["boundaryField"][boundary]["value"] = self.wind_key wind_file.writeFile()
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 case_setup(ci): template_case = SolutionDirectory( "template", archive=None, paraviewLink=False) case = template_case.cloneCase("{0}".format(ci.name)) stfproperties = ParsedParameterFile(path.join( case.name, "constant", "STFProperties")) stfproperties["apparentMass"] = ci.ma stfproperties["mass"] = ci.m stfproperties.writeFile()
def edit_decompseParDict(dictionary, cores=4): try: tqdm.write("{}: Editing decompseParDict: {}".format( datetime.datetime.now(), dictionary)) decompseParDict = ParsedParameterFile(dictionary) available_core_config = [2, 4, 8, 12] if cores not in available_core_config: raise ValueError( "Invalid core numbers, possible choices: (2, 4, 8, 12)") decompseParDict["numberOfSubdomains"] = cores if decompseParDict["numberOfSubdomains"] == 2: simpleCoeffs = {"n": str("(2 1 1)"), "delta": 0.001} hierarchicalCoeffs = { "n": str("(2 1 1)"), "delta": 0.001, "order": "xyz" } elif decompseParDict["numberOfSubdomains"] == 4: simpleCoeffs = {"n": str("(2 2 1)"), "delta": 0.001} hierarchicalCoeffs = { "n": str("(2 2 1)"), "delta": 0.001, "order": "xyz" } elif decompseParDict["numberOfSubdomains"] == 8: simpleCoeffs = {"n": str("(2 2 2)"), "delta": 0.001} hierarchicalCoeffs = { "n": str("(2 2 2)"), "delta": 0.001, "order": "xyz" } elif decompseParDict["numberOfSubdomains"] == 12: simpleCoeffs = {"n": str("(3 2 2)"), "delta": 0.001} hierarchicalCoeffs = { "n": str("(3 2 2)"), "delta": 0.001, "order": "xyz" } decompseParDict["simpleCoeffs"] = simpleCoeffs decompseParDict["hierarchicalCoeffs"] = hierarchicalCoeffs try: decompseParDict.writeFile() except IOError: tqdm.write("Can't write file. Content would have been:") tqdm.write(decompseParDict) except IOError: tqdm.write(dictionary, " does not exist") return 1
def setBoundaries(self): boundfile = os.path.join(self.constfolder_,"polyMesh","boundary") boundDict = ParsedParameterFile(boundfile,boundaryDict=True) nbound = int(len(boundDict)/2) for i in range(nbound): if boundDict[2*i] in ['domainX0','domainX1']: if self.ndim>2: boundDict[2*i+1]['type'] = 'patch' else: boundDict[2*i+1]['type'] = 'empty' elif self.symmetry>0 and (boundDict[2*i] in ['domainY0']): if self.symmetry==1: boundDict[2*i+1]['type'] = 'symmetry' elif self.symmetry==2: boundDict[2*i+1]['type'] = 'symmetryPlane' boundDict.writeFile()