示例#1
0
    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)
示例#2
0
    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)
示例#3
0
    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
示例#4
0
 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())
示例#5
0
    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
示例#6
0
 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())
示例#7
0
文件: bc.py 项目: dwstephens/petroSym
    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)
示例#8
0
 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
示例#9
0
 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)
示例#10
0
    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")
示例#11
0
 def boundary_dict_path(self):
     return BoundaryDict(self.path).realName()
示例#12
0
 def boundary_dict(self):
     return BoundaryDict(self.path)
示例#13
0
 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)
示例#14
0
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()
示例#15
0
    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