Beispiel #1
0
    def blockMesh(self):
        '''This functions configures and runs blockMeshDict'''

        ## The first step is to configure the domain for blockMeshDict based on the stl file
        self.blockMeshDomain()
        ## That file gets written to file
        self.blockMeshDict.writeFile()
        ## And we run blockMeshDict
        Runner(args=["--silent","blockMesh","-case",self.casePath])
        Runner(args=["--silent","surfaceFeatureExtract","-case",self.casePath])
Beispiel #2
0
    def execute(self,*args,**kwargs):
        """Execute the passed arguments on the case and check if
        everything went alright
        @param regexps: a list of regular expressions that the output should be scanned for"""

        try:
            regexps=kwargs["regexps"]
            if type(regexps)!=list:
                self.fail(regexps,"is not a list of strings")
                raise KeyError
        except KeyError:
            regexps=None

        if len(args)==1 and type(args[0])==str:
            args=[a.replace("%case%",self.solution().name) for a in args[0].split()]

        pyArgs=["--silent","--no-server-process"]
        if self.__runParallel:
            pyArgs+=["--procnr=%d" % self["nrCpus"]]

        argList=list(args)+\
                 ["-case",self.caseDir]
        self.status("Executing"," ".join(argList))
        if regexps:
            self.status("Also looking for the expressions",'"'+('" "'.join(regexps))+'"')
            pyArgs+=[r'--custom-regexp=%s' % r for r in regexps]

        runner=Runner(args=pyArgs+argList)
        self.status("Execution ended")

        if not runner["OK"]:
            self.fail("Running "," ".join(argList),"failed")
        else:
            self.status("Execution was OK")
        if "warnings" in runner:
            self.status(runner["warnings"],"during execution")
        print_()
        self.status("Output of"," ".join(argList),":")
        if runner["lines"]>(self.__tailLength+self.__headLength):
            self.status("The first",self.__headLength,"lines of the output.",
                        "Of a total of",runner["lines"])
            self.line()
            self.runCommand("head","-n",self.__headLength,runner["logfile"])
            self.line()
            print_()
            self.status("The last",self.__tailLength,"lines of the output.",
                        "Of a total of",runner["lines"])
            self.line()
            self.runCommand("tail","-n",self.__tailLength,runner["logfile"])
            self.line()
        else:
            self.line()
            self.runCommand("cat",runner["logfile"])
            self.line()

        self.status("End of output")
        print_()

        return runner
Beispiel #3
0
    def cfMesh(self, path, ):
        os.rename(self.casePath+'/0', self.casePath+'/0.snappy')
        os.rename(self.casePath+'/0.cfMesh', self.casePath+'/0')
        dx = (self.stlSolid.bb[1]-self.stlSolid.bb[0])
        dy = (self.stlSolid.bb[3]-self.stlSolid.bb[2])
        dz = (self.stlSolid.bb[5]-self.stlSolid.bb[4])

        # Configure the downwindBox
        self.cfMeshDict['objectRefinements']['downwindBox']['centre'] = [0.75*dx, 0, 0]
        self.cfMeshDict['objectRefinements']['downwindBox']['lengthX'] = 2.5 * dx
        self.cfMeshDict['objectRefinements']['downwindBox']['lengthY'] = 1.4 * dy
        self.cfMeshDict['objectRefinements']['downwindBox']['lengthZ'] = 1.4 * dz
        self.cfMeshDict['objectRefinements']['downwindBox']['cellSize'] = 0.025
        self.cfMeshDict.writeFile()

        Runner(args=['--silent',"surfaceGenerateBoundingBox",'-case',self.casePath, path, self.casePath+'/box.stl', 2*dx, 8*dx, 2*dy, 2*dy, 4*dz, 4*dz ])
        Runner(args=['--silent',"cartesianMesh",'-case',self.casePath])
        Runner(args=['--silent',"checkMesh",'-case',self.casePath])
        exit()
Beispiel #4
0
 def sampleCases(self, cases, work, wind_dict):
     # TODO - at the moment for 90 degrees phi only and in line instead of in a function
     for case in cases:
         self._r.status('preparing Sample file for case '+case.name)
         sampleFile = ParsedParameterFile(path.join(case.systemDir(), "sampleDict"))
         self.writeMetMastLocations(case) # will replace the following 4 lines
         sampleFile['sets'][1]['start'] = "("+str(-wind_dict['SHMParams']['domainSize']['fXup']*0.99)+" "+str(0)+" "+str(wind_dict['SHMParams']['domainSize']['z_min'])+")"
         sampleFile['sets'][1]['end'] = "("+str(-wind_dict['SHMParams']['domainSize']['fXup']*0.99)+" "+str(0)+" "+str(wind_dict['SHMParams']['domainSize']['z_min']+50)+")"
         sampleFile['sets'][3]['start'] = "("+str(wind_dict['SHMParams']['centerOfDomain']['x0'])+" "+str(0)+" "+str(wind_dict['SHMParams']['domainSize']['typical_height'])+")"
         sampleFile['sets'][3]['end'] = "("+str(wind_dict['SHMParams']['centerOfDomain']['x0'])+" "+str(0)+" "+str(wind_dict['SHMParams']['domainSize']['typical_height']+50)+")"
         del sampleFile.content['surfaces'][:]
         for i,h in enumerate(wind_dict['sampleParams']['hSample']):
             self._r.status('preparing sampling surface at '+str(h)+' meters agl')
             translateSTL.stl_shift_z_filenames(path.join(case.name,'constant/triSurface/terrain.stl'), path.join(case.name,'constant/triSurface/terrain_agl_'+str(h)+'.stl'), h)
             sampleFile.content['surfaces'].append('agl_'+str(h))
             sampleFile.content['surfaces'].append(['agl_'+str(h)])
             sampleFile['surfaces'][len(sampleFile['surfaces'])-1]={'type':'sampledTriSurfaceMesh','surface':'terrain_agl_'+str(h)+'.stl','source':'cells'}
         sampleFile.writeFile()
         self._r.status('Sampling case '+case.name)
         Runner(args=["sample" ,"-latestTime", "-case" ,case.name])
Beispiel #5
0
    def __init__(self, casedir, nprocs=None, parserArgs=None):
        self.casePath = casedir
        self.procsUtil = Utilities.parallelUtilities(nprocs)
        self.decomposeParDict = ParsedParameterFile(
            os.path.join(self.casePath, 'system', 'decomposeParDict'))
        if parserArgs:
            self.modifyDicts(parserArgs)

        if self.procsUtil.procs > 1:
            self.parallel = True
            self.nprocs = self.procsUtil.procs
            print 'Using %s processors based on procsUtil' % self.nprocs
            self.decomposeParDict['numberOfSubdomains'] = self.nprocs
            self.decomposeParDict.writeFile()
        else:
            self.parallel = False
            self.nprocs = 1
        if self.parallel:
            for file in glob.glob(self.casePath + '/processor*'):
                shutil.rmtree(file)
            Runner(args=["decomposePar", "-case", self.casePath])
            Runner(args=[
                "--proc=%s" % self.nprocs, "potentialFoam", "-case",
                self.casePath, "-noFunctionObjects"
            ])
            Runner(args=[
                "--proc=%s" % self.nprocs, "simpleFoam", "-case", self.casePath
            ])
            Runner(args=[
                "reconstructParMesh", "-mergeTol", "1e-6", "-constant",
                "-case", self.casePath
            ])
            Runner(args=["reconstructPar", "-case", self.casePath])
            for file in glob.glob(self.casePath + '/processor*'):
                shutil.rmtree(file)
        else:
            runner = Runner(args=["simpleFoam", "-case", self.casePath])
Beispiel #6
0
 def reconstructCases(self, cases):
     for case in cases:
         Runner(args=["reconstructPar" ,"-latestTime", "-case" ,case])
Beispiel #7
0
    def snappyHexMesh(self):
        '''
        This function runs snappyHexMesh for us
        '''
        ## First, lets add a few refinement regions based on the geometry

        ## The first is a box that surrounds the aircraft and extends downwind by three body lengths
        self.snappyHexMeshDict['geometry']['downwindbox'] = {}
        dwBox = self.snappyHexMeshDict['geometry']['downwindbox']
        dwBox['type'] = 'searchableBox'
        boxenlarge = 2.5
        dwBox['min'] = [
            boxenlarge * self.stlSolid.bb[0], boxenlarge * self.stlSolid.bb[2],
            boxenlarge * self.stlSolid.bb[4]
        ]
        dwBox['max'] = [
            boxenlarge * self.stlSolid.bb[1] + 4 *
            (self.stlSolid.bb[1] - self.stlSolid.bb[0]),
            boxenlarge * self.stlSolid.bb[3], boxenlarge * self.stlSolid.bb[5]
        ]

        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'downwindbox'] = {}
        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'downwindbox']['mode'] = 'inside'
        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'downwindbox']['levels'] = [[1, 4]]
        self.snappyHexMeshDict['castellatedMeshControls']['locationInMesh'][
            0] = dwBox['min'][0]
        self.snappyHexMeshDict['castellatedMeshControls']['locationInMesh'][
            1] = dwBox['min'][1]
        self.snappyHexMeshDict['castellatedMeshControls']['locationInMesh'][
            2] = dwBox['min'][2]

        ## Next we add some refinement regions around the wing tips
        self.snappyHexMeshDict['geometry']['wingtip1'] = {}
        wt1Box = self.snappyHexMeshDict['geometry']['wingtip1']
        wt1Box['type'] = 'searchableCylinder'
        wt1Box['point1'] = self.stlSolid.yminPoint.tolist()
        ## Next point is 6 meters downwind
        wt1Box['point2'] = [
            sum(x) for x in zip(self.stlSolid.yminPoint, [6, 0, 0])
        ]
        wt1Box['radius'] = .2

        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'wingtip1'] = {}
        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'wingtip1']['mode'] = 'inside'
        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'wingtip1']['levels'] = [[1, 5]]

        ## Next we add some refinement regions around the wing tips
        self.snappyHexMeshDict['geometry']['wingtip2'] = {}
        wt2Box = self.snappyHexMeshDict['geometry']['wingtip2']
        wt2Box['type'] = 'searchableCylinder'
        wt2Box['point1'] = self.stlSolid.ymaxPoint.tolist()
        ## Next point is 6 meters downwind
        wt2Box['point2'] = [
            sum(x) for x in zip(self.stlSolid.ymaxPoint, [6, 0, 0])
        ]
        wt2Box['radius'] = .2

        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'wingtip2'] = {}
        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'wingtip2']['mode'] = 'inside'
        self.snappyHexMeshDict['castellatedMeshControls']['refinementRegions'][
            'wingtip2']['levels'] = [[1, 5]]

        ## Save the snappyHexMeshDict file
        self.snappyHexMeshDict.writeFile()

        ## We need to know if we should run this in parallel
        if self.parallel:
            ## Ok, running in parallel. Lets first configure the decomposePar dict based on the number of processors we have
            self.decomposeParDict['numberOfSubdomains'] = self.nprocs
            self.decomposeParDict.writeFile()
            ## The we decompose the case (Split up the problem into a few subproblems)
            Runner(args=[
                '--silent', "decomposePar", "-force", "-case", self.casePath
            ])

            ## Then run snappyHexMesh to build our final mesh for the simulation, also in parallel
            print "Starting snappyHexMesh"
            # Runner(args=['--silent', "--proc=%s"%self.nprocs,"snappyHexMesh","-overwrite","-case",self.casePath])
            Runner(args=[
                "--proc=%s" % self.nprocs, "snappyHexMesh", "-overwrite",
                "-case", self.casePath
            ])
            ## Finally, we combine the mesh back into a single mesh. This allows us to decompose it more intelligently for simulation

            Runner(args=[
                '--silent', "reconstructParMesh", "-constant", "-case",
                self.casePath
            ])
        else:
            ## No parallel? Ok, lets just run snappyHexMesh
            Runner(args=[
                '--silent', "snappyHexMesh", "-overwrite", "-case",
                self.casePath
            ])
Beispiel #8
0
    def foamRun(self,application,
                args=[],
                foamArgs=[],
                steady=False,
                multiRegion=True,
                progress=False,
                compress=False,
                noLog=False):
        """Runs a foam utility on the case.
        If it is a parallel job and the grid has
        already been decomposed (and not yet reconstructed) it is run in
        parallel
        @param application: the Foam-Application that is to be run
        @param foamArgs: A list if with the additional arguments for the
        Foam-Application
        @param compress: Compress the log-file
        @param args: A list with additional arguments for the Runner-object
        @param steady: Use the steady-runner
        @param multiRegion: Run this on multiple regions (if None: I don't have an opinion on this)
        @param progress: Only output the time and nothing else
        @param noLog: Do not generate a logfile"""

        arglist=args[:]
        arglist+=["--job-id=%s" % self.fullJobId()]
        for k,v in iteritems(self.parameters):
            arglist+=["--parameter=%s:%s" % (str(k),str(v))]

        if self.isDecomposed and self.nproc>1:
            arglist+=["--procnr=%d" % self.nproc]
            if config().getboolean("ClusterJob","useMachineFile"):
                arglist+=["--machinefile=%s" % self.hostfile]

        arglist+=["--echo-command-prefix='=== Executing'"]

        if progress:
            arglist+=["--progress"]
        if noLog:
            arglist+=["--no-log"]
        if compress:
            arglist+=["--compress"]

        if self.multiRegion:
            if multiRegion:
                arglist+=["--all-regions"]
        elif multiRegion:
            warning("This is not a multi-region case, so trying to run stuff multi-region won't do any good")

        if self.restarted:
            arglist+=["--restart"]

        arglist+=[application]
        if oldApp():
            arglist+=[".",self.casename()]
        else:
            arglist+=["-case",self.casename()]

        arglist+=foamArgs

        self.message("Executing",arglist)

        if steady:
            self.message("Running Steady")
            runner=SteadyRunner(args=arglist)
        else:
            runner=Runner(args=arglist)
Beispiel #9
0
def runNoPlot((i, d)):
    target, args = d['target'], d['args']
    time.sleep(i * 2)
    print "got %s" % repr(args)
    return Runner(args=args)
Beispiel #10
0
    def sampleDictionaries(self, cases, work, wind_dict):
        # TODO - at the moment for 90 degrees phi only and in line instead of in a function
        for case in cases:
            self._r.status('preparing Sample file for case ' + case.name)
            sampleFile = ParsedParameterFile(
                path.join(case.systemDir(), "sampleDict"))
            del sampleFile.content['sets'][:]
            if len(wind_dict["Measurements"]) > 0:
                self._r.status("creating sample locations for measurements")
                for metMast in wind_dict["Measurements"]:
                    self._r.status("adding met mast " + metMast)
                    # creating sub directory entry
                    sampleFile.content['sets'].append(metMast)
                    # creating another fictional sub directory entry - so that i can run it over in a second
                    sampleFile.content['sets'].append([metMast])
                    sampleFile['sets'][len(sampleFile['sets'])-1] = \
                    {'type':'uniform', 'axis':'z',\
                    'start':'('+str(wind_dict["Measurements"][metMast]["x"])+" "\
                               +str(wind_dict["Measurements"][metMast]["y"])+" "\
                               +str(wind_dict["Measurements"][metMast]["gl"])+")",\
                    'end':  '('+str(wind_dict["Measurements"][metMast]["x"])+" "\
                               +str(wind_dict["Measurements"][metMast]["y"])+" "\
                               +str(wind_dict["Measurements"][metMast]["gl"]+\
                                    wind_dict["Measurements"][metMast]["h"])+")",\
                    'nPoints':wind_dict['sampleParams']['nPoints']}
            if len(wind_dict['sampleParams']['metMasts']) > 0:
                self._r.status("creating sample locations for sampleParams")
                for metMast in wind_dict['sampleParams']['metMasts']:
                    # creating sub directory entry
                    sampleFile.content['sets'].append(metMast)
                    # creating another fictional sub directory entry - so that i can run it over in a second
                    sampleFile.content['sets'].append([metMast])
                    sampleFile['sets'][len(sampleFile['sets'])-1] = \
                    {'type':'uniform', 'axis':'z',\
                    'start':'('+str(wind_dict["sampleParams"]["metMasts"][metMast]["x"])+" "\
                               +str(wind_dict["sampleParams"]["metMasts"][metMast]["y"])+" "\
                               +str(wind_dict["sampleParams"]["metMasts"][metMast]["gl"])+")",\
                    'end':  '('+str(wind_dict["sampleParams"]["metMasts"][metMast]["x"])+" "\
                               +str(wind_dict["sampleParams"]["metMasts"][metMast]["y"])+" "\
                               +str(wind_dict["sampleParams"]["metMasts"][metMast]["gl"]+\
                                    wind_dict["sampleParams"]["metMasts"][metMast]["h"])+")",\
                    'nPoints':wind_dict['sampleParams']['nPoints']}

            del sampleFile.content['surfaces'][:]
            for i, h in enumerate(wind_dict['sampleParams']['hSample']):
                self._r.status('preparing sampling surface at ' + str(h) +
                               ' meters agl')
                translateSTL.stl_shift_z_filenames(
                    path.join(case.name, 'constant/triSurface/terrain.stl'),
                    path.join(
                        case.name,
                        'constant/triSurface/terrain_agl_' + str(h) + '.stl'),
                    h)
                # creating sub directory entry
                sampleFile.content['surfaces'].append('agl_' + str(h))
                # creating another fictional sub directory entry - so that i can run it over in a second
                sampleFile.content['surfaces'].append(['agl_' + str(h)])
                sampleFile['surfaces'][len(sampleFile['surfaces']) - 1] = {
                    'type': 'sampledTriSurfaceMesh',
                    'surface': 'terrain_agl_' + str(h) + '.stl',
                    'source': 'cells'
                }
            sampleFile.writeFile()
            self._r.status('Sampling case ' + case.name)
            Runner(args=["sample", "-latestTime", "-case", case.name])
Beispiel #11
0
#!C:\Users\Lee\Anaconda3\python.exe

from PyFoam.Applications.Runner import Runner

Runner()
Beispiel #12
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys, math, os
from os import path
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory
from PyFoam.Basics.TemplateFile import TemplateFile
from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile
from PyFoam.Basics.DataStructures import Vector
from PyFoam.Execution.BasicRunner import BasicRunner
from PyFoam.Applications.PlotRunner import PlotRunner
from PyFoam.Applications.Runner import Runner
from PyFoam.Applications.Decomposer import Decomposer
from PyFoam.Applications.CaseReport import CaseReport
from PyFoam.Execution.ParallelExecution import LAMMachine
from PyFoam.Applications.PotentialRunner import PotentialRunner
from numpy import *
from pylab import *
import matplotlib.pyplot as plt
import os, glob, subprocess
from matplotlib.backends.backend_pdf import PdfPages

Runner(args=[" reconstructPar ", " -latestTime", " -case ", work.name])
Beispiel #13
0
import sys
case = "/home/weibin/test"

from PyFoam.Applications.Decomposer import Decomposer
from PyFoam.Applications.Runner import Runner
from PyFoam.Applications.PlotRunner import PlotRunner
PlotRunner(args=["--progress", "Decomposer", "proc", 2, "-case", case])
PlotRunner(args=["--clear", "blockMesh", "-case", case])
Runner(args=["--progress", "icoFoam", "-case", case])