Exemple #1
0
    def __init__(self,analyzer,
                 argv=None,
                 silent=False,
                 logname="PyFoamSolve",
                 server=False,
                 lam=None,
                 compressLog=False,
                 restart=False,
                 noLog=False,
                 logTail=None,
                 remark=None,
                 parameters=None,
                 jobId=None,
                 smallestFreq=60.,
                 echoCommandLine=None):
        """ @param analyzer: the analyzer for the output
        argv, silent, logname, server, lam, noLog - see BasicRunner"""
        BasicRunner.__init__(self,argv,silent,logname,
                             server=server,
                             lam=lam,
                             restart=restart,
                             compressLog=compressLog,
                             noLog=noLog,
                             logTail=logTail,
                             remark=remark,
                             parameters=parameters,
                             echoCommandLine=echoCommandLine,
                             jobId=jobId)
        StepAnalyzedCommon.__init__(self,
                                    logname,
                                    analyzer,
                                    smallestFreq=smallestFreq)

        self.writeToStateFile("LogDir",self.logDir)
Exemple #2
0
def processCase_2dHill(template0, target0, hillName, AR, r, x, Ls, L, L1, H,
                       x0, z0, us, yM, h, caseType):

    caseStr = "_AR_" + str(AR) + "_z0_" + str(z0)
    if caseType == "Crude": caseStr = caseStr + "Crude"
    target = target0 + caseStr

    # sample results
    dirNameList = glob.glob(target + "*")
    dirNameList.sort()
    for dirName in dirNameList:
        # sampling
        arg = " -case " + dirName + "/"
        sampleRun = BasicRunner(argv=["sample -latestTime" + arg],
                                silent=True,
                                server=False,
                                logname="sampleLog")
        sampleRun.start()
#finding the most converged run.
    setName = glob.glob(dirName + '/sets/*')
    lastRun = range(len(setName))
    for num in range(len(setName)):
        lastRun[num] = int(setName[num][setName[num].rfind("/") + 1:])
    m = max(lastRun)
    p = lastRun.index(m)
    data_y = genfromtxt(setName[p] + '/line_y_U.xy', delimiter=' ')
    y, Ux_y, Uy_y = data_y[:, 0], data_y[:, 1], data_y[:, 2]
    if AR < 1000:  # if terrain isn't flat
        y = y - h  # normalizing data to height of hill-top above ground

    return y, Ux_y, Uy_y
Exemple #3
0
 def run_block_mesh(self, work):
     blockRun = BasicRunner(argv=["blockMesh", '-case', work.name],
                         silent=True, server=False, logname="blockMesh")
     self._r.status("Running blockMesh")
     blockRun.start()
     if not blockRun.runOK():
         self._r.error("there was an error with blockMesh")
def processCase_2dHill(template0, target0, hillName, AR, r, x, Ls, L, L1, H, x0, z0, us, yM, h, caseType):

	caseStr = "_AR_" + str(AR) + "_z0_" + str(z0)
	if caseType=="Crude": caseStr = caseStr + "Crude"
  	target = target0+caseStr
  	
    # sample results
	dirNameList = glob.glob(target + "*")
	dirNameList.sort()
	for dirName in dirNameList:
 		# sampling
 		arg = " -case " + dirName + "/"
 		sampleRun = BasicRunner(argv=["sample -latestTime" + arg],silent=True,server=False,logname="sampleLog")
		sampleRun.start()
 	#finding the most converged run.
  	setName =  glob.glob(dirName + '/sets/*')
  	lastRun = range(len(setName))
	for num in range(len(setName)):
		lastRun[num] = int(setName[num][setName[num].rfind("/")+1:])
  	m = max(lastRun)
  	p = lastRun.index(m)
	data_y = genfromtxt(setName[p] + '/line_y_U.xy',delimiter=' ')
  	y, Ux_y, Uy_y  = data_y[:,0], data_y[:,1], data_y[:,2] 
	if AR<1000: 	# if terrain isn't flat
		y = y-h # normalizing data to height of hill-top above ground

	return y,Ux_y,Uy_y
Exemple #5
0
def myBasicRunner(command, add=""):
    run = BasicRunner(argv=command + ["-case", work_dir],
                      silent=True,
                      server=False,
                      logname=command[0] + ("." + add if add else add))
    print "Running " + command[0]
    run.start()
 def run_block_mesh(self, work):
     blockRun = BasicRunner(argv=["blockMesh", '-case', work.name],
                         silent=True, server=False, logname="blockMesh")
     self._r.status("Running blockMesh")
     blockRun.start()
     if not blockRun.runOK():
         self._r.error("there was an error with blockMesh")
    def run(self):
        cName=self.parser.getArgs()[0]
        sol=SolutionDirectory(cName,archive=None)
        # self.addLocalConfig(cName)
        initial=sol[0]
        if "U" not in initial or "p" not in initial:
            error("Either 'p' or 'U' missing from the initial directory",initial.baseName())
        if self.opts.writep:
            initial["p.prepotential"]=initial["p"]
        initial["U.prepotential"]=initial["U"]

        lam=self.getParallel(sol)

        if self.opts.writep:
            writep=["-writep"]
        else:
            writep=[]

        argv=["potentialFoam"]
        if oldApp():
            argv+=[".",cName]
        else:
            argv+=["-case",cName]

        self.setLogname(default="Potential",useApplication=False)

        self.checkAndCommit(sol)

        run=BasicRunner(argv=argv+writep,
                        server=self.opts.server,
                        logname=self.opts.logname,
                        compressLog=self.opts.compress,
                        silent=self.opts.progress or self.opts.silent,
                        lam=lam,
                        logTail=self.opts.logTail,
                        echoCommandLine=self.opts.echoCommandPrefix,
                        noLog=self.opts.noLog)

        print_("Setting system-directory for potentialFoam")
        trig=PotentialTrigger(sol,
                              self.opts.noCorr,
                              self.opts.tolerance,
                              self.opts.relTol,
                              pRefCell=self.opts.pRefCell,
                              pRefValue=self.opts.pRefValue,
                              removeLibs=self.opts.removeLibs,
                              removeFunctions=self.opts.removeFunctions)
        run.addEndTrigger(trig.resetIt)

        self.addToCaseLog(cName,"Starting")

        run.start()

        self.setData(run.data)

        self.addToCaseLog(cName,"Ending")
Exemple #8
0
    def execute(self,para,log):
        if Command.parallel!=None:
            print_("     Doing reconstruction")
            argv=["reconstructPar",".",para['case']]
            if self.onlyLatest:
                argv.append("-latestTime")
            run=BasicRunner(argv=argv,silent=True,logname="Reconstruction")
            run.start()
            Command.parallel.stop()
        else:
            print_("     No reconstruction done")
        Command.parallel=None

        return True,None
 def run_SHM(self, work, wind_dict):
     if wind_dict["procnr"] > 1:
         self._r.status("Running SHM parallel")
         decomposeDict = ParsedParameterFile(
         path.join(work.systemDir(), "decomposeParDict"))
         decomposeDict["method"] = "ptscotch"
         decomposeDict.writeFile()
         self.mpirun(procnr=wind_dict['procnrSnappy'], argv=['snappyHexMesh',
             '-overwrite', '-case', work.name],output_file=path.join(work.name, 'SHM.log'))
         print 'running clearCase'
         ClearCase(args=work.name+'  --processors-remove')
     else:
         SHMrun = BasicRunner(argv=["snappyHexMesh",
                             '-overwrite','-case',work.name],
                         server=False,logname="SHM")
         self._r.status("Running SHM uniprocessor")
         SHMrun.start()
Exemple #10
0
 def run_SHM(self, work, wind_dict):
     if wind_dict["procnr"] > 1:
         self._r.status("Running SHM parallel")
         decomposeDict = ParsedParameterFile(
         path.join(work.systemDir(), "decomposeParDict"))
         decomposeDict["method"] = "ptscotch"
         decomposeDict.writeFile()
         self.mpirun(procnr=wind_dict['procnrSnappy'], argv=['snappyHexMesh',
             '-overwrite', '-case', work.name],output_file=path.join(work.name, 'SHM.log'))
         print 'running clearCase'
         ClearCase(args=work.name+'  --processors-remove')
     else:
         SHMrun = BasicRunner(argv=["snappyHexMesh",
                             '-overwrite','-case',work.name],
                         server=False,logname="SHM")
         self._r.status("Running SHM uniprocessor")
         SHMrun.start()
Exemple #11
0
    def run_tool(self, tool_name):
        """Run an OpenFOAM tool on the case.

        It is assumed that the tool accepts the standard "-case" argument.

        Args:
            tool_name (str): name of tool to run (e.g. "icoFoam")

        Raises:
            CaseToolRunFailed: if the tool exits with an error
        """
        logname = 'log.{}'.format(tool_name)
        runner = BasicRunner(
            [tool_name, '-case', self.root_dir_path],
            silent=True, logname=logname
        )
        runner.start()
        if not runner.runOK():
            raise CaseToolRunFailed('Tool "{}" failed'.format(tool_name))
    def SnappyHexMeshrun(self):
        subprocess.call(['rm', '-r', 'constant/polyMesh/*'],
                        cwd=self.case_path)
        subprocess.call(['rm', '-r', '0'], cwd=self.case_path)
        subprocess.call(['cp', '-r', '0_orig', '0'], cwd=self.case_path)
        ###then stl from binary to ascii
        barry = mesh.Mesh.from_file(self.case_path +
                                    'constant/triSurface/ribbon.stl')
        barry.save("ribbon.stl", mode=stl.ASCII)
        subprocess.call(['mv', 'ribbon.stl', self.case_path])
        subprocess.call([
            'surfaceTransformPoints', '-rotate', " ((0 1 0)(0 0 1)) ",
            'ribbon.stl', 'ribbon_modified.stl'
        ],
                        stdout=self.stdout,
                        cwd=self.case_path)

        with open(self.case_path + 'mergedVolume.stl', 'w') as outfile:
            for infile in (self.case_path + 'ribbon_modified.stl',
                           self.case_path +
                           'Hollorfsen_Cervantes_walls_cfmesh.stl'):
                shutil.copyfileobj(open(infile), outfile)

        subprocess.call(['rm', '-r', 'mergedTotal.stl'], cwd=self.case_path)
        subprocess.call(['rm', '-r', 'mergedTotal2.stl'], cwd=self.case_path)
        subprocess.call(['rm', '-r', 'mergedTotal3.stl'], cwd=self.case_path)

        with open(self.case_path + 'mergedTotal.stl', 'w') as outfile:
            for infile in (self.case_path + 'Hollorfsen_Cervantes_inflow.stl',
                           self.case_path + 'RCONE.stl',
                           self.case_path + 'outflow_extension.stl',
                           self.case_path + 'extended_outflow2.stl',
                           self.case_path + 'mergedVolume.stl'):
                shutil.copyfileobj(open(infile), outfile)

        subprocess.call([
            'surfaceTransformPoints', '-scale', " (0.001 0.001 0.001) ",
            'mergedTotal.stl', 'mergedVolume2.stl'
        ],
                        stdout=self.stdout,
                        cwd=self.case_path)

        snappy = BasicRunner(argv=[self.solver2, "-case", self.case_path],
                             silent=False)
        snappy.start()

        decompose = BasicRunner(argv=[self.solver3, "-case", self.case_path],
                                silent=False)
        decompose.start()
Exemple #13
0
    def run(self):
        cName = self.parser.casePath()

        self.checkCase(cName)

        sol = SolutionDirectory(cName, archive=None)

        print_("Clearing out old timesteps ....")

        sol.clearResults()

        self.checkAndCommit(SolutionDirectory(cName, archive=None))

        run = BasicRunner(argv=self.parser.getArgs(),
                          server=self.opts.server,
                          logname="PyFoamMeshUtility")

        self.addLibFunctionTrigger(run, sol)

        self.addToCaseLog(cName, "Starting")

        run.start()

        self.setData(run.data)

        sol.reread(force=True)

        self.addToCaseLog(cName, "Ending")

        if sol.latestDir() != sol.initialDir():
            for f in listdir(path.join(sol.latestDir(), "polyMesh")):
                system("mv -f " + path.join(sol.latestDir(), "polyMesh", f) +
                       " " + sol.polyMeshDir())

            print_("\nClearing out new timesteps ....")

            sol.clearResults()
        else:
            print_("\n\n  No new timestep. Utility propably failed")
Exemple #14
0
    def __init__(self,
                 analyzer,
                 argv=None,
                 silent=False,
                 logname="PyFoamSolve",
                 server=False,
                 lam=None,
                 compressLog=False,
                 restart=False,
                 noLog=False,
                 logTail=None,
                 remark=None,
                 parameters=None,
                 jobId=None,
                 smallestFreq=60.,
                 echoCommandLine=None):
        """ @param analyzer: the analyzer for the output
        argv, silent, logname, server, lam, noLog - see BasicRunner"""
        BasicRunner.__init__(self,
                             argv,
                             silent,
                             logname,
                             server=server,
                             lam=lam,
                             restart=restart,
                             compressLog=compressLog,
                             noLog=noLog,
                             logTail=logTail,
                             remark=remark,
                             parameters=parameters,
                             echoCommandLine=echoCommandLine,
                             jobId=jobId)
        StepAnalyzedCommon.__init__(self,
                                    logname,
                                    analyzer,
                                    smallestFreq=smallestFreq)

        self.writeToStateFile("LogDir", self.logDir)
Exemple #15
0
    def run(self):
        cName=self.parser.casePath()

        self.checkCase(cName)

        sol=SolutionDirectory(cName,archive=None)

        print_("Clearing out old timesteps ....")

        sol.clearResults()

        self.checkAndCommit(SolutionDirectory(cName,archive=None))

        run=BasicRunner(argv=self.parser.getArgs(),
                        server=self.opts.server,
                        logname="PyFoamMeshUtility")

        self.addLibFunctionTrigger(run,sol)

        self.addToCaseLog(cName,"Starting")

        run.start()

        self.setData(run.data)

        sol.reread(force=True)

        self.addToCaseLog(cName,"Ending")

        if sol.latestDir()!=sol.initialDir():
            for f in listdir(path.join(sol.latestDir(),"polyMesh")):
                system("mv -f "+path.join(sol.latestDir(),"polyMesh",f)+" "+sol.polyMeshDir())

            print_("\nClearing out new timesteps ....")

            sol.clearResults()
        else:
            print_("\n\n  No new timestep. Utility propably failed")
Exemple #16
0
    def run(self):
        cName = self.parser.getArgs()[0]
        sol = SolutionDirectory(cName, archive=None)
        self.addLocalConfig(cName)
        initial = sol[0]
        if "U" not in initial or "p" not in initial:
            error("Either 'p' or 'U' missing from the initial directory",
                  initial.baseName())
        if self.opts.writep:
            initial["p.prepotential"] = initial["p"]
        initial["U.prepotential"] = initial["U"]

        lam = self.getParallel(sol)

        if self.opts.writep:
            writep = ["-writep"]
        else:
            writep = []

        argv = ["potentialFoam"]
        if oldApp():
            argv += [".", cName]
        else:
            argv += ["-case", cName]

        self.setLogname(default="Potential", useApplication=False)

        self.checkAndCommit(sol)

        run = BasicRunner(argv=argv + writep,
                          server=self.opts.server,
                          logname=self.opts.logname,
                          compressLog=self.opts.compress,
                          silent=self.opts.progress or self.opts.silent,
                          lam=lam,
                          logTail=self.opts.logTail,
                          echoCommandLine=self.opts.echoCommandPrefix,
                          noLog=self.opts.noLog)

        print_("Setting system-directory for potentialFoam")
        trig = PotentialTrigger(sol,
                                self.opts.noCorr,
                                self.opts.tolerance,
                                self.opts.relTol,
                                pRefCell=self.opts.pRefCell,
                                pRefValue=self.opts.pRefValue,
                                removeLibs=self.opts.removeLibs,
                                removeFunctions=self.opts.removeFunctions)
        run.addEndTrigger(trig.resetIt)

        self.addToCaseLog(cName, "Starting")

        run.start()

        self.setData(run.data)

        self.addToCaseLog(cName, "Ending")
Exemple #17
0
    def execute(self,para,log):
        argv=[self.utility,".",para['case']]+self.options.split()
        print_("     Executing"," ".join(argv),end=" ")
        sys.stdout.flush()
        run=BasicRunner(argv,silent=True,lam=Command.parallel,logname="_".join(argv))
        run.start()
        if run.runOK():
            print_()
        else:
            print_("---> there was a problem")

        return run.runOK(),None
Exemple #18
0
        subprocess.call(activator, shell=True)

        activator = 'funkySetFields -case '+refCase+' -field Ct -expression "1e-3" -condition "(pow(pos().x-'+str(pancakesCenters[pancackes,0])+',2) + pow(pos().y-'+str(pancakesCenters[pancackes,1])+',2) < pow('+str(radius)+',2) )&&(pos().z>0) && (pos().z<=(1e-6+0))" -time "0"'

        subprocess.call(activator, shell=True)
        dire=SolutionDirectory(refCase)
        sol=SolutionFile(dire.initialDir(),"Ct")
        sol.replaceBoundary("inlet","0")
        a= 'sh fixInlet.sh'
        subprocess.call(a, shell=True)

#        tobinary()
                # parallel decomposition
        if nproc > 1:
            args = ["--method=scotch", "--clear", refCase, nproc]
            Decomposer(args=args)

        run = BasicRunner(
            argv=[
                solver,
                "-case",
                caseName],
            silent=True,
            noLog=False)
        run.start()
        runCmd = 'pyFoamRunner.py advDiffMicellesNoFlow -case '+caseName+' > /dev/null 2>&1 &'
        # subprocess.call(runCmd, shell=True)
        post = 'mpirun -np ' + str(nproc) + ' foamToEnsight -case '+refCase+' -parallel -name pancanke_noflow_radius='+str(radius)+'_loc='+str(pancackes)
        subprocess.call(post, shell=True)
        a = "rm 0/t* 0/*.backup"
        subprocess.call(a, shell=True)
 def SnappyHexMeshrun(self):
     subprocess.call(['rm', '-r', self.case_path + 'constant/polyMesh'])
     subprocess.call([
         'cp', '-r',
         self.case_path + 'pitzDaily_backup/constant/polyMesh_backup',
         self.case_path + '/constant/polyMesh'
     ])
     subprocess.call(['rm', '-r', self.case_path + '0'])
     subprocess.call([
         'cp', '-r', self.case_path + 'pitzDaily_backup/0_orig',
         self.case_path + '/0'
     ])
     surface = BasicRunner(argv=[self.solver5, "-case", self.case_path],
                           silent=True)
     surface.start()
     snappy = BasicRunner(
         argv=[self.solver2, "-overwrite", "-case", self.case_path],
         silent=True)
     snappy.start()
     check = BasicRunner(
         argv=[self.checkingmesh, "-latestTime", "-case", self.case_path],
         silent=True)
     check.start()
     merge = BasicRunner(
         argv=[self.solver3, "-overwrite", "-case", self.case_path],
         silent=True)  # merge STL with lowerboundary
     merge.start()
Exemple #20
0
    def stopHandle(self):
        BasicRunner.stopHandle(self)
        StepAnalyzedCommon.stopHandle(self)

        self.tearDown()
Exemple #21
0
def reWriteBlockMeshDict(target, caseType):
    # read dictionaries of target case - with 3 different z0 (assuming standard case, 0.1, 0.03 and 0.005
    z0Str = target[target.find("z0") + 3:]
    dict005Name = target.replace(z0Str, "0.005")
    dict03Name = target.replace(z0Str, "0.03")
    dict1Name = target.replace(z0Str, "0.1")

    # - just for memory sake ... dict005 = ParsedBlockMeshDict(target.replace(z0Str,"0.005")+"/constant/polyMesh/blockMeshDict")
    # - just for memory sake... dict03["blocks"][4][1] = dict005["blocks"][4][1]

    # erase all previous mesh files
    # for 0.03 case
    curDir = os.getcwd()
    os.chdir(dict03Name)
    os.chdir('constant/polyMesh')
    os.system("rm -rf *")
    os.chdir(curDir)

    # for 0.1 case
    os.chdir(dict1Name)
    os.chdir('constant/polyMesh')
    os.system("rm -rf *")
    os.chdir(curDir)

    # copy the 0.005 blockMeshDict to the 0.03 and 0.1 cases
    os.system("cp %s %s" % (dict005Name + "/constant/polyMesh/blockMeshDict",
                            dict03Name + "/constant/polyMesh/blockMeshDict"))
    os.system("cp %s %s" % (dict005Name + "/constant/polyMesh/blockMeshDict",
                            dict1Name + "/constant/polyMesh/blockMeshDict"))

    # running blockMesh on 0.03 case
    blockRun = BasicRunner(argv=["blockMesh", '-case', dict03Name],
                           silent=True,
                           server=False,
                           logname="blockMesh")
    blockRun.start()
    if not blockRun.runOK(): print "there was an error with blockMesh"

    # running blockMesh on 0.005 case
    blockRun = BasicRunner(argv=["blockMesh", '-case', dict1Name],
                           silent=True,
                           server=False,
                           logname="blockMesh")
    blockRun.start()
    if not blockRun.runOK(): print "there was an error with blockMesh"

    # mapping fields - From earlier result if exists
    if caseType == "mapFields":
        # copying 0 time files from Crude run - because mapFields won't start with a non similar p and points size
        os.system('cp -r ' + dict03Name + 'Crude/0/* ' + dict03Name + '/0/')
        os.system('cp -r ' + dict1Name + 'Crude/0/* ' + dict1Name + '/0/')

        # finding the most converged run. assuming the "crude" run had the same dirName with "Crude" attached
        # for z0 = 0.03
        mapRun = BasicRunner(argv=[
            'mapFields -consistent -sourceTime latestTime' + ' -case ' +
            dict03Name + ' ' + dict03Name + "Crude"
        ],
                             silent=True,
                             server=False,
                             logname='mapLog')
        mapRun.start()
        # for z0 = 0.1
        mapRun = BasicRunner(argv=[
            'mapFields -consistent -sourceTime latestTime' + ' -case ' +
            dict1Name + ' ' + dict1Name + "Crude"
        ],
                             silent=True,
                             server=False,
                             logname='mapLog')
        mapRun.start()
Exemple #22
0
    def buildCase(self,cName,args):
        """Builds the case
        @param cName: The name of the case directory
        @param args: The arguments (as a dictionary)"""

        args=self.calculateVariables(args)
        
        os.mkdir(cName)
        
        for d in self.parameterTree().getElementsByTagName("directory"):
            dName=path.join(cName,d.getAttribute("name"))
            if not path.isdir(dName):
                os.mkdir(dName)
            sName=path.join(self.templatePath(),d.getAttribute("name"))
            for f in d.getElementsByTagName("file"):
                dFile=path.join(dName,f.getAttribute("name"))
                shutil.copy(path.join(sName,f.getAttribute("name")),dFile)
                if len(f.getElementsByTagName("parameter"))>0:
                    pf=ParsedParameterFile(dFile)
                    for p in f.getElementsByTagName("parameter"):
                        pName=p.getAttribute("name")
                        pValue=self.expandVars(p.getAttribute("value"),args)
                        exec "pf"+pName+"="+pValue
                    pf.writeFile()

        prep=self.getSingleElement(self.doc,"meshpreparation")
        util=prep.getElementsByTagName("utility")
        copy=self.getSingleElement(prep,"copy",optional=True)
        
        if len(util)>0 and copy:
            error("Copy and utilitiy mesh preparation specified")
        elif len(util)>0:
            for u in util:
                app=u.getAttribute("command")
                arg=self.expandVars(u.getAttribute("arguments"),args)
                argv=[app,"-case",cName]+arg.split()
                if oldApp():
                    argv[1]="."
                run=BasicRunner(argv=argv,silent=True,logname="CaseBuilder.prepareMesh."+app)
                run.start()
                if not run.runOK():
                    error(app,"failed. Check the logs")
        elif copy:
            source=self.expandVars(copy.getAttribute("template"),args)
            time=self.expandVars(copy.getAttribute("time"),args)
            if time=="":
                time="constant"
            shutil.copytree(path.join(source,time,"polyMesh"),
                             path.join(cName,"constant","polyMesh"))
        else:
            error("Neither copy nor utilitiy mesh preparation specified")
            
        dName=path.join(cName,self.initialDir())
        if not path.isdir(dName):
            os.mkdir(dName)
        sName=path.join(self.templatePath(),self.initialDir())
        for f in self.fieldTree().getElementsByTagName("field"):
            dFile=path.join(dName,f.getAttribute("name"))
            shutil.copy(path.join(sName,f.getAttribute("name")),dFile)
            default=self.makeBC(self.getSingleElement(f,"defaultbc"),args)
            
            CreateBoundaryPatches(args=["--fix-types",
                                        "--overwrite",
                                        "--clear",
                                        "--default="+default,
                                        dFile]) 
            bcDict={}
            bounds=self.boundaries()
            for b in f.getElementsByTagName("bc"):
                nm=b.getAttribute("name")
                if nm not in bounds:
                    error("Boundary",nm,"not in list",bounds,"for field",f.getAttribute("name"))
                bcDict[nm]=b
                
            for name,pattern in self.boundaryPatterns():
                if name in bcDict:
                    default=self.makeBC(bcDict[name],args)
                    CreateBoundaryPatches(args=["--filter="+pattern,
                                                "--overwrite",
                                                "--default="+default,
                                                dFile]) 

            ic=self.expandVars(self.getSingleElement(f,"ic").getAttribute("value"),args)
            pf=ParsedParameterFile(dFile)
            pf["internalField"]="uniform "+ic
            pf.writeFile()
 def SnappyHexMeshrun(self):
     subprocess.call(['rm', '-r', self.case_path+'constant/polyMesh'])
     subprocess.call(['cp', '-r', self.case_path+'heat_exchange/constant/polyMesh_backup', self.case_path+'/constant/polyMesh'])
     subprocess.call(['rm', '-r', self.case_path+'0'])
     subprocess.call(['cp', '-r', self.case_path+'heat_exchange/0_orig', self.case_path+'0'])
     surface = BasicRunner(argv=[self.solver5,"-case", self.case_path], silent=False)
     surface.start()
     snappy = BasicRunner(argv=[self.solver2,"-overwrite","-case",self.case_path], silent=False)
     snappy.start()
     extrude = BasicRunner(argv=[self.solver6,"-case",self.case_path], silent=False)
     extrude.start()
     check = BasicRunner(argv=[self.checkingmesh, "-latestTime","-case", self.case_path], silent=False)
     check.start()
Exemple #24
0
def myBasicRunner(command, add=""):
    run = BasicRunner(argv=command + ["-case", work_dir], silent=True, server=False, 
                      logname=command[0] + ( "." + add if add else add ))
    print "Running " + command[0]
    run.start()
Exemple #25
0
pi = 3.1415926
ratio_max = 0
theta = 0
#Obtain Value of Theta from dummy theta file
with open("theta", "r") as f:
    for line in f:
        theta = float(line.split("e")[0]) * 10**(float(line.split("e")[1]))
#Calculate new velocity
Ux = U * np.cos(theta * pi / 180.)
Uy = U * np.sin(theta * pi / 180.)
#Replace the existing U boundary conditions
new_vel = "uniform (" + str(Ux) + " " + str(Uy) + " 0)"
vel["internalField"] = new_vel
vel.writeFile()
#Run the solver
BasicRunner(argv=["simpleFoam", "-case", "."]).start()
#Store the Cl/Cd ratio in a dummy file
cl = 0
cd = 0
count = 0
with open(pproc, "r") as p:
    for i, line in enumerate(p):
        if i > 9:
            cl_i = abs(float(line.split()[3]))
            cd_i = abs(float(line.split()[2]))
            cl = cl_i
            cd = cd_i
            #count = count + 1
cl = float(cl)
cd = float(cd)
ratio = cl / cd
Exemple #26
0
# from os import path
from PyFoam.Execution.BasicRunner import BasicRunner

from setupCases import pbe_grids

if __name__ == "__main__":

    for c in ["pure_coal", "pure_br"]:
        for N in pbe_grids:
            block_mesh = BasicRunner(
                argv=["blockMesh", "-case", "{0}{1}".format(c, N)],
                silent=True)
            block_mesh.start()
            run = BasicRunner(
                argv=["twoPhaseEulerFoam", "-case", "{0}{1}".format(c, N)],
                silent=True)
            run.start()
Exemple #27
0
valueList.append({'velocity':5,'alpha':10})
valueList.append({'velocity':7.5,'alpha':10})
print valueList

for k in range(6,len(valueList)):
    vel = valueList[k]['velocity']
    alpha = valueList[k]['alpha']
    caseDir.clear(functionObjectData=True)
    caseDir.clearOther()
    caseDir.clearPattern("postProcessing")
    caseDir.clearResults(functionObjectData=True)
    velocity = [0,math.sin(alpha*math.pi/180)*vel,-math.cos(alpha*math.pi/180)*vel]
    print "Simulation {:d} from {:d}: velocity = {:f} alpha = {:f}".format(k,len(valueList),vel,alpha)
    parameters['flowVelocity'] = "({:f} {:f} {:f})".format(velocity[0],velocity[1],velocity[2])
    parameters['magUInf'] = "{:f}".format(vel)
    parameters.writeFile()
    decompose = BasicRunner(argv=["decomposePar"],silent=True)
    print " Decompose Dictionary"
    start = time.clock()
    decompose.start()
    print " Run SimpleFoam"
    run = AnalyzedRunner(StandardLogAnalyzer(),argv=["mpirun -np 4","simpleFoam","-parallel"],silent=True)
    run.start()
    run.picklePlots()
    print " Reconstruct Par"
    reconstruct = BasicRunner(argv=["reconstructPar"],silent=True)
    reconstruct.start()
    end = time.clock()
    print " Save Data"
    print " Run finalized. Ellapsed time: {:f}s".format(end-start)
    caseDir.lastToArchive("vel={:f}alpha={:f}".format(vel,alpha))
y3 = y0 + (l/2*cos(phi) - d/2*sin(phi))
x4 = x0 + (l/2*sin(phi) - d/2*cos(phi))
y4 = y0 + (l/2*cos(phi) + d/2*sin(phi))
n = floor(d/cell)
m = floor(l/cell)
q = floor((Href+450)/cell) # -450 is the minimum of the blockMeshDict.template - since that is slightly lower then the lowest point on the planet

bmName = path.join(work.constantDir(),"polyMesh/blockMeshDict")
template = TemplateFile(bmName+".template")
template.writeToFile(bmName,{'X0':x1,'X1':x2,'X2':x3,'X3':x4,'Y0':y1,'Y1':y2,'Y2':y3,'Y3':y4,'Z0':Href,'n':int(n),'m':int(m),'q':int(q)})


#--------------------------------------------------------------------------------------
# running blockMesh
#--------------------------------------------------------------------------------------
blockRun = BasicRunner(argv=["blockMesh",'-case',work.name],silent=True,server=False,logname="blockMesh")
print "Running blockMesh"
blockRun.start()
if not blockRun.runOK(): print("there was an error with blockMesh")

#--------------------------------------------------------------------------------------
# changing ABLconditions 
#--------------------------------------------------------------------------------------

# 1: changing ABLConditions
bmName = path.join(work.initialDir(),"include/ABLConditions")
template = TemplateFile(bmName+".template")
template.writeToFile(bmName,{'us':us,'Uref':Uref,'Href':Href,'z0':z0,'xDirection':sin(phi),'yDirection':cos(phi)})
# 2: changing initialConditions
#bmName = path.join(work.initialDir(),"include/initialConditions")
#template = TemplateFile(bmName+".template")
Exemple #29
0
    def prepare(self, sol, cName=None, overrideParameters=None):
        if cName == None:
            cName = sol.name

        if self.opts.onlyVariables:
            self.opts.verbose = True

        vals = {}
        vals["casePath"] = '"' + path.abspath(cName) + '"'
        vals["caseName"] = '"' + path.basename(path.abspath(cName)) + '"'
        vals["foamVersion"] = foamVersion()
        vals["foamFork"] = foamFork()

        if self.opts.verbose:
            print_("Looking for template values", cName)
        for f in self.opts.valuesDicts:
            if self.opts.verbose:
                print_("Reading values from", f)
            vals.update(
                ParsedParameterFile(f, noHeader=True,
                                    doMacroExpansion=True).getValueDict())
        for v in self.opts.values:
            if self.opts.verbose:
                print_("Updating values", v)
            vals.update(eval(v))

        if overrideParameters:
            vals.update(overrideParameters)

        if self.opts.verbose and len(vals) > 0:
            print_("\nUsed values\n")
            nameLen = max(len("Name"), max(*[len(k) for k in vals.keys()]))
            format = "%%%ds - %%s" % nameLen
            print_(format % ("Name", "Value"))
            print_("-" * 40)
            for k, v in sorted(iteritems(vals)):
                print_(format % (k, v))
            print_("")
        elif self.opts.verbose:
            print_("\nNo values specified\n")

        if self.opts.onlyVariables:
            return

        if self.opts.doClear:
            if self.opts.verbose:
                print_("Clearing", cName)
            sol.clear(processor=True,
                      pyfoam=True,
                      vtk=True,
                      removeAnalyzed=True,
                      keepParallel=False,
                      clearHistory=False,
                      clearParameters=True,
                      additional=["postProcessing"])

        if self.opts.writeParameters:
            fName = path.join(cName, self.parameterOutFile)
            if self.opts.verbose:
                print_("Writing parameters to", fName)
            with WriteParameterFile(fName, noHeader=True) as w:
                w.content.update(vals, toString=True)
                w["foamVersion"] = vals["foamVersion"]
                w.writeFile()

        self.addToCaseLog(cName)

        for over in self.opts.overloadDirs:
            if self.opts.verbose:
                print_("Overloading files from", over)
                self.overloadDir(sol.name, over)

        zeroOrig = path.join(sol.name, "0.org")

        hasOrig = path.exists(zeroOrig)
        if not hasOrig:
            if self.opts.verbose:
                print_("Not going to clean '0'")
            self.opts.cleanDirectories.remove("0")

        if self.opts.doCopy:
            if hasOrig:
                if self.opts.verbose:
                    print_("Found 0.org. Clearing 0")
                zeroDir = path.join(sol.name, "0")
                if path.exists(zeroDir):
                    rmtree(zeroDir)
                elif self.opts.verbose:
                    print_("No 0-directory")

            if self.opts.verbose:
                print_("")

        if self.opts.doTemplates:
            self.searchAndReplaceTemplates(sol.name, vals,
                                           self.opts.templateExt)

            if self.opts.verbose:
                print_("")

        if self.opts.doMeshCreate:
            if self.opts.meshCreateScript:
                scriptName = path.join(sol.name, self.opts.meshCreateScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultMeshCreate)):
                scriptName = path.join(sol.name, self.defaultMeshCreate)
            else:
                scriptName = None

            if scriptName:
                if self.opts.verbose:
                    print_("Executing", scriptName, "for mesh creation")
                if self.opts.verbose:
                    echo = "Mesh: "
                else:
                    echo = None
                result = "".join(
                    execute([scriptName], workdir=sol.name, echo=echo))
                open(scriptName + ".log", "w").write(result)
            else:
                if self.opts.verbose:
                    print_(
                        "No script for mesh creation found. Looking for 'blockMeshDict'"
                    )
                if sol.blockMesh() != "":
                    if self.opts.verbose:
                        print_(sol.blockMesh(), "found. Executing 'blockMesh'")
                    bm = BasicRunner(argv=["blockMesh", "-case", sol.name])
                    bm.start()
                    if not bm.runOK():
                        self.error("Problem with blockMesh")
            if self.opts.verbose:
                print_("")

        if self.opts.doCopy:
            self.copyOriginals(sol.name)

            if self.opts.verbose:
                print_("")

        if self.opts.doPostTemplates:
            self.searchAndReplaceTemplates(sol.name, vals,
                                           self.opts.postTemplateExt)

            if self.opts.verbose:
                print_("")

        if self.opts.doCaseSetup:
            if self.opts.caseSetupScript:
                scriptName = path.join(sol.name, self.opts.caseSetupScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultCaseSetup)):
                scriptName = path.join(sol.name, self.defaultCaseSetup)
            else:
                scriptName = None

            if scriptName:
                if self.opts.verbose:
                    print_("Executing", scriptName, "for case setup")
                if self.opts.verbose:
                    echo = "Case:"
                else:
                    echo = None
                result = "".join(
                    execute([scriptName], workdir=sol.name, echo=echo))
                open(scriptName + ".log", "w").write(result)
            else:
                if self.opts.verbose:
                    print_("No script for case-setup found. Nothing done")
            if self.opts.verbose:
                print_("")

        if self.opts.doTemplateClean:
            if self.opts.verbose:
                print_("Clearing templates")
            for d in self.opts.cleanDirectories:
                for e in [self.opts.templateExt, self.opts.postTemplateExt]:
                    self.cleanExtension(path.join(sol.name, d), e)
            if self.opts.verbose:
                print_("")

        if self.opts.verbose:
            print_("Case setup finished")
Exemple #30
0
    def buildCase(self, cName, args):
        """Builds the case
        @param cName: The name of the case directory
        @param args: The arguments (as a dictionary)"""

        args = self.calculateVariables(args)

        os.mkdir(cName)

        for d in self.parameterTree().getElementsByTagName("directory"):
            dName = path.join(cName, d.getAttribute("name"))
            if not path.isdir(dName):
                os.mkdir(dName)
            sName = path.join(self.templatePath(), d.getAttribute("name"))
            for f in d.getElementsByTagName("file"):
                dFile = path.join(dName, f.getAttribute("name"))
                shutil.copy(path.join(sName, f.getAttribute("name")), dFile)
                if len(f.getElementsByTagName("parameter")) > 0:
                    pf = ParsedParameterFile(dFile)
                    for p in f.getElementsByTagName("parameter"):
                        pName = p.getAttribute("name")
                        pValue = self.expandVars(p.getAttribute("value"), args)
                        exec_("pf" + pName + "=" + pValue)
                    pf.writeFile()

        prep = self.getSingleElement(self.doc, "meshpreparation")
        util = prep.getElementsByTagName("utility")
        copy = self.getSingleElement(prep, "copy", optional=True)

        if len(util) > 0 and copy:
            error("Copy and utilitiy mesh preparation specified")
        elif len(util) > 0:
            for u in util:
                app = u.getAttribute("command")
                arg = self.expandVars(u.getAttribute("arguments"), args)
                argv = [app, "-case", cName] + arg.split()
                if oldApp():
                    argv[1] = "."
                run = BasicRunner(argv=argv,
                                  silent=True,
                                  logname="CaseBuilder.prepareMesh." + app)
                run.start()
                if not run.runOK():
                    error(app, "failed. Check the logs")
        elif copy:
            source = self.expandVars(copy.getAttribute("template"), args)
            time = self.expandVars(copy.getAttribute("time"), args)
            if time == "":
                time = "constant"
            shutil.copytree(path.join(source, time, "polyMesh"),
                            path.join(cName, "constant", "polyMesh"))
        else:
            error("Neither copy nor utilitiy mesh preparation specified")

        dName = path.join(cName, self.initialDir())
        if not path.isdir(dName):
            os.mkdir(dName)
        sName = path.join(self.templatePath(), self.initialDir())
        for f in self.fieldTree().getElementsByTagName("field"):
            dFile = path.join(dName, f.getAttribute("name"))
            shutil.copy(path.join(sName, f.getAttribute("name")), dFile)
            default = self.makeBC(self.getSingleElement(f, "defaultbc"), args)

            CreateBoundaryPatches(args=[
                "--fix-types", "--overwrite", "--clear", "--default=" +
                default, dFile
            ])
            bcDict = {}
            bounds = self.boundaries()
            for b in f.getElementsByTagName("bc"):
                nm = b.getAttribute("name")
                if nm not in bounds:
                    error("Boundary", nm, "not in list", bounds, "for field",
                          f.getAttribute("name"))
                bcDict[nm] = b

            for name, pattern in self.boundaryPatterns():
                if name in bcDict:
                    default = self.makeBC(bcDict[name], args)
                    CreateBoundaryPatches(args=[
                        "--filter=" + pattern, "--overwrite", "--default=" +
                        default, dFile
                    ])

            ic = self.expandVars(
                self.getSingleElement(f, "ic").getAttribute("value"), args)
            pf = ParsedParameterFile(dFile)
            pf["internalField"] = "uniform " + ic
            pf.writeFile()
Exemple #31
0
        controlDict["functions"]["forcesCoeffs"]["liftDir"] = Vector(
            -sin(radians(angle)), cos(radians(angle)), 0)
        controlDict["functions"]["forcesCoeffs"]["dragDir"] = Vector(
            cos(radians(angle)), sin(radians(angle)), 0)
        controlDict["functions"]["forcesCoeffs"][
            "magUInf"] = mach * speedOfSound
        controlDict.writeFile()

        #implement parallelization
        print('Decomposing...')
        Decomposer(args=['--progress', clone_name, num_procs])
        CaseReport(args=['--decomposition', clone_name])
        machine = LAMMachine(nr=num_procs)

        #run simpleFoam
        foamRun = BasicRunner(argv=[solver, "-case", clone_name],
                              logname="simpleFoam")
        print("Running simpleFoam")
        foamRun.start()
        if not foamRun.runOK():
            error("There was a problem with simpleFoam")

        #get headers and last line of postprocessing file
        with open(
                path.join(clone_name, 'postProcessing', 'forcesCoeffs', '0',
                          'coefficient.dat'), "rb") as table:
            last = table.readlines()[-1].decode()
            print("last line of coefficients" + last)
            splitLast = last.split()
            print(splitLast)
            Cd = float(splitLast[2])
            Cl = float(splitLast[3])
Exemple #32
0
        'X3': x4,
        'Y0': y1,
        'Y1': y2,
        'Y2': y3,
        'Y3': y4,
        'Z0': Href,
        'n': int(n),
        'm': int(m),
        'q': int(q)
    })

#--------------------------------------------------------------------------------------
# running blockMesh
#--------------------------------------------------------------------------------------
blockRun = BasicRunner(argv=["blockMesh", '-case', work.name],
                       silent=True,
                       server=False,
                       logname="blockMesh")
print "Running blockMesh"
blockRun.start()
if not blockRun.runOK(): print("there was an error with blockMesh")

#--------------------------------------------------------------------------------------
# changing ABLconditions
#--------------------------------------------------------------------------------------

# 1: changing ABLConditions
bmName = path.join(work.initialDir(), "include/ABLConditions")
template = TemplateFile(bmName + ".template")
template.writeToFile(
    bmName, {
        'us': us,
def reWriteBlockMeshDict(target, caseType):
    # read dictionaries of target case - with 3 different z0 (assuming standard case, 0.1, 0.03 and 0.005
    z0Str = target[target.find("z0")+3:]
    dict005Name = target.replace(z0Str,"0.005")
    dict03Name = target.replace(z0Str,"0.03")
    dict1Name = target.replace(z0Str,"0.1")

    # - just for memory sake ... dict005 = ParsedBlockMeshDict(target.replace(z0Str,"0.005")+"/constant/polyMesh/blockMeshDict")
    # - just for memory sake... dict03["blocks"][4][1] = dict005["blocks"][4][1]
   
    # erase all previous mesh files
    # for 0.03 case
    curDir = os.getcwd()
    os.chdir(dict03Name)
    os.chdir('constant/polyMesh')
    os.system("rm -rf *")
    os.chdir(curDir)
    
    # for 0.1 case
    os.chdir(dict1Name)
    os.chdir('constant/polyMesh')
    os.system("rm -rf *")
    os.chdir(curDir)

    # copy the 0.005 blockMeshDict to the 0.03 and 0.1 cases
    os.system("cp %s %s" % (dict005Name+"/constant/polyMesh/blockMeshDict", dict03Name+"/constant/polyMesh/blockMeshDict") )
    os.system("cp %s %s" % (dict005Name+"/constant/polyMesh/blockMeshDict", dict1Name+"/constant/polyMesh/blockMeshDict") )
    
    # running blockMesh on 0.03 case
    blockRun = BasicRunner(argv=["blockMesh",'-case',dict03Name],silent=True,server=False,logname="blockMesh")
    blockRun.start()
    if not blockRun.runOK(): print "there was an error with blockMesh"
    
    # running blockMesh on 0.005 case
    blockRun = BasicRunner(argv=["blockMesh",'-case',dict1Name],silent=True,server=False,logname="blockMesh")
    blockRun.start()
    if not blockRun.runOK(): print "there was an error with blockMesh"

   	# mapping fields - From earlier result if exists
    if caseType == "mapFields":
        # copying 0 time files from Crude run - because mapFields won't start with a non similar p and points size 
        os.system('cp -r ' + dict03Name + 'Crude/0/* ' + dict03Name + '/0/')
        os.system('cp -r ' + dict1Name + 'Crude/0/* ' + dict1Name + '/0/')
        
        # finding the most converged run. assuming the "crude" run had the same dirName with "Crude" attached
        # for z0 = 0.03
        mapRun = BasicRunner(argv=['mapFields -consistent -sourceTime latestTime' +
			 ' -case ' + dict03Name + ' ' + dict03Name + "Crude"],silent=True,server=False,logname='mapLog')
        mapRun.start()
	    # for z0 = 0.1
        mapRun = BasicRunner(argv=['mapFields -consistent -sourceTime latestTime' +
			 ' -case ' + dict1Name + ' ' + dict1Name + "Crude"],silent=True,server=False,logname='mapLog')
        mapRun.start()	
    def prepare(self,sol,
                cName=None,
                overrideParameters=None,
                numberOfProcessors=None):
        """Do the actual preparing
        @param numberOfProcessors: If set this overrides the value set in the
        command line"""

        if cName==None:
            cName=sol.name

        if self.opts.onlyVariables:
            self.opts.verbose=True

        vals={}
        vals,self.metaData=self.getDefaultValues(cName)
        vals.update(self.addDictValues("System",
                                       "Automatically defined values",
                                       {
                                           "casePath" : '"'+path.abspath(cName)+'"',
                                           "caseName" : '"'+path.basename(path.abspath(cName))+'"',
                                           "foamVersion" : foamVersion(),
                                           "foamFork" : foamFork(),
                                           "numberOfProcessors" : numberOfProcessors if numberOfProcessors!=None else self.opts.numberOfProcessors
                                       }))

        if len(self.opts.extensionAddition)>0:
            vals.update(self.addDictValues("ExtensionAdditions",
                                           "Additional extensions to be processed",
                                           dict((e,True) for e in self.opts.extensionAddition)))

        valsWithDefaults=set(vals.keys())

        self.info("Looking for template values",cName)
        for f in self.opts.valuesDicts:
            self.info("Reading values from",f)
            vals.update(ParsedParameterFile(f,
                                            noHeader=True,
                                            doMacroExpansion=True).getValueDict())

        setValues={}
        for v in self.opts.values:
            self.info("Updating values",v)
            vals.update(eval(v))
            setValues.update(eval(v))

        if overrideParameters:
            vals.update(overrideParameters)

        unknownValues=set(vals.keys())-valsWithDefaults
        if len(unknownValues)>0:
            self.warning("Values for which no default was specified: "+
                         ", ".join(unknownValues))

        if self.opts.verbose and len(vals)>0:
            print_("\nUsed values\n")
            nameLen=max(len("Name"),
                        max(*[len(k) for k in vals.keys()]))
            format="%%%ds - %%s" % nameLen
            print_(format % ("Name","Value"))
            print_("-"*40)
            for k,v in sorted(iteritems(vals)):
                print_(format % (k,v))
            print_("")
        else:
            self.info("\nNo values specified\n")

        self.checkCorrectOptions(vals)

        derivedScript=path.join(cName,self.opts.derivedParametersScript)
        if path.exists(derivedScript):
            self.info("Deriving variables in script",derivedScript)
            scriptText=open(derivedScript).read()
            glob={}
            oldVals=vals.copy()
            exec_(scriptText,glob,vals)
            added=[]
            changed=[]
            for k,v in iteritems(vals):
                if k not in oldVals:
                    added.append(k)
                elif vals[k]!=oldVals[k]:
                    changed.append(k)
            if len(changed)>0 and (not self.opts.allowDerivedChanges and not configuration().getboolean("PrepareCase","AllowDerivedChanges")):
                self.error(self.opts.derivedParametersScript,
                           "changed values of"," ".join(changed),
                           "\nTo allow this set --allow-derived-changes or the configuration item 'AllowDerivedChanges'")
            if len(added)>0:
                self.info("Added values:"," ".join(added))
            if len(changed)>0:
                self.info("Changed values:"," ".join(changed))
            if len(added)==0 and len(changed)==0:
                self.info("Nothing added or changed")
        else:
            self.info("No script",derivedScript,"for derived values")

        if self.opts.onlyVariables:
            return

        if self.opts.doClear:
            self.info("Clearing",cName)
            sol.clear(processor=True,
                      pyfoam=True,
                      vtk=True,
                      removeAnalyzed=True,
                      keepParallel=False,
                      clearHistory=False,
                      clearParameters=True,
                      additional=["postProcessing"])

        if self.opts.writeParameters:
            fName=path.join(cName,self.parameterOutFile)
            self.info("Writing parameters to",fName)
            with WriteParameterFile(fName,noHeader=True) as w:
                w.content.update(vals,toString=True)
                w["foamVersion"]=vals["foamVersion"]
                w.writeFile()

        if self.opts.writeReport:
            fName=path.join(cName,self.parameterOutFile+".rst")
            self.info("Writing report to",fName)
            with open(fName,"w") as w:
                helper=RestructuredTextHelper(defaultHeading=1)
                w.write(".. title:: "+self.__strip(vals["caseName"])+"\n")
                w.write(".. sectnum::\n")
                w.write(".. header:: "+self.__strip(vals["caseName"])+"\n")
                w.write(".. header:: "+time.asctime()+"\n")
                w.write(".. footer:: ###Page### / ###Total###\n\n")

                w.write("Parameters set in case directory "+
                        helper.literal(self.__strip(vals["casePath"]))+" at "+
                        helper.emphasis(time.asctime())+"\n\n")
                w.write(".. contents::\n\n")
                if len(self.opts.valuesDicts):
                    w.write(helper.heading("Parameter files"))
                    w.write("Parameters read from files\n\n")
                    w.write(helper.enumerateList([helper.literal(f) for f in self.opts.valuesDicts]))
                    w.write("\n")
                if len(setValues)>0:
                    w.write(helper.heading("Overwritten parameters"))
                    w.write("These parameters were set from the command line\n\n")
                    w.write(helper.definitionList(setValues))
                    w.write("\n")
                w.write(helper.heading("Parameters with defaults"))
                w.write(self.makeReport(vals))
                if len(unknownValues)>0:
                    w.write(helper.heading("Unspecified parameters"))
                    w.write("If these parameters are actually used then specify them in "+
                            helper.literal(self.defaultParameterFile)+"\n\n")
                    tab=helper.table(True)
                    for u in unknownValues:
                        tab.addRow(u)
                        tab.addItem("Value",vals[u])
                    w.write(str(tab))

        self.addToCaseLog(cName)

        for over in self.opts.overloadDirs:
            self.info("Overloading files from",over)
            self.overloadDir(sol.name,over)

        zeroOrig=path.join(sol.name,"0.org")

        hasOrig=path.exists(zeroOrig)
        cleanZero=True

        if not hasOrig:
            self.info("Not going to clean '0'")
            self.opts.cleanDirectories.remove("0")
            cleanZero=False

        if self.opts.doCopy:
            if hasOrig:
                self.info("Found 0.org. Clearing 0")
                zeroDir=path.join(sol.name,"0")
                if path.exists(zeroDir):
                    rmtree(zeroDir)
                else:
                    self.info("No 0-directory")

            self.info("")
        else:
            cleanZero=False

        if self.opts.doTemplates:
            self.searchAndReplaceTemplates(sol.name,
                                           vals,
                                           self.opts.templateExt)

            self.info("")

        backupZeroDir=None

        if self.opts.doMeshCreate:
            if self.opts.meshCreateScript:
                scriptName=path.join(sol.name,self.opts.meshCreateScript)
                if not path.exists(scriptName):
                    self.error("Script",scriptName,"does not exist")
            elif path.exists(path.join(sol.name,self.defaultMeshCreate)):
                scriptName=path.join(sol.name,self.defaultMeshCreate)
            else:
                scriptName=None

            if scriptName:
                self.info("Executing",scriptName,"for mesh creation")
                if self.opts.verbose:
                    echo="Mesh: "
                else:
                    echo=None
                result="".join(execute([scriptName],workdir=sol.name,echo=echo))
                open(scriptName+".log","w").write(result)
            else:
                self.info("No script for mesh creation found. Looking for 'blockMeshDict'")
                if sol.blockMesh()!="":
                    self.info(sol.blockMesh(),"found. Executing 'blockMesh'")
                    bm=BasicRunner(argv=["blockMesh","-case",sol.name])
                    bm.start()
                    if not bm.runOK():
                        self.error("Problem with blockMesh")
                for r in sol.regions():
                    self.info("Checking region",r)
                    s=SolutionDirectory(sol.name,region=r,
                                        archive=None,paraviewLink=False)
                    if s.blockMesh()!="":
                        self.info(s.blockMesh(),"found. Executing 'blockMesh'")
                        bm=BasicRunner(argv=["blockMesh","-case",sol.name,
                                             "-region",r])
                        bm.start()
                        if not bm.runOK():
                            self.error("Problem with blockMesh")

            self.info("")

            if cleanZero and path.exists(zeroDir):
                self.warning("Mesh creation recreated 0-directory")
                if self.opts.keepZeroDirectoryFromMesh:
                    backupZeroDir=zeroDir+".bakByPyFoam"
                    self.info("Backing up",zeroDir,"to",backupZeroDir)
                    move(zeroDir,backupZeroDir)
                else:
                    self.info("Data in",zeroDir,"will be removed")

        if self.opts.doCopy:
            self.copyOriginals(sol.name)

            self.info("")

            if backupZeroDir:
                self.info("Copying backups from",backupZeroDir,"to",zeroDir)
                self.overloadDir(zeroDir,backupZeroDir)
                self.info("Removing backup",backupZeroDir)
                rmtree(backupZeroDir)

        if self.opts.doPostTemplates:
            self.searchAndReplaceTemplates(sol.name,
                                           vals,
                                           self.opts.postTemplateExt)

            self.info("")

        if self.opts.doCaseSetup:
            if self.opts.caseSetupScript:
                scriptName=path.join(sol.name,self.opts.caseSetupScript)
                if not path.exists(scriptName):
                    self.error("Script",scriptName,"does not exist")
            elif path.exists(path.join(sol.name,self.defaultCaseSetup)):
                scriptName=path.join(sol.name,self.defaultCaseSetup)
            else:
                scriptName=None

            if scriptName:
                self.info("Executing",scriptName,"for case setup")
                if self.opts.verbose:
                    echo="Case:"
                else:
                    echo=None
                result="".join(execute([scriptName],workdir=sol.name,echo=echo))
                open(scriptName+".log","w").write(result)
            else:
                self.info("No script for case-setup found. Nothing done")
            self.info("")

        if self.opts.doFinalTemplates:
            self.searchAndReplaceTemplates(sol.name,
                                           vals,
                                           self.opts.finalTemplateExt)

        if self.opts.doTemplateClean:
            self.info("Clearing templates")
            for d in self.opts.cleanDirectories:
                for e in [self.opts.templateExt,
                          self.opts.postTemplateExt,
                          self.opts.finalTemplateExt]:
                    self.cleanExtension(path.join(sol.name,d),e)
            self.info("")

        self.info("Case setup finished")
Exemple #35
0
base_case = "base"

templateCase = SolutionDirectory(base_case, archive=None, paraviewLink=False)

omegas = nm.linspace(0, 3, 13)
nus = nm.ones(omegas.shape) * 1e-6

for i, eps in enumerate(omegas):
    case = templateCase.cloneCase("testCase{:02}".format(i))

    epsilonBC = ParsedParameterFile(path.join(case.name, "0", "omega"))
    epsilonBC["boundaryField"]["fixedWalltop_patch1"]["value"].setUniform(eps)
    epsilonBC["boundaryField"]["fixedWallbot_patch1"]["value"].setUniform(eps)
    epsilonBC.writeFile()

    run = BasicRunner(argv=[solver, "-case", case.name], silent=False)
    # run.start()

    case = SolutionDirectory(case.name, archive=None, paraviewLink=False)

    if float(max(case.times)) < .28:
        case.clear()
        case.clearResults()
        trans = ParameterFile(
            path.join(case.name, "constant/transportProperties"))
        trans.readFile()
        trans.replaceParameter("nu", "[0 2 -1 0 0 0 0]  1e-5")
        trans.writeFile()
        # trans.closeFile()
        nus[i] = 1e-5
        run = BasicRunner(argv=[solver, "-case", case.name], silent=False)
Exemple #36
0
    logger.info('    Start time: %s' % startTime)
    logger.info('    End time:  %s' % endTime)
    logger.info('    pressureDiff: %s' % dp0)
    logger.info('    U0_0: %s' % U0_0)
    logger.info('    U0_Target: %s' % U0_Target)

    run = 0

    while run < 10:

        # Run the model
        logger.info(
            '-------------------------------------------------------------')
        logger.info('    Starting run of model.......RUN: %s' % run)
        logger.info('    Starting time: %s' % datetime.datetime.now())
        BasicRunner(argv=["pisoFoam", "-case ", dire.name],
                    silent=True).start()
        logger.info('    Ending time: %s' % datetime.datetime.now())
        time.sleep(1)

        # Run the sample utility
        logger.info('    Extracting the velocity profile')
        sample_str = "sample -latestTime -case "
        sample_str += case
        os.system(sample_str)
        time.sleep(5)

        # Read the velocity
        L1UfilePath = path.join(case, 'postProcessing/sets', str(endTime),
                                profile_name)
        U0_1 = getU0(L1UfilePath, level)
        logger.info('    The end velocity was: %s m/s, the target is: %s m/s' %
Exemple #37
0
def FOAM_model(xtr, y, ztr, Patient, Template):
    errorCode = True  ## True when simulation has succesfully run
    ## Specify simulation folder
    Simulation = Patient + "/simulation"

    ## Clear case
    ClearCase(args=["--clear-history", Simulation])
    print("Complete cleaning the case done")

    if not os.path.exists(Simulation):  ## if simulation directory doesnt exist
        ## Clone template onto simulation folder
        CloneCase(args=[Template, Simulation])
        print("Copied generic case to patient specific folder")

    ## copy betavSolid and actual skin temperature data onto the gland 0 folder
    shutil.copyfile(Template + "/0/gland/betavSolid",
                    Simulation + "/0/gland/betavSolid")
    shutil.copyfile(Patient + "/actualSkinData",
                    Simulation + "/0/gland/actualSkinData")

    ## define different cell zones using topoSetDict
    bmName = os.path.join(Simulation, 'system', "topoSetDict")
    template = TemplateFile(bmName + ".template", expressionDelimiter="$")
    template.writeToFile(bmName, {
        'x': xtr,
        'y': y,
        'z': ztr,
        'r': radius,
        'gr': gr
    })

    print("Setting template file for topoSet done")

    ## Run topoSet
    topoSetRun = BasicRunner(argv=["topoSet", "-case", Simulation],
                             silent=True,
                             server=False,
                             logname='log.topoSet')
    topoSetRun.start()
    if not topoSetRun.runOK():
        error("There was a problem with topoSet")
    print("topoSet done")
    print(xtr, y, ztr)

    ## Split mesh regions based on toposet
    splitMeshRegionsRun = BasicRunner(
        argv=["splitMeshRegions -cellZones -overwrite", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.splitMeshRegions')
    splitMeshRegionsRun.start()
    if not splitMeshRegionsRun.runOK():
        error("There was a problem with split mesh regions")
    print("split mesh regions done")

    ## Run change dictionary for gland region
    changeDictionaryGlandRun = BasicRunner(
        argv=[" changeDictionary -region gland", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.changeDictionaryGland')
    changeDictionaryGlandRun.start()
    if not changeDictionaryGlandRun.runOK():
        error("There was a problem with change dictionary for gland")
    print("change dictionary gland done")

    ## Run change dictionary for tumor region
    changeDictionaryTumorRun = BasicRunner(
        argv=[" changeDictionary -region tumor", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.changeDictionaryTumor')
    changeDictionaryTumorRun.start()
    if not changeDictionaryTumorRun.runOK():
        error("There was a problem with change dictionary for tumor")
    print("change dictionary tumor done")

    ## Run setFields for gland region
    setFieldsGlandRun = BasicRunner(
        argv=["setFields -region gland", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.setFieldsGland')
    setFieldsGlandRun.start()
    if not setFieldsGlandRun.runOK():
        error("There was a problem with setFields for gland")
    print("set fields for gland done")

    ## define gland anisotropic thermal conductivity
    bmName = os.path.join(Simulation, 'constant', 'gland',
                          "thermophysicalProperties")
    template = TemplateFile(bmName + ".template", expressionDelimiter="$")
    template.writeToFile(bmName, {'x': xtr, 'y': y, 'z': ztr})

    print("Setting anisotropic thermal conductivity for gland done")

    ## define tumor anisotropic thermal conductivity
    bmName = os.path.join(Simulation, 'constant', 'tumor',
                          "thermophysicalProperties")
    template = TemplateFile(bmName + ".template", expressionDelimiter="$")
    template.writeToFile(bmName, {'x': xtr, 'y': y, 'z': ztr})

    print("Setting anisotropic thermal conductivity for tumor done")

    ## removing fvoptions if benign tumor
    if state == 'benign':
        if not os.path.exists(Simulation + "/constant/tumor/fvOptions"):
            print("Removing heat sources for benign tumors done")
        else:
            os.remove(Simulation + "/constant/tumor/fvOptions")
            print("Removing heat sources for benign tumors done")

    ## multi region simple foam with two heat sources specified for tumor region
    print("Running")
    theRun = BasicRunner(
        argv=["chtMultiRegionSimpleFoam", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.solver')
    #"-postProcess", "-func", "surfaces"
    theRun.start()
    errorCode = theRun.endSeen

    if not theRun.runOK():
        error("There was a problem while running the solver")
    print("Solver run done")

    ## converting latest simulation step to VTK- gland
    print("Converting gland region to VTK")
    VTKGlandRun = BasicRunner(argv=[
        "foamToVTK -fields '(T)' -latestTime -ascii -region gland", "-case",
        Simulation
    ],
                              silent=True,
                              server=False,
                              logname='log.VTKGland')
    VTKGlandRun.start()
    if not VTKGlandRun.runOK():
        error(
            "There was a problem while converting the gland region to VTK for post-processing"
        )
    print("Conversion of Gland region to VTK done")

    ## converting latest simulation step to VTK- tumor
    print("Converting tumor region to VTK")
    VTKTumorRun = BasicRunner(argv=[
        "foamToVTK -fields '(T)' -latestTime -ascii -region tumor", "-case",
        Simulation
    ],
                              silent=True,
                              server=False,
                              logname='log.VTKTumor')
    VTKTumorRun.start()
    if not VTKTumorRun.runOK():
        error(
            "There was a problem while converting the tumor region to VTK for post-processing"
        )
    print("Conversion of Tumor region to VTK done")

    ## Moving VTK for post processing by rounding off to two decimal places
    if ((y * 100) % 1) == 0:
        y_str = str(round(y * 100) / 100) + '0'
    else:
        y_str = str(y)
    shutil.move(Simulation + "/VTK", Patient + "/VTK" + "/VTK" + y_str)
    return errorCode
Exemple #38
0
 def lineHandle(self,line):
     """Not to be called: calls the analyzer for the current line"""
     StepAnalyzedCommon.lineHandle(self,line)
     BasicRunner.lineHandle(self,line)
Exemple #39
0
 def lineHandle(self,line):
     """Not to be called: calls the analyzer for the current line"""
     StepAnalyzedCommon.lineHandle(self,line)
     BasicRunner.lineHandle(self,line)
Exemple #40
0
    def stopHandle(self):
        BasicRunner.stopHandle(self)
        StepAnalyzedCommon.stopHandle(self)

        self.tearDown()
Exemple #41
0
def run3dHillBase(template0, AR, z0, us, caseType):

	# loading other parameters from dictionary file
	inputDict = ParsedParameterFile("testZ0InfluenceDict")
	h		= inputDict["simParams"]["h"]
	yM 		= inputDict["simParams"]["yM"]
	# SHM parameters
	cell	= inputDict["SHMParams"]["cellSize"]["cell"] 
	Href = inputDict["SHMParams"]["domainSize"]["domZ"] 
	zz = inputDict["SHMParams"]["pointInDomain"]["zz"]
	# case definitions Martinez2DBump
	ks = 19.58 * z0 # [m] Martinez 2011
	k = inputDict["kEpsParams"]["k"]
	Cmu = inputDict["kEpsParams"]["Cmu"]	
	# yp/ks = 0.02 = x/ks
	hSample = inputDict["sampleParams"]["hSample"]
	procnr = multiprocessing.cpu_count()
	caseStr = "_z0_" + str(z0)
  	target = "runs/" + template0 + caseStr
  	x0, y0, phi = 	inputDict["SHMParams"]["centerOfDomain"]["x0"], inputDict["SHMParams"]["centerOfDomain"]["x0"], \
  					inputDict["SHMParams"]["flowOrigin"]["deg"]*pi/180
  	H = h
  	a = h*AR
	#--------------------------------------------------------------------------------------
	# cloning case
	#--------------------------------------------------------------------------------------
	orig = 	SolutionDirectory(template0,
			archive=None,
			paraviewLink=False)
	work = orig.cloneCase(target)
				  
	#--------------------------------------------------------------------------------------
	# changing inlet profile - - - - according to Martinez 2010
	#--------------------------------------------------------------------------------------
	# change inlet profile
	Uref = Utop = us/k*math.log(Href/z0)
	# calculating turbulentKE
	TKE = us*us/math.sqrt(Cmu)
	# 1: changing ABLConditions
	bmName = path.join(work.initialDir(),"include/ABLConditions")
	template = TemplateFile(bmName+".template")
	template.writeToFile(bmName,{'us':us,'Uref':Uref,'Href':Href,'z0':z0,'xDirection':sin(phi),'yDirection':cos(phi)})
	# 2: changing initialConditions
	bmName = path.join(work.initialDir(),"include/initialConditions")
	template = TemplateFile(bmName+".template")
	template.writeToFile(bmName,{'TKE':TKE})
	# 3: changing initial and boundary conditions for new z0
	# changing ks in nut, inside nutRoughWallFunction
	nutFile = ParsedParameterFile(path.join(work.initialDir(),"nut"))
	nutFile["boundaryField"]["ground"]["Ks"].setUniform(ks)
	nutFile["boundaryField"]["terrain_.*"]["Ks"].setUniform(ks)
	nutFile.writeFile()
	
	#--------------------------------------------------------------------------------------
	# changing sample file
	#--------------------------------------------------------------------------------------
	# 2: changing initialConditions
	bmName = path.join(work.systemDir(),"sampleDict")
	template = TemplateFile(bmName+".template")
	if AR>100:# flat terrain
		h=0
		template.writeToFile(bmName,{'hillTopY':0,'sampleHeightAbovePlain':50,'sampleHeightAboveHill':50,'inletX':3500})
	else:
		template.writeToFile(bmName,{'hillTopY':h,'sampleHeightAbovePlain':50,'sampleHeightAboveHill':h+50,'inletX':h*AR*4*0.9}) 
	
	# if SHM - create mesh
	if caseType.find("SHM")>0:
		phi = phi - pi/180 * 90	#--------------------------------------------------------------------------------------
		# creating blockMeshDict
		#--------------------------------------------------------------------------------------
		l, d = a*inputDict["SHMParams"]["domainSize"]["fX"], a*inputDict["SHMParams"]["domainSize"]["fY"]
		x1 = x0 - (l/2*sin(phi) + d/2*cos(phi))
		y1 = y0 - (l/2*cos(phi) - d/2*sin(phi))
		x2 = x0 - (l/2*sin(phi) - d/2*cos(phi))
		y2 = y0 - (l/2*cos(phi) + d/2*sin(phi))
		x3 = x0 + (l/2*sin(phi) + d/2*cos(phi))
		y3 = y0 + (l/2*cos(phi) - d/2*sin(phi))
		x4 = x0 + (l/2*sin(phi) - d/2*cos(phi))
		y4 = y0 + (l/2*cos(phi) + d/2*sin(phi))
		n = floor(d/(cell*inputDict["SHMParams"]["cellSize"]["cellYfactor"]))
		m = floor(l/(cell*inputDict["SHMParams"]["cellSize"]["cellYfactor"]))
		q = floor((Href+450)/cell) # -450 is the minimum of the blockMeshDict.template - since that is slightly lower then the lowest point on the planet

		bmName = path.join(work.constantDir(),"polyMesh/blockMeshDict")
		template = TemplateFile(bmName+".template")
		template.writeToFile(bmName,{'X0':x1,'X1':x2,'X2':x3,'X3':x4,'Y0':y1,'Y1':y2,'Y2':y3,'Y3':y4,'Z0':Href,'n':int(n),'m':int(m),'q':int(q)})
		
		#--------------------------------------------------------------------------------------
		# running blockMesh
		#--------------------------------------------------------------------------------------
		blockRun = BasicRunner(argv=["blockMesh",'-case',work.name],silent=True,server=False,logname="blockMesh")
		print "Running blockMesh"
		blockRun.start()
		if not blockRun.runOK(): error("there was an error with blockMesh")

		#--------------------------------------------------------------------------------------
		# running SHM
		#--------------------------------------------------------------------------------------
		print "calculating SHM parameters"
		# calculating refinement box positions
		l1, l2, h1, h2 = 2*a, 1.3*a, 4*H, 2*H # refinement rulls - Martinez 2011
		refBox1_minx, refBox1_miny, refBox1_minz = x0 - l1*(sin(phi)+cos(phi)), y0 - l1*(cos(phi)-sin(phi)), 0 #enlarging to take acount of the rotation angle
		refBox1_maxx, refBox1_maxy, refBox1_maxz = x0 + l1*(sin(phi)+cos(phi)), y0 + l1*(cos(phi)-sin(phi)), h1 #enlarging to take acount of the rotation angle
		refBox2_minx, refBox2_miny, refBox2_minz = x0 - l2*(sin(phi)+cos(phi)), y0 - l2*(cos(phi)-sin(phi)), 0 #enlarging to take acount of the rotation angle
		refBox2_maxx, refBox2_maxy, refBox2_maxz = x0 + l2*(sin(phi)+cos(phi)), y0 + l2*(cos(phi)-sin(phi)),h2 #enlarging to take acount of the rotation angle
		
		# changing cnappyHexMeshDict - with parsedParameterFile
		SHMDict = ParsedParameterFile(path.join(work.systemDir(),"snappyHexMeshDict"))
		SHMDict["geometry"]["refinementBox1"]["min"] = "("+str(refBox1_minx)+" "+str(refBox1_miny)+" "+str(refBox1_minz)+")"
		SHMDict["geometry"]["refinementBox1"]["max"] = "("+str(refBox1_maxx)+" "+str(refBox1_maxy)+" "+str(refBox1_maxz)+")"
		SHMDict["geometry"]["refinementBox2"]["min"] = "("+str(refBox2_minx)+" "+str(refBox2_miny)+" "+str(refBox2_minz)+")"
		SHMDict["geometry"]["refinementBox2"]["max"] = "("+str(refBox2_maxx)+" "+str(refBox2_maxy)+" "+str(refBox2_maxz)+")"
		SHMDict["castellatedMeshControls"]["locationInMesh"] = "("+str(x0)+" "+str(y0)+" "+str(zz)+")"
		levelRef = inputDict["SHMParams"]["cellSize"]["levelRef"]
		SHMDict["castellatedMeshControls"]["refinementSurfaces"]["terrain"]["level"] = "("+str(levelRef)+" "+str(levelRef)+")"
		r = inputDict["SHMParams"]["cellSize"]["r"]
		SHMDict["addLayersControls"]["expansionRatio"] = r
		fLayerRatio = inputDict["SHMParams"]["cellSize"]["fLayerRatio"]
		SHMDict["addLayersControls"]["finalLayerThickness"] = fLayerRatio
		# calculating finalLayerRatio for getting 
		zp_z0 = inputDict["SHMParams"]["cellSize"]["zp_z0"]
		firstLayerSize = 2*zp_z0*z0
		L = math.log(fLayerRatio/firstLayerSize*cell/2**levelRef)/math.log(r)+1
		SHMDict["addLayersControls"]["layers"]["terrain_solid"]["nSurfaceLayers"] = int(round(L))
		SHMDict.writeFile()
		"""
		# changing snappyHexMeshDict - with template file
		snapName = path.join(work.systemDir(),"snappyHexMeshDict")
		template = TemplateFile(snapName+".template")
		template.writeToFile(snapName,{	'refBox1_minx':refBox1_minx,'refBox1_miny':refBox1_miny,'refBox1_minz':refBox1_minz,
							'refBox1_maxx':refBox1_maxx,'refBox1_maxy':refBox1_maxy,'refBox1_maxz':refBox1_maxz,
							'refBox2_minx':refBox2_minx,'refBox2_miny':refBox2_miny,'refBox2_minz':refBox2_minz,
							'refBox2_maxx':refBox2_maxx,'refBox2_maxy':refBox2_maxy,'refBox2_maxz':refBox2_maxz,
							'locInMesh_x':x0,'locInMesh_y':y0,'locInMesh_z':zz})
		"""
		# TODO - add parallel runs!
		SHMrun = BasicRunner(argv=["snappyHexMesh",'-overwrite','-case',work.name],server=False,logname="SHM")
		print "Running SHM"
		SHMrun.start()
	
	
	# mapping fields - From earlier result if exists
	if caseType.find("mapFields")>0: #TODO - fix mapping issue. mucho importante!
		#copying results from other z0 converged runs
  		setName =  glob.glob(target + 'Crude/sets/*')
  		lastRun = range(len(setName))
		for num in range(len(setName)):
			lastRun[num] = int(setName[num][setName[num].rfind("/")+1:])
  		sourceTimeArg = str(max(lastRun))
		mapRun = BasicRunner(argv=['mapFields -consistent -sourceTime ' + sourceTimeArg +
			 ' -case ' + work.name + ' ' + target + "Crude"],silent=True,server=False,logname='mapLog')
		mapRun.start()
		
	# parallel rule
	#print "Mesh has " + str(cells) + " cells"
	#if cells>100000: parallel=1
	#else: parallel=0
	parallel = 1
	cluster = 1
	if parallel:
		#--------------------------------------------------------------------------------------
		# decomposing
		#--------------------------------------------------------------------------------------
		# removing U.template from 0/ directory
		subprocess.call("rm " + bmName + ".template ",shell=True)
		arg = " -case " + work.name
	 	decomposeRun = BasicRunner(argv=["decomposePar -force" + arg],silent=True,server=False,logname="decompose")
		decomposeRun.start()


		#--------------------------------------------------------------------------------------
		# running
		#--------------------------------------------------------------------------------------
		machine = LAMMachine(nr=procnr)
		# run case
		PlotRunner(args=["--proc=%d"%procnr,"--progress","--no-continuity","--hardcopy", "--non-persist", "simpleFoam","-case",work.name])

		#--------------------------------------------------------------------------------------
		# reconstruct
		#-------------------------------------------------------------------------
		reconstructRun = BasicRunner(argv=["reconstructPar -latestTime" + arg],silent=True,server=False,logname="reconstructLog")
		reconstructRun.start()
	else:
		
		#--------------------------------------------------------------------------------------
		# running
		#--------------------------------------------------------------------------------------
		PlotRunner(args=["--progress","simpleFoam","-case",work.name])

	# sample results
	dirNameList = glob.glob(target + "*")
	dirNameList.sort()
	for dirName in dirNameList:
 		# sampling
 		arg = " -case " + dirName + "/"
 		sampleRun = BasicRunner(argv=["sample -latestTime" + arg],silent=True,server=False,logname="sampleLog")
		sampleRun.start()
 	#finding the most converged run.
  	setName =  glob.glob(dirName + '/sets/*')
  	lastRun = range(len(setName))
	for num in range(len(setName)):
		lastRun[num] = int(setName[num][setName[num].rfind("/")+1:])
  	m = max(lastRun)
  	p = lastRun.index(m)
	data_y = genfromtxt(setName[p] + '/line_y_U.xy',delimiter=' ')
  	y, Ux_y, Uy_y  = data_y[:,0], data_y[:,1], data_y[:,2] 
	if AR<100: 	# if terrain isn't flat
		#TODO find the height of the hill - the exact one! because of truncation errors etc - 
		#just follow the line measurements and look for the first place above 0
		h = min(data_y[:,0])
		y = y-h # normalizing data to height of hill-top above ground

	return y,Ux_y,Uy_y
Exemple #42
0
    #clone base case
    clone_name = '/%s/dTdz%0.3f_z%d' % (path.join(getcwd(),
                                                  copy_dir), temp, depth)
    clone = dire.cloneCase(clone_name)

    #read parameter file and change parameter
    param_file = ParsedParameterFile(
        path.join(clone_name, 'constant', 'parameterFile'))
    param_file['dTdz'] = 'dTdz [0 -1 0 0 0 0 0] %0.3f' % temp
    param_file['z0'] = 'z0 [0 1 0 0 0 0 0] %.1f' % depth
    param_file.writeFile()

    #set initial fields
    run_initFields = BasicRunner(
        argv=['setInitialFields', '-case', clone_name],
        logname='setInitialFields')
    run_initFields.start()
    print('initial fields set')

    #implement parallelization
    print('Decomposing...')
    Decomposer(args=['--progress', clone_name, num_procs])
    CaseReport(args=['--decomposition', clone_name])
    machine = LAMMachine(nr=num_procs)

    #run solver
    print('Running solver...')
    print('PID: ' + str(getpid()))
    run_solver = BasicRunner(argv=['trainingSolver', '-case', clone_name],
                             logname='trainingSolver',
Exemple #43
0
# from os import path
from PyFoam.Execution.BasicRunner import BasicRunner

from setupCases import pbe_grids

if __name__ == "__main__":

    for c in ["pure_coal", "pure_br"]:
        for N in pbe_grids:
            block_mesh = BasicRunner(
                argv=["blockMesh", "-case", "{0}{1}".format(c, N)],
                silent=True
            )
            block_mesh.start()
            run = BasicRunner(
                argv=["twoPhaseEulerFoam", "-case", "{0}{1}".format(c, N)],
                silent=True
            )
            run.start()
Exemple #44
0
 nutFile = ParsedParameterFile(path.join(work.initialDir(),"nut"))
 nutFile["boundaryField"]["ground"]["Ks"].setUniform(ks)
 nutFile.writeFile()
 # changing ABLconditions
 bmName = path.join(work.initialDir(),"include/ABLconditions")
 template = TemplateFile(bmName+".template")
 template.writeToFile(bmName,{'z0':z0,'us':us})
 # changing initialConditions
 bmName = path.join(work.initialDir(),"include/initialConditions")
 template = TemplateFile(bmName+".template")
 template.writeToFile(bmName,{'TKE':TKE})
 
 # run the new case
 # creating mesh
 if withBlock==1:
   blockRun = BasicRunner(argv=["blockMesh",'-case',work.name],silent=True,server=False,logname="blocky")
   print "Running blockMesh"
   blockRun.start()
   if not blockRun.runOK(): error("there was an error with blockMesh")
 # decomposing
 print "Decomposing"
 Decomposer(args=["--progress",work.name,2])
 CaseReport(args=["--decomposition",work.name])
 # running
 machine = LAMMachine(nr=2)
 
 # laminar case for better first guess (rarely converges for 2D case with simpleFoam)
 print "running laminar case"
 turb = ParsedParameterFile(path.join(work.name,'constant/RASProperties'))
 turb["turbulence"]="off"
 turb.writeFile()
Exemple #45
0
    def run(self):
        config=ConfigParser.ConfigParser()
        files=self.parser.getArgs()

        good=config.read(files)
        # will work with 2.4
        # if len(good)!=len(files):
        #    print "Problem while trying to parse files",files
        #    print "Only ",good," could be parsed"
        #    sys.exit(-1)

        benchName=config.get("General","name")
        if self.opts.nameAddition!=None:
            benchName+="_"+self.opts.nameAddition
        if self.opts.foamVersion!=None:
            benchName+="_v"+self.opts.foamVersion
            
        isParallel=config.getboolean("General","parallel")
        lam=None

        if isParallel:
            nrCpus=config.getint("General","nProcs")
            machineFile=config.get("General","machines")
            if not path.exists(machineFile):
                self.error("Machine file ",machineFile,"needed for parallel run")
            lam=LAMMachine(machineFile,nr=nrCpus)
            if lam.cpuNr()>nrCpus:
                self.error("Wrong number of CPUs: ",lam.cpuNr())

            print "Running parallel on",lam.cpuNr(),"CPUs"

        if config.has_option("General","casesDirectory"):
            casesDirectory=path.expanduser(config.get("General","casesDirectory"))
        else:
            casesDirectory=foamTutorials()

        if not path.exists(casesDirectory):
            self.error("Directory",casesDirectory,"needed with the benchmark cases is missing")
        else:
            print "Using cases from directory",casesDirectory

        benchCases=[]
        config.remove_section("General")

        for sec in config.sections():
            print "Reading: ",sec
            skipIt=False
            skipReason=""
            if config.has_option(sec,"skip"):
                skipIt=config.getboolean(sec,"skip")
                skipReason="Switched off in file"
            if self.opts.excases!=None and not skipIt:
                for p in self.opts.excases:
                    if fnmatch(sec,p):
                        skipIt=True
                        skipReason="Switched off by pattern '"+p+"'"
            if self.opts.cases!=None:
                for p in self.opts.cases:
                    if fnmatch(sec,p):
                        skipIt=False
                        skipReason=""
                
            if skipIt:
                print "Skipping case ..... Reason:"+skipReason
                continue
            sol=config.get(sec,"solver")
            cas=config.get(sec,"case")
            pre=eval(config.get(sec,"prepare"))
            preCon=[]
            if config.has_option(sec,"preControlDict"):
                preCon=eval(config.get(sec,"preControlDict"))
            con=eval(config.get(sec,"controlDict"))
            bas=config.getfloat(sec,"baseline")
            wei=config.getfloat(sec,"weight")
            add=[]
            if config.has_option(sec,"additional"):
                add=eval(config.get(sec,"additional"))
                print "Adding: ", add
            util=[]
            if config.has_option(sec,"utilities"):
                util=eval(config.get(sec,"utilities"))
                print "Utilities: ", util    
            nr=99999
            if config.has_option(sec,"nr"):
                nr=eval(config.get(sec,"nr"))
            sp=None
            if config.has_option(sec,"blockSplit"):
                sp=eval(config.get(sec,"blockSplit"))
            toRm=[]
            if config.has_option(sec,"filesToRemove"):
                toRm=eval(config.get(sec,"filesToRemove"))
            setInit=[]
            if config.has_option(sec,"setInitial"):
                setInit=eval(config.get(sec,"setInitial"))

            parallelOK=False
            if config.has_option(sec,"parallelOK"):
                parallelOK=config.getboolean(sec,"parallelOK")

            deMet=["metis"]
            if config.has_option(sec,"decomposition"):
                deMet=config.get(sec,"decomposition").split()

            if deMet[0]=="metis":
                pass
            elif deMet[0]=="simple":
                if len(deMet)<2:
                    deMet.append(0)
                else:
                    deMet[1]=int(deMet[1])
            else:
                print "Unimplemented decomposition method",deMet[0],"switching to metis"
                deMet=["metis"]

            if isParallel==False or parallelOK==True:
                if path.exists(path.join(casesDirectory,sol,cas)):
                    benchCases.append( (nr,sec,sol,cas,pre,con,preCon,bas,wei,add,util,sp,toRm,setInit,deMet) )
                else:
                    print "Skipping",sec,"because directory",path.join(casesDirectory,sol,cas),"could not be found"
            else:
                print "Skipping",sec,"because not parallel"

        benchCases.sort()

        parallelString=""
        if isParallel:
            parallelString=".cpus="+str(nrCpus)

        resultFile=open("Benchmark."+benchName+"."+uname()[1]+parallelString+".results","w")

        totalSpeedup=0
        minSpeedup=None
        maxSpeedup=None
        totalWeight =0
        runsOK=0
        currentEstimate = 1.

        print "\nStart Benching\n"
        
        csv=CSVCollection("Benchmark."+benchName+"."+uname()[1]+parallelString+".csv")
        
#        csvHeaders=["description","solver","case","caseDir","base",
#                    "benchmark","machine","arch","cpus","os","version",
#                    "wallclocktime","cputime","cputimeuser","cputimesystem","maxmemory","cpuusage","speedup"]

        for nr,description,solver,case,prepare,control,preControl,base,weight,additional,utilities,split,toRemove,setInit,decomposition in benchCases:
            #    control.append( ("endTime",-2000) )
            print "Running Benchmark: ",description
            print "Solver: ",solver
            print "Case: ",case
            caseName=solver+"_"+case+"_"+benchName+"."+uname()[1]+".case"
            print "Short name: ",caseName
            caseDir=caseName+".runDir"

            csv["description"]=description
            csv["solver"]=solver
            csv["case"]=case
            csv["caseDir"]=caseDir
            csv["base"]=base

            csv["benchmark"]=benchName
            csv["machine"]=uname()[1]
            csv["arch"]=uname()[4]
            if lam==None:
                csv["cpus"]=1
            else:
                csv["cpus"]=lam.cpuNr()
            csv["os"]=uname()[0]
            csv["version"]=uname()[2]
            
            workDir=path.realpath(path.curdir)

            orig=SolutionDirectory(path.join(casesDirectory,solver,case),
                                   archive=None,
                                   paraviewLink=False)
            for a in additional+utilities:
                orig.addToClone(a)
            orig.cloneCase(path.join(workDir,caseDir))

            if oldApp():
                argv=[solver,workDir,caseDir]
            else:
                argv=[solver,"-case",path.join(workDir,caseDir)]
                
            run=BasicRunner(silent=True,argv=argv,logname="BenchRunning",lam=lam)
            runDir=run.getSolutionDirectory()
            controlFile=ParameterFile(runDir.controlDict())

            for name,value in preControl:
                print "Setting parameter",name,"to",value,"in controlDict"
                controlFile.replaceParameter(name,value)

            for rm in toRemove:
                fn=path.join(caseDir,rm)
                print "Removing file",fn
                remove(fn)

            for field,bc,val in setInit:
                print "Setting",field,"on",bc,"to",val
                SolutionFile(runDir.initialDir(),field).replaceBoundary(bc,val)

            oldDeltaT=controlFile.replaceParameter("deltaT",0)

            for u in utilities:
                print "Building utility ",u
                execute("wmake 2>&1 >%s %s" % (path.join(caseDir,"BenchCompile."+u),path.join(caseDir,u)))

            print "Preparing the case: "
            if lam!=None:
                prepare=prepare+[("decomposePar","")]
                if decomposition[0]=="metis":
                    lam.writeMetis(SolutionDirectory(path.join(workDir,caseDir)))
                elif decomposition[0]=="simple":
                    lam.writeSimple(SolutionDirectory(path.join(workDir,caseDir)),decomposition[1])

            if split:
                print "Splitting the mesh:",split
                bm=BlockMesh(runDir.blockMesh())
                bm.refineMesh(split)

            for pre,post in prepare:
                print "Doing ",pre," ...."
                post=post.replace("%case%",caseDir)
                if oldApp():
                    args=string.split("%s %s %s %s" % (pre,workDir,caseDir,post))
                else:
                    args=string.split("%s -case %s %s" % (pre,path.join(workDir,caseDir),post))
                util=BasicRunner(silent=True,argv=args,logname="BenchPrepare_"+pre)
                util.start()

            controlFile.replaceParameter("deltaT",oldDeltaT)

            #    control.append(("endTime",-1000))
            for name,value in control:
                print "Setting parameter",name,"to",value,"in controlDict"
                controlFile.replaceParameter(name,value)

            print "Starting at ",asctime(localtime(time()))
            print " Baseline is %f, estimated speedup %f -> estimated end at %s " % (base,currentEstimate,asctime(localtime(time()+base/currentEstimate)))
            print "Running the case ...."
            run.start()

            speedup=None
            cpuUsage=0
            speedupOut=-1

            try:
                speedup=base/run.run.wallTime()
                cpuUsage=100.*run.run.cpuTime()/run.run.wallTime()
            except ZeroDivisionError:
                print "Division by Zero: ",run.run.wallTime()

            if not run.runOK():
                print "\nWARNING!!!!"
                print "Run had a problem, not using the results. Check the log\n"
                speedup=None

            if speedup!=None:
                speedupOut=speedup

                totalSpeedup+=speedup*weight
                totalWeight +=weight
                runsOK+=1
                if maxSpeedup==None:
                    maxSpeedup=speedup
                elif speedup>maxSpeedup:
                    maxSpeedup=speedup
                if minSpeedup==None:
                    minSpeedup=speedup
                elif speedup<minSpeedup:
                    minSpeedup=speedup

            print "Wall clock: ",run.run.wallTime()
            print "Speedup: ",speedup," (Baseline: ",base,")"
            print "CPU Time: ",run.run.cpuTime()
            print "CPU Time User: "******"CPU Time System: ",run.run.cpuSystemTime()
            print "Memory: ",run.run.usedMemory()
            print "CPU Usage: %6.2f%%" % (cpuUsage)

            csv["wallclocktime"]=run.run.wallTime()
            csv["cputime"]=run.run.cpuTime()
            csv["cputimeuser"]=run.run.cpuUserTime()
            csv["cputimesystem"]=run.run.cpuSystemTime()
            csv["maxmemory"]=run.run.usedMemory()
            csv["cpuusage"]=cpuUsage
            if speedup!=None:
                csv["speedup"]=speedup
            else:
                csv["speedup"]="##"
                
            csv.write()
            
            resultFile.write("Case %s WallTime %g CPUTime %g UserTime %g SystemTime %g Memory %g MB  Speedup %g\n" %(caseName,run.run.wallTime(),run.run.cpuTime(),run.run.cpuUserTime(),run.run.cpuSystemTime(),run.run.usedMemory(),speedupOut))

            resultFile.flush()
            
            if speedup!=None:
                currentEstimate=totalSpeedup/totalWeight

            if self.opts.removeCases:
                print "Clearing case",
                if speedup==None:
                    print "not ... because it failed"
                else:
                    print "completely"
                    rmtree(caseDir,ignore_errors=True)

            print
            print
        
        if lam!=None:
            lam.stop()

        print "Total Speedup: ",currentEstimate," ( ",totalSpeedup," / ",totalWeight, " ) Range: [",minSpeedup,",",maxSpeedup,"]"

        print runsOK,"of",len(benchCases),"ran OK"

        resultFile.write("Total Speedup: %g\n" % (currentEstimate))
        if minSpeedup and maxSpeedup:
            resultFile.write("Range: [ %g , %g ]\n" % (minSpeedup,maxSpeedup))

        resultFile.close()
Exemple #46
0
    def prepare(self,
                sol,
                cName=None,
                overrideParameters=None,
                numberOfProcessors=None):
        """Do the actual preparing
        :param numberOfProcessors: If set this overrides the value set in the
        command line"""

        if cName == None:
            cName = sol.name

        if self.opts.onlyVariables:
            self.opts.verbose = True

        vals = {}
        vals, self.metaData = self.getDefaultValues(cName)
        vals.update(
            self.addDictValues(
                "System", "Automatically defined values", {
                    "casePath":
                    '"' + path.abspath(cName) + '"',
                    "caseName":
                    '"' + path.basename(path.abspath(cName)) + '"',
                    "foamVersion":
                    foamVersion(),
                    "foamFork":
                    foamFork(),
                    "numberOfProcessors":
                    numberOfProcessors if numberOfProcessors != None else
                    self.opts.numberOfProcessors
                }))

        if len(self.opts.extensionAddition) > 0:
            vals.update(
                self.addDictValues(
                    "ExtensionAdditions",
                    "Additional extensions to be processed",
                    dict((e, True) for e in self.opts.extensionAddition)))

        valsWithDefaults = set(vals.keys())

        self.info("Looking for template values", cName)
        for f in self.opts.valuesDicts:
            self.info("Reading values from", f)
            vals.update(
                ParsedParameterFile(f, noHeader=True,
                                    doMacroExpansion=True).getValueDict())

        setValues = {}
        for v in self.opts.values:
            self.info("Updating values", v)
            vals.update(eval(v))
            setValues.update(eval(v))

        if overrideParameters:
            vals.update(overrideParameters)

        unknownValues = set(vals.keys()) - valsWithDefaults
        if len(unknownValues) > 0:
            self.warning("Values for which no default was specified: " +
                         ", ".join(unknownValues))

        if self.opts.verbose and len(vals) > 0:
            print_("\nUsed values\n")
            nameLen = max(len("Name"), max(*[len(k) for k in vals.keys()]))
            format = "%%%ds - %%s" % nameLen
            print_(format % ("Name", "Value"))
            print_("-" * 40)
            for k, v in sorted(iteritems(vals)):
                print_(format % (k, v))
            print_("")
        else:
            self.info("\nNo values specified\n")

        self.checkCorrectOptions(vals)

        derivedScript = path.join(cName, self.opts.derivedParametersScript)
        derivedAdded = None
        derivedChanged = None
        if path.exists(derivedScript):
            self.info("Deriving variables in script", derivedScript)
            scriptText = open(derivedScript).read()
            glob = {}
            oldVals = vals.copy()
            exec_(scriptText, glob, vals)
            derivedAdded = []
            derivedChanged = []
            for k, v in iteritems(vals):
                if k not in oldVals:
                    derivedAdded.append(k)
                elif vals[k] != oldVals[k]:
                    derivedChanged.append(k)
            if len(derivedChanged) > 0 and (
                    not self.opts.allowDerivedChanges
                    and not configuration().getboolean("PrepareCase",
                                                       "AllowDerivedChanges")):
                self.error(
                    self.opts.derivedParametersScript, "changed values of",
                    " ".join(derivedChanged),
                    "\nTo allow this set --allow-derived-changes or the configuration item 'AllowDerivedChanges'"
                )
            if len(derivedAdded) > 0:
                self.info("Added values:", " ".join(derivedAdded))
            if len(derivedChanged) > 0:
                self.info("Changed values:", " ".join(derivedChanged))
            if len(derivedAdded) == 0 and len(derivedChanged) == 0:
                self.info("Nothing added or changed")
        else:
            self.info("No script", derivedScript, "for derived values")

        if self.opts.onlyVariables:
            return

        self.__writeToStateFile(sol, "Starting")

        if self.opts.doClear:
            self.info("Clearing", cName)
            self.__writeToStateFile(sol, "Clearing")
            sol.clear(processor=True,
                      pyfoam=True,
                      vtk=True,
                      removeAnalyzed=True,
                      keepParallel=False,
                      clearHistory=False,
                      clearParameters=True,
                      additional=["postProcessing"])
            self.__writeToStateFile(sol, "Done clearing")

        if self.opts.writeParameters:
            fName = path.join(cName, self.parameterOutFile)
            self.info("Writing parameters to", fName)
            with WriteParameterFile(fName, noHeader=True) as w:
                w.content.update(vals, toString=True)
                w["foamVersion"] = vals["foamVersion"]
                w.writeFile()

        if self.opts.writeReport:
            fName = path.join(cName, self.parameterOutFile + ".rst")
            self.info("Writing report to", fName)
            with open(fName, "w") as w:
                helper = RestructuredTextHelper(defaultHeading=1)
                w.write(".. title:: " + self.__strip(vals["caseName"]) + "\n")
                w.write(".. sectnum::\n")
                w.write(".. header:: " + self.__strip(vals["caseName"]) + "\n")
                w.write(".. header:: " + time.asctime() + "\n")
                w.write(".. footer:: ###Page### / ###Total###\n\n")

                w.write("Parameters set in case directory " +
                        helper.literal(self.__strip(vals["casePath"])) +
                        " at " + helper.emphasis(time.asctime()) + "\n\n")
                w.write(".. contents::\n\n")
                if len(self.opts.valuesDicts):
                    w.write(helper.heading("Parameter files"))
                    w.write("Parameters read from files\n\n")
                    w.write(
                        helper.enumerateList([
                            helper.literal(f) for f in self.opts.valuesDicts
                        ]))
                    w.write("\n")
                if len(setValues) > 0:
                    w.write(helper.heading("Overwritten parameters"))
                    w.write(
                        "These parameters were set from the command line\n\n")
                    w.write(helper.definitionList(setValues))
                    w.write("\n")
                w.write(helper.heading("Parameters with defaults"))
                w.write(self.makeReport(vals))
                if len(unknownValues) > 0:
                    w.write(helper.heading("Unspecified parameters"))
                    w.write(
                        "If these parameters are actually used then specify them in "
                        + helper.literal(self.defaultParameterFile) + "\n\n")
                    tab = helper.table(True)
                    for u in unknownValues:
                        tab.addRow(u)
                        tab.addItem("Value", vals[u])
                    w.write(str(tab))
                if not derivedAdded is None:
                    w.write(helper.heading("Derived Variables"))
                    w.write("Script with derived Parameters" +
                            helper.literal(derivedScript) + "\n\n")
                    if len(derivedAdded) > 0:
                        w.write("These values were added:\n")
                        tab = helper.table(True)
                        for a in derivedAdded:
                            tab.addRow(a)
                            tab.addItem("Value", str(vals[a]))
                        w.write(str(tab))
                    if len(derivedChanged) > 0:
                        w.write("These values were changed:\n")
                        tab = helper.table(True)
                        for a in derivedChanged:
                            tab.addRow(a)
                            tab.addItem("Value", str(vals[a]))
                            tab.addItem("Old", str(oldVals[a]))
                        w.write(str(tab))
                    w.write("The code of the script:\n")
                    w.write(helper.code(scriptText))

        self.addToCaseLog(cName)

        for over in self.opts.overloadDirs:
            self.info("Overloading files from", over)
            self.__writeToStateFile(sol, "Overloading")
            self.overloadDir(sol.name, over)

        self.__writeToStateFile(sol, "Initial")

        zeroOrig = path.join(sol.name, "0.org")

        hasOrig = path.exists(zeroOrig)
        cleanZero = True

        if not hasOrig:
            self.info("Not going to clean '0'")
            self.opts.cleanDirectories.remove("0")
            cleanZero = False

        if self.opts.doCopy:
            if hasOrig:
                self.info("Found 0.org. Clearing 0")
                zeroDir = path.join(sol.name, "0")
                if path.exists(zeroDir):
                    rmtree(zeroDir)
                else:
                    self.info("No 0-directory")

            self.info("")
        else:
            cleanZero = False

        if self.opts.doTemplates:
            self.__writeToStateFile(sol, "Templates")
            self.searchAndReplaceTemplates(
                sol.name,
                vals,
                self.opts.templateExt,
                ignoreDirectories=self.opts.ignoreDirectories)

            self.info("")

        backupZeroDir = None

        if self.opts.doMeshCreate:
            self.__writeToStateFile(sol, "Meshing")
            if self.opts.meshCreateScript:
                scriptName = path.join(sol.name, self.opts.meshCreateScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultMeshCreate)):
                scriptName = path.join(sol.name, self.defaultMeshCreate)
            else:
                scriptName = None

            if scriptName:
                self.info("Executing", scriptName, "for mesh creation")
                if self.opts.verbose:
                    echo = "Mesh: "
                else:
                    echo = None
                self.executeScript(scriptName, workdir=sol.name, echo=echo)
            else:
                self.info(
                    "No script for mesh creation found. Looking for 'blockMeshDict'"
                )
                if sol.blockMesh() != "":
                    self.info(sol.blockMesh(), "found. Executing 'blockMesh'")
                    bm = BasicRunner(argv=["blockMesh", "-case", sol.name])
                    bm.start()
                    if not bm.runOK():
                        self.error("Problem with blockMesh")
                for r in sol.regions():
                    self.info("Checking region", r)
                    s = SolutionDirectory(sol.name,
                                          region=r,
                                          archive=None,
                                          paraviewLink=False)
                    if s.blockMesh() != "":
                        self.info(s.blockMesh(),
                                  "found. Executing 'blockMesh'")
                        bm = BasicRunner(argv=[
                            "blockMesh", "-case", sol.name, "-region", r
                        ])
                        bm.start()
                        if not bm.runOK():
                            self.error("Problem with blockMesh")

            self.info("")

            if cleanZero and path.exists(zeroDir):
                self.warning("Mesh creation recreated 0-directory")
                if self.opts.keepZeroDirectoryFromMesh:
                    backupZeroDir = zeroDir + ".bakByPyFoam"
                    self.info("Backing up", zeroDir, "to", backupZeroDir)
                    move(zeroDir, backupZeroDir)
                else:
                    self.info("Data in", zeroDir, "will be removed")
            self.__writeToStateFile(sol, "Done Meshing")

        if self.opts.doCopy:
            self.__writeToStateFile(sol, "Copying")
            self.copyOriginals(sol.name)

            self.info("")

            if backupZeroDir:
                self.info("Copying backups from", backupZeroDir, "to", zeroDir)
                self.overloadDir(zeroDir, backupZeroDir)
                self.info("Removing backup", backupZeroDir)
                rmtree(backupZeroDir)

        if self.opts.doPostTemplates:
            self.__writeToStateFile(sol, "Post-templates")
            self.searchAndReplaceTemplates(
                sol.name,
                vals,
                self.opts.postTemplateExt,
                ignoreDirectories=self.opts.ignoreDirectories)

            self.info("")

        if self.opts.doCaseSetup:
            self.__writeToStateFile(sol, "Case setup")
            if self.opts.caseSetupScript:
                scriptName = path.join(sol.name, self.opts.caseSetupScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultCaseSetup)):
                scriptName = path.join(sol.name, self.defaultCaseSetup)
            else:
                scriptName = None

            if scriptName:
                self.info("Executing", scriptName, "for case setup")
                if self.opts.verbose:
                    echo = "Case:"
                else:
                    echo = None
                self.executeScript(scriptName, workdir=sol.name, echo=echo)
            elif path.exists(path.join(sol.name, "system", "setFieldsDict")):
                self.info(
                    "So setup script found. But 'setFieldsDict'. Executing setFields"
                )
                sf = BasicRunner(argv=["setFields", "-case", sol.name])
                sf.start()
                if not sf.runOK():
                    self.error("Problem with setFields")
            else:
                self.info("No script for case-setup found. Nothing done")
            self.info("")
            self.__writeToStateFile(sol, "Done case setup")

        if self.opts.doFinalTemplates:
            self.__writeToStateFile(sol, "Final templates")
            self.searchAndReplaceTemplates(
                sol.name,
                vals,
                self.opts.finalTemplateExt,
                ignoreDirectories=self.opts.ignoreDirectories)

        if self.opts.doTemplateClean:
            self.info("Clearing templates")
            for d in self.opts.cleanDirectories:
                for e in [
                        self.opts.templateExt, self.opts.postTemplateExt,
                        self.opts.finalTemplateExt
                ]:
                    self.cleanExtension(path.join(sol.name, d), e)
            self.info("")

        self.info("Case setup finished")
        self.__writeToStateFile(sol, "Finished OK")
Exemple #47
0
#f.Q *= stdNoise ** 2
#ensemble = f.initialize(x=x, P=P)

# Generating lists for data collection and for plots
thetaList = []
ThetaListOne = []
ThetaListAll = []
ThetaListMeanT = []
ThetaListMeanT1Grid = []
ThetaListMeanT1Time = []
ThetaListMeanT1TimeForPlot = []
ThetaListMeanTAll = []
ThetaListMeanTAllForPlot = []

# Prediction using the OpenFoam -- RichardsFoam2
blockRun = BasicRunner(argv=["blockMesh"], silent=True, server=False)
print("Running blockMesh")
blockRun.start()
if not blockRun.runOK():
    error("There was a problem with blockMesh")

print("Running RichardsFoam2")
for i in range(N):  # N ensemble member
    print('Ensemble number: ', i + 1)
    ThetaListOne = []
    for j in range(timeSpan):
        print('At day: ', j + 1)
        control["startTime"] = j * dt
        control["endTime"] = (j + 1) * dt
        control.writeFile()
        state = ParsedParameterFile(str(control["startTime"]) + '/psi')
Exemple #48
0
def prepareCase_2dHill(template0, targetDir, target0, hillName, AR, r, x, Ls, L, L1, H, x0, z0, us, yM, h, caseType):

    # case definitions Martinez2DBump
    ks = 19.58 * z0 # [m] Martinez 2011
    k = 0.4
    Cmu = 0.03     # Castro 96
    Htop = Href = H    # [m]

    # yp/ks = 0.02 = x/ks
    funky = 0
    plotMartinez = 1
    hSample = 10
    fac = 10 # currecting calculation of number of cells and Rx factor to get a smooth transition 
             # from the inner refined cell and the outer less refined cells of the blockMesh Mesh
    procnr = 4

    caseStr = "_AR_" + str(AR) + "_z0_" + str(z0)
    if caseType=="Crude":
        caseStr = caseStr + "Crude"
    target = os.path.join(targetDir, target0 + caseStr)
    if not os.path.exists(template0):
        print "there is no %r directory in the current directory %r" % (template0, os.getcwd())
        raise SystemExit
    orig = SolutionDirectory(template0,
              archive=None,
              paraviewLink=False)
    #--------------------------------------------------------------------------------------
    # clonning case
    #--------------------------------------------------------------------------------------
    if not os.path.exists(targetDir):
        os.mkdir(targetDir)
    work = orig.cloneCase(target)

    #--------------------------------------------------------------------------------------
    # creating mesh
    #--------------------------------------------------------------------------------------
    y0 =  2 * x * z0 # setting first cell according to Martinez 2011 p. 25
    ny = int(round(math.log(H/y0*(r-1)+1)/math.log(r)))    # number of cells in the y direction of the hill block
    Ry  = r**(ny-1.)
    nx = int(L/x0-1)
    rx = max(r,1.1)
    ns = int(round(math.log((Ls-L)/x0*(rx-1)/rx**fac+1)/math.log(rx)))    # number of cells in the x direction of the hill block
    Rx = rx**(ns-1)
    # changing blockMeshDict - from template file
    bmName = path.join(work.constantDir(),"polyMesh/blockMeshDict")
    if AR==1000: # if flat terrain
        template = TemplateFile(bmName+"_flat_3cell.template")
    else:
        template = TemplateFile(bmName+"_3cell.template")
    template.writeToFile(bmName,{'H':H,'ny':ny,'Ry':Ry,'nx':nx,'L':L,'L1':L1,'Ls':Ls,'Rx':Rx,'Rx_one_over':1/Rx,'ns':ns})
    # writing ground shape (hill, or whatever you want - equation in function writeGroundShape.py)
    # sample file is changed as well - for sampling h=10 meters above ground
    sampleName = path.join(work.systemDir(),"sampleDict.template")
    write2dShape(bmName,H,L,sampleName,hSample,hillName,AR)
    # changing Y line limits
    bmName = path.join(work.systemDir(),"sampleDict")
    template = TemplateFile(bmName + ".template")
    if AR==1000: # if flat terrain
        template.writeToFile(bmName,{'hillTopY':0,'maxY':yM*2.5})
    else:
        template.writeToFile(bmName,{'hillTopY':h,'maxY':yM*2.5+h})

    # running blockMesh
    print "running blockMesh"
    blockRun = BasicRunner(argv=["blockMesh",'-case',work.name],silent=True,server=False,logname="blockMesh")
    blockRun.start()
    if not blockRun.runOK():
        error("there was an error with blockMesh")

    #--------------------------------------------------------------------------------------
    # changing inlet profile - - - - according to Martinez 2010
    #--------------------------------------------------------------------------------------
    # change inlet profile
    Uref = Utop = us/k*math.log(Href/z0)
    # calculating turbulentKE
    TKE = us*us/math.sqrt(Cmu)
    # 1: changing ABLConditions
    bmName = path.join(work.initialDir(),"include/ABLConditions")
    template = TemplateFile(bmName+".template")
    template.writeToFile(bmName,{'us':us,'Uref':Uref,'Href':Href,'z0':z0})
    # 2: changing initialConditions
    bmName = path.join(work.initialDir(),"include/initialConditions")
    template = TemplateFile(bmName+".template")
    template.writeToFile(bmName,{'TKE':TKE})

    if funky:    
        # 3: changing U (inserting variables into groovyBC for inlet profile)
        bmName = path.join(work.initialDir(),"U")
        template = TemplateFile(bmName + ".template")
        template.writeToFile(bmName,{'us':us,'z0':z0,'K':k,'Utop':Utop})
        # 4: changing k (inserting variables into groovyBC for inlet profile)
        bmName = path.join(work.initialDir(),"k")
        template = TemplateFile(bmName + ".template")
        template.writeToFile(bmName,{'us':us,'z0':z0,'K':k,'Utop':Utop,'Cmu':Cmu})
        # 5: changing epsilon (inserting variables into groovyBC for inlet profile)
        bmName = path.join(work.initialDir(),"epsilon")
        template = TemplateFile(bmName + ".template")
        template.writeToFile(bmName,{'us':us,'z0':z0,'K':k,'Utop':Utop,'Cmu':Cmu})

    # 6: changing initial and boundary conditions for new z0
    # changing ks in nut, inside nutRoughWallFunction
    nutFile = ParsedParameterFile(path.join(work.initialDir(),"nut"))
    nutFile["boundaryField"]["ground"]["Ks"].setUniform(ks)
    nutFile.writeFile()
    
    # 7: changing convergence criterion for Crude runs
    if caseType == "Crude":    
        fvSolutionFile = ParsedParameterFile(path.join(work.systemDir(),"fvSolution"))
        fvSolutionFile["SIMPLE"]["residualControl"]["p"] = 1e-6
        fvSolutionFile["SIMPLE"]["residualControl"]["U"] = 1e-6
        fvSolutionFile.writeFile()
     
    # mapping fields - From earlier result if exists
    if caseType == "mapFields":
        #finding the most converged run. assuming the "crude" run had the same dirName with "Crude" attached
        setName =  glob.glob(target + 'Crude/sets/*')
        lastRun = range(len(setName))
        for num in range(len(setName)):
            lastRun[num] = int(setName[num][setName[num].rfind("/")+1:])
        sourceTimeArg = str(max(lastRun))
        mapRun = BasicRunner(argv=['mapFields -consistent -sourceTime ' + sourceTimeArg +
             ' -case ' + work.name + ' ' + target + "Crude"],silent=True,server=False,logname='mapLog')
        mapRun.start()

    # parallel rule
    cells = nx * (ny+2*ns)
    print "Mesh has " + str(cells) + " cells"
    if cells>40000: parallel=1
    else: parallel=0

    if parallel:
        #--------------------------------------------------------------------------------------
        # decomposing
        #--------------------------------------------------------------------------------------
        # removing U.template from 0/ directory
        subprocess.call("rm " + bmName + ".template ",shell=True)
        arg = " -case " + work.name
        decomposeRun = BasicRunner(argv=["decomposePar -force" + arg],silent=True,server=False,logname="decompose")
        decomposeRun.start()