def pyFoamDict(self, application="foamStar"): d = DictProxy() if application == "foamStar": # for key, val in self.waveCondition.pyFoamDict(application = application).items(): # d[key] = val d["${}Wave".format(self.name)] = "" else: d["waveTheoryName"] = waveTypeDict[ self.waveCondition.waveType][application] if self.relax: r = DictProxy() if self.patchNames is None: r["zoneName"] = self.name + "Zone" # r["relaxationScheme"] = "spatial" r["origin"] = Vector(*self.origin) r["orientation"] = Vector(*self.orientation) # r["relaxationShape"] = "rectangular" else: r["relaxationScheme"] = "farfield" r["zoneName"] = self.name + "Zone" r["farfieldDistance"] = self.length r["blendingDistance"] = self.length * 0.95 r["farfieldPatchNames"] = self.patchNames d["relaxationZone"] = r return d
def testMakeDictionaryProxy(self): d=DictProxy() d["b"]=2 d["a"]=1 g=FoamFileGenerator(d) self.assertEqual(str(g),"b 2;\na 1;\n") d=DictProxy() d["a"]=1 d["b"]=2 g=FoamFileGenerator(d) self.assertEqual(str(g),"a 1;\nb 2;\n") d=DictProxy() d[u("a")]=1 d["b"]=u("2") g=FoamFileGenerator(d) self.assertEqual(str(g),"a 1;\nb 2;\n")
def p_dictionary(self, p): '''dictionary : '{' enter_dict dictbody '}' exit_dict | '{' '}' ''' if len(p) == 6: p[0] = p[5] else: p[0] = DictProxy()
def pyFoamDict(self, application="foamStar"): d = DictProxy() d["waveType"] = waveTypeDict[self.waveType][application] if self.waveType != "noWaves": d["height"] = self.height d["period"] = self.period d["depth"] = self.depth d["refTime"] = self.startTime d["startTime"] = self.startTime d["rampTime"] = self.rampTime if self.waveType == "streamFunction": d["order"] = 25 if application == "foamExtend" or application == "swenseFoam": d["wind"] = Vector(0., 0., 0.) d["currentType"] = "constantCurrent" d["U0"] = Vector(0, 0., 0.) d["setEulerianCurrent"] = True d["EulerianCurrent"] = self.U0 d["waveDirection"] = Vector(*self.refDirection) d["phi"] = 0. #In wave2foam, with "EulerianCurrent", input is encounter period # d["period"] = 2*pi / omega2omegae(2*pi / self.period , v = self.U0, beta = 180.) elif application == "foamStar": if self.waveType != "noWaves": d["refDirection"] = Vector(*self.refDirection) d["U0"] = Vector(self.U0, 0., 0.) d["EulerianCurrent"] = 0.0 else: raise (Exception("Application not known {}".format(application))) return d
def testMakeDictionaryProxyBool(self): d=DictProxy() d["b"]=True d["a"]=False g=FoamFileGenerator(d) self.assertEqual(str(g),"b yes;\na no;\n") self.assertEqual(g.makeString(firstLevel=True),"b yes;\na no;\n")
def setWaveProbes(waveProbesList, application="foamStar", writeProbesInterval=0.1, OFversion=5): d = DictProxy() d["type"] = "surfaceElevation" d["fields"] = "({})".format(alpha[application]) d["writePrecision"] = 6 d["interpolationScheme"] = "cellPointFace" if OFversion == 5: d["writeControl"] = "timeStep" d["writeInterval"] = 1 else: d["outputControl"] = "timeStep" d["outputInterval"] = 1 if application != "foamStar": # navalFoam ? d["file"] = "surfaceElevation.dat" if writeProbesInterval is not None: d["surfaceSampleDeltaT"] = writeProbesInterval d["sets"] = [ "p_{0:05} {{start ({1:} {2:} {3:}); end ({1:} {2:} {4:}); type face; axis z; nPoints {5:}; }}" .format(i, *p) for i, p in enumerate(waveProbesList) ] return d
def parse(self, content): """Constructs a representation of the file""" temp = ParsedParameterFile.parse(self, content) self.content = DictProxy() for i in range(0, len(temp), 2): self.content[temp[i]] = temp[i + 1] return self.content
def manipulate(self,content): lenData=2+2+(2*7+3)+2 rawData=zip(*[content[i::lenData] for i in range(lenData)]) content=DictProxy() for d in rawData: name=d[0] data=d[2:] used=0 specDict={} specDict["nMoles"]=data[used] specDict["molWeight"]=data[used+1] used+=2 thermDict={} thermDict["Tlow"]=data[used] thermDict["Thigh"]=data[used+1] thermDict["Tcommon"]=data[used+2] thermDict["highCpCoeffs"]=list(data[used+3:used+3+7]) thermDict["lowCpCoeffs"]=list(data[used+3+7:used+3+2*7]) used+=2*7+3 transDict={} transDict["As"]=data[used] transDict["Ts"]=data[used+1] used+=2 if len(data)!=used: warning("Not all data for",name,"used:",used,len(data)) comment=self.makeComment(d) content[name]={"specie":specDict, "thermodynamics":thermDict, "transport":transDict} content.addDecoration(name,comment) return content
def __init__(self, name, backup=False, className="dictionary", objectName=None, createZipped=False, **kwargs): ParsedParameterFile.__init__(self, name, backup=backup, dontRead=True, createZipped=createZipped, **kwargs) if objectName == None: objectName = path.basename(name) self.content = DictProxy() self.header = { "version": "2.0", "format": "ascii", "class": className, "object": objectName }
case, mdFile=None, modes2use=None, datFile=None, dmigFile=None, draft=0., scale=1., vtkOut=True, hullPatch=None, localPts=None): res = cls(name=join(case, getFilePath("initFlexDict")), read=False) res.header["class"] = "dictionary" fem = DictProxy() fem["mdFile"] = '"../{}"; selected ( '.format( mdFile) + len(modes2use) * '{} '.format(*modes2use) + ')' fem["datFile"] = '"../{}"'.format(datFile) fem["dmigMfile"] = '"../{}"'.format(dmigFile) fem["dmigKfile"] = '"../{}"'.format(dmigFile) fem["pchCoordinate"] = SymmTensor(*[0, 0, -draft, 0, 0, 0]) fem["pchScaleMode"] = scale fem["pchLengthUnit"] = 1 fem["pchMassUnit"] = 1 if not vtkOut: fem["outputToVTK"] = "no" fem["patches"] = "({})".format(hullPatch) fem["ySym"] = "(true)" if localPts is not None: if len(localPts) > 0: fem["pointList"] = "(localMotion)"
""" Convenience class to simply write boudary condition for sea-keeping case """ class BoundaryOmega(ReadWriteFile): @classmethod def Build(cls, case, symmetry=1, wallFunction=False, application="foamStar", namePatch=namePatch, omega=2., case2D=False): patch = namePatch[application] res = cls(name=join(case, getFilePath("boundaryOmega")), read=False) res.header["class"] = "volScalarField" res["dimensions"] = Dimension(*[0, 0, -1, 0, 0, 0, 0]) res["internalField"] = "uniform {}".format(omega) bf = DictProxy() bf[patch["outlet"]] = {"type": "fixedValue", "value": omega} bf[patch["inlet"]] = {"type": "fixedValue", "value": omega} if application == "foamStar": bf[patch["side1"]] = {"type": "fixedValue", "value": omega} bf[patch["side2"]] = {"type": "fixedValue", "value": omega} else: bf[patch["side"]] = {"type": "fixedValue", "value": omega} bf[patch["bottom"]] = {"type": "fixedValue", "value": omega} bf[patch["top"]] = {"type": "fixedValue", "value": omega} bf[patch["structure"]] = {"type": "zeroGradient"} bf["defaultFaces"] = {"type": "empty"} res["boundaryField"] = bf if wallFunction: res["boundaryField"][patch["structure"]] = {"type": "omegaWallFunction"}
FvSchemes dictionnary """ @classmethod def Build(cls, case, application="foamStar", prsJump=False, orthogonalCorrection=False, blendCN=0.9, simType="steady", limitedGrad=False): res = cls(name=join(case, getFilePath("fvSchemes")), read=False) #-------- ddtSchemes ddt = DictProxy() if simType.lower() == "steady": ddt["default"] = "steadyState" ddt["ddt(U)"] = "Euler" ddt["ddt(alpha.water)"] = "Euler" elif simType.lower() == "euler": ddt["default"] = "Euler" ddt["ddt(U)"] = "Euler" else: ddt["default"] = "CrankNicolson {}".format(blendCN) ddt["ddt(rho,U)"] = "backward" ddt["ddt(U)"] = "Euler" res["ddtSchemes"] = ddt #-------- gradSchemes grad = DictProxy()
import PyFoam from ideFoam.inputFiles import ReadWriteFile, getFilePath from PyFoam.Basics.DataStructures import DictProxy from os.path import join from copy import deepcopy """ Convenience class to simply write "fvSheme" """ GAMG_prec_1 = DictProxy() GAMG_prec_1["preconditioner"] = "GAMG" GAMG_prec_1["tolerance"] = 1e-7 GAMG_prec_1["relTol"] = 0 GAMG_prec_1["smoother"] = "DICGaussSeidel" GAMG_prec_1["nPreSweeps"] = 0 GAMG_prec_1["nPostSweeps"] = 2 GAMG_prec_1["nFinestSweeps"] = 2 GAMG_prec_1["cacheAgglomeration"] = "false" GAMG_prec_1["nCellsInCoarsestLevel"] = 10 GAMG_prec_1["agglomerator"] = "faceAreaPair" GAMG_prec_1["mergeLevels"] = 1 GAMG_prec_2 = DictProxy() GAMG_prec_2["preconditioner"] = "GAMG" GAMG_prec_2["tolerance"] = 1e-7 GAMG_prec_2["relTol"] = 0 GAMG_prec_2["nVcycles"] = 2 GAMG_prec_2["smoother"] = "DICGaussSeidel" GAMG_prec_2["nPreSweeps"] = 2
geometricCut=True, writeMesh=False): """Create RefineMeshDict from a few parameter """ suffix = '' if orient is not None: suffix += '.' + orient if name is not None: suffix += '.' + name res = cls(join(case, "system", "refineMeshDict" + suffix), read=False) res["set"] = set if refineUptoCellLevel is not None: res["refineUptoCellLevel"] = refineUptoCellLevel res["coordinateSystem"] = coordinateSystem globalCoef = DictProxy() globalCoef["tan1"] = "(1 0 0)" globalCoef["tan2"] = "(0 1 0)" res["globalCoeffs"] = globalCoef if orient is None: patchCoef = DictProxy() if patch == "outside": patchCoef["patch"] = patch patchCoef["tan1"] = "(1 0 0)" else: patchCoef["patch"] = "patchName" patchCoef["tan1"] = "(0 1 0)" patchCoef["tan2"] = "(0 0 1)" res["patchLocalCoeffs"] = patchCoef
Convenience class to simply write SurfaceFeatureExtractDict """ class SurfaceFeatureExtractDict(ReadWriteFile): """ SurfaceFeatureExtractDict dictionary """ @classmethod def Build(cls, case, stlname="body"): res = cls(name=join(case, getFilePath("surfaceFeatureExtractDict")), read=False) stlname = stlname.split('.stl')[0] #remove .stl extension body = DictProxy() body["extractionMethod"] = "extractFromSurface" body["extractFromSurfaceCoeffs"] = {"includedAngle": 150.} body["subsetFeatures"] = { "nonManifoldEdges": "yes", "openEdges": "yes" } body["writeObj"] = "yes" res[stlname + ".stl"] = body return res if __name__ == "__main__": print(SurfaceFeatureExtractDict.Build("test"))
OpenFOAM version used """ res = cls(name=join(case, getFilePath("snappyHexMeshDict")), read=False) stlname = stlname.split('.stl')[0] #remove .stl extension res["#inputMode"] = "overwrite" res["castellatedMesh"] = castellatedMesh res["snap"] = snap res["addLayers"] = addLayers geometry = DictProxy() body = DictProxy() body["type"] = "triSurfaceMesh" body["name"] = patchName body["patchInfo"] = {"type": "wall"} geometry['"' + stlname + '.stl"'] = body res["geometry"] = geometry castel = DictProxy() castel["maxLocalCells"] = 1000000 castel["maxGlobalCells"] = 10000000 castel["minRefinementCells"] = 0 castel["nCellsBetweenLevels"] = nCellsBetweenLevels castel["locationInMesh"] = "({} {} {})".format(*locationInMesh) castel["features"] = [{
res = cls( name = join(case, getFilePath("extrudeMeshDict") ), read = False ) patch = namePatch[version] res["constructFrom"] = "patch" res["sourceCase"] = sourceCase res["sourcePatches"] = [patch[sourcePatch]] res["exposedPatchName"] = patch[exposedPatchName] if flipNormals : res["flipNormals"] = True res["extrudeModel"] = "linearNormal" res["nLayers"] = nLayers res["expansionRatio"] = expansionRatio linCoef = DictProxy() linCoef["thickness"] = thickness res["linearNormalCoeffs"] = linCoef res["mergeFaces"] = mergeFaces res["mergeTol"] = mergeTol return res if __name__ == "__main__" : print(ExtrudeMeshDict.Build("test"))
def manipulate(self,content): newReactions=DictProxy() rData=zip(*[content["reactions"][i::3] for i in range(3)]) cnt=1 for rType,scheme,parameters in rData: name="reaction%d"%cnt cnt+=1 r={} r["type"]=rType r["reaction"]='"'+str(scheme).strip()+'"' if rType in ["irreversibleArrheniusReaction", "reversibleArrheniusReaction"]: r["A"]=parameters[0] r["beta"]=parameters[1] r["Ta"]=parameters[2] elif rType in ["reversiblethirdBodyArrheniusReaction"]: r["A"]=parameters[0][0] r["beta"]=parameters[0][1] r["Ta"]=parameters[0][2] r["defaultEfficiency"]=parameters[1][0] r["coeffs"]=self.makeCoeffList(parameters[1][1:], parameters[1][0], content["species"]) elif rType in ["reversibleArrheniusLindemannFallOffReaction"]: r["k0"]={} r["k0"]["A"]=parameters[0][0] r["k0"]["beta"]=parameters[0][1] r["k0"]["Ta"]=parameters[0][2] r["kInf"]={} r["kInf"]["A"]=parameters[1][0] r["kInf"]["beta"]=parameters[1][1] r["kInf"]["Ta"]=parameters[1][2] r["F"]={} r["thirdBodyEfficiencies"]={} r["thirdBodyEfficiencies"]["defaultEfficiency"]=parameters[2][0] r["thirdBodyEfficiencies"]["coeffs"]=self.makeCoeffList(parameters[2][1:], parameters[2][0], content["species"]) elif rType in ["reversibleArrheniusTroeFallOffReaction"]: r["k0"]={} r["k0"]["A"]=parameters[0][0] r["k0"]["beta"]=parameters[0][1] r["k0"]["Ta"]=parameters[0][2] r["kInf"]={} r["kInf"]["A"]=parameters[1][0] r["kInf"]["beta"]=parameters[1][1] r["kInf"]["Ta"]=parameters[1][2] r["F"]={} r["F"]["alpha"]=parameters[2][0] r["F"]["Tsss"]=parameters[2][1] r["F"]["Ts"]=parameters[2][2] r["F"]["Tss"]=parameters[2][3] r["thirdBodyEfficiencies"]={} r["thirdBodyEfficiencies"]["defaultEfficiency"]=parameters[3][0] r["thirdBodyEfficiencies"]["coeffs"]=self.makeCoeffList(parameters[3][1:], parameters[3][0], content["species"]) else: r["unsupported"]=parameters newReactions[name]=r content["reactions"]=newReactions
def p_enter_dict(self, p): '''enter_dict :''' self.dictStack.append(DictProxy())
Zgrading[i]) res["blocks"] = [blockstr] else: ny = Ycells * (1 + (not sym)) rXY = (xmax - xmin) / (ymax - ymin) rYZ = (zmax - zmin) / (ymax - ymin) ny = int(round(ny * (np.sqrt(2)**(gridlvl - 1)))) nz = int(round(ny * rYZ * cellRatio)) if ndim > 2: nx = int(round(ny * rXY)) else: nx = 1 res["blocks"] = '( hex (0 1 2 3 4 5 6 7) ( {:d} {:d} {:d} ) simpleGrading (1 1 1) )'.format( nx, ny, nz) res["edges"] = '()' if createPatch: if patches is not None: res["patches"] = patches else: res["patches"] = default_patches else: faces = DictProxy() faces["type"] = 'patch' faces["faces"] = '()' res["boundary"] = ["defaultFaces", faces] res["mergePatchPairs"] = '()' return res if __name__ == "__main__": print(BlockMeshDict.Build("test"))
def __init__(self, content, fName=None, debug=False, noHeader=False, noBody=False, doMacroExpansion=False, boundaryDict=False, preserveComments=True, preserveNewlines=True, listDict=False, listDictWithHeader=False, listLengthUnparsed=None, binaryMode=False, treatBinaryAsASCII=False, duplicateCheck=False, noVectorOrTensor=False, dictStack=None, duplicateFail=True): """:param content: the string to be parsed :param fName: Name of the actual file (if any) :param debug: output debug information during parsing :param noHeader: switch that turns off the parsing of the header :param duplicateCheck: Check for duplicates in dictionaries :param duplicateFail: Fail if a duplicate is discovered""" self.binaryMode = binaryMode self.treatBinaryAsASCII = treatBinaryAsASCII self.fName = fName self.data = None self.header = None self.debug = debug self.listLengthUnparsed = listLengthUnparsed self.doMacros = doMacroExpansion self.preserveComments = preserveComments self.preserveNewLines = preserveNewlines self.duplicateCheck = duplicateCheck self.duplicateFail = duplicateFail self.noVectorOrTensor = noVectorOrTensor self.inHeader = True self.inBinary = False self.checkPrelistLength = True # Make sure that the first comment is discarded self.collectDecorations = False self.inputMode = inputModes.merge self._decorationBuffer = "" startCnt = 0 self.dictStack = dictStack if self.dictStack == None: self.dictStack = [DictProxy()] if noBody: self.start = 'noBody' startCnt += 1 if noHeader: self.inHeader = False self.start = 'noHeader' startCnt += 1 self.collectDecorations = True if listDict: self.inHeader = False self.start = 'pureList' startCnt += 1 self.dictStack = [] self.collectDecorations = True if listDictWithHeader: self.start = 'pureListWithHeader' startCnt += 1 if boundaryDict: self.start = 'boundaryDict' startCnt += 1 self.checkPrelistLength = False if startCnt > 1: error("Only one start symbol can be specified.", startCnt, "are specified") PlyParser.__init__(self, debug=debug) #sys.setrecursionlimit(50000) #print sys.getrecursionlimit() self.emptyCnt = 0 self.header, self.data = self.parse(content)
@classmethod def Build_imposed(cls, case, dispFile='', cog=[0., 0., 0.], OFversion=5, application="foamStar"): """Build dynamicMeshDict for cases with imposed motions """ res = cls(name=join(case, getFilePath("dynamicMeshDict")), read=False) if OFversion == 5: res["dynamicFvMesh"] = "dynamicMotionSolverFvMesh" res["motionSolver"] = "solidBody" res["solidBodyMotionFunction"] = "tabulated6DoFMotion" tab = DictProxy() tab["timeDataFileName"] = '"' + dispFile + '"' tab["CofG"] = '( {:.6f} {:.6f} {:.6f} )'.format(*cog) res["tabulated6DoFMotionCoeffs"] = tab else: res["dynamicFvMesh"] = "solidBodyMotionFvMesh" sdc = DictProxy() sdc["solidBodyMotionFunction"] = "BVtabulated6DoFMotion" tab = DictProxy() tab["timeDataFileName"] = '"' + dispFile + '"' tab["CofG"] = '( {:.6f} {:.6f} {:.6f} )'.format(*cog) sdc["BVtabulated6DoFMotionCoeffs"] = tab res["solidBodyMotionFvMeshCoeffs"] = sdc return res @classmethod
res["adjustTimeStep"] = "no" res["maxCo"] = 0.5 res["maxAlphaCo"] = 0.5 res["maxDeltaT"] = 1. if application == "foamStar" : res ["libs"] = ['"libfoamStar.so"' , #'"libBVtabulated6DoFMotion.so"', ] elif application == "snappyHexMesh" : pass else : res ["libs"] = [ '"libforces.so"' , ] # Set functions fDict = DictProxy() # Motions if outputMotions: motionDict = DictProxy() motionDict["type"] = "motionInfo" fDict["motionInfo"] = motionDict # Internal loads if vbmPatch is not None : vbmDict = DictProxy() vbmDict["type"] = "internalLoads" if OFversion==5: vbmDict["writeControl"] = "timeStep" vbmDict["writeInterval"] = 1 else:
case, rhoWater=1000, nuWater=1e-6, rhoAir=1., nuAir=1.48e-05, sigma=0.0, application="foamStar"): res = cls(name=join(case, getFilePath("transportProperties")), read=False) res.header["class"] = "dictionary" if application == "foamStar": res["phases"] = ["water", "air"] dw = DictProxy() dw["transportModel"] = "Newtonian" dw["nu"] = "nu [0 2 -1 0 0 0 0] {}".format(nuWater) dw["rho"] = "rho [1 -3 0 0 0 0 0] {}".format(rhoWater) res['"' + water[application] + '"'] = dw da = DictProxy() da["transportModel"] = "Newtonian", da["nu"] = "nu [0 2 -1 0 0 0 0] {}".format(nuAir) da["rho"] = "rho [1 -3 0 0 0 0 0] {}".format(rhoAir) res['"' + air[application] + '"'] = da res[r"sigma"] = "sigma [1 0 -2 0 0 0 0] {}".format(sigma) return res