Example #1
0
    def __call__(self):
        texts={}
        for n,val in iteritems(self.templates):
            template=TemplateFile(content=val,
                                  expressionDelimiter="|-",
                                  encoding="ascii")
            try:
                texts[n]=str(template.getString(self.runner.getData()))
            except TemplateRenderError:
                e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e'
                error("Template error",e,"while rendering",val)


        msg=Message()
        msg["To"]=self.sendTo
        msg["From"]=self.sentFrom
        msg["Subject"]=texts["subject"]
        for n,v in iteritems(self.mailFields):
            msg[n]=v
        msg.set_payload(texts["message"])

        print_("Connecting to SMTP-server",self.server)

        try:
            s=smtplib.SMTP(self.server)
        except:
            e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e'
            error("Could not connect to",self.server,":",e)

        print_("Sending mail")
        r=s.sendmail(self.sentFrom,self.sendTo.split(","),msg.as_string())
        print_("\n",self.name,"Sent mail to",self.sendTo," Response:",r)

# not yet tested with python3
Example #2
0
    def __call__(self):
        if self.useSSL:
            meth = httplib.HTTPSConnection
        else:
            meth = httplib.HTTPConnection

        conn = meth(self.host)

        parameters = {}
        for n, val in iteritems(self.parameters):
            if n in self.templates:
                template = TemplateFile(content=val,
                                        expressionDelimiter="|-",
                                        encoding="ascii")
                try:
                    parameters[n] = str(
                        template.getString(self.runner.getData()))
                except TemplateRenderError:
                    e = sys.exc_info()[
                        1]  # Needed because python 2.5 does not support 'as e'
                    error("Template error", e, "while rendering", val)
            else:
                parameters[n] = val
        encoded = urllib.urlencode(parameters)
        try:
            conn.request(self.method, self.url, encoded, self.headers)
        except socket.error:
            e = sys.exc_info()[
                1]  # Needed because python 2.5 does not support 'as e'
            error("Could not connect to", self.host, ":", e)

        result = conn.getresponse()
        print_("\n", self.name, "Result of request:", result.status,
               result.reason, result.read())
Example #3
0
 def create_block_mesh_dict(self, work, wind_dict, params):
     phi = params['phi']
     cell_size = params["cell_size"]
     SHM = wind_dict["SHMParams"]
     Href = SHM["domainSize"]["domZ"]
     domainSize = SHM["domainSize"]
     lup, ldown, d = domainSize["fXup"], domainSize["fXdown"], domainSize["fY"]
     x0, y0 = (SHM["centerOfDomain"]["x0"],
             SHM["centerOfDomain"]["y0"])
     sin_phi = sin(phi)
     cos_phi = cos(phi)
     x1 = x0 - (lup * sin_phi + d / 2 * cos_phi)
     y1 = y0 - (lup * cos_phi - d / 2 * sin_phi)
     x2 = x0 - (lup * sin_phi - d / 2 * cos_phi)
     y2 = y0 - (lup * cos_phi + d / 2 * sin_phi)
     x3 = x0 + (ldown * sin_phi + d / 2 * cos_phi)
     y3 = y0 + (ldown * cos_phi - d / 2 * sin_phi)
     x4 = x0 + (ldown * sin_phi - d / 2 * cos_phi)
     y4 = y0 + (ldown * cos_phi + d / 2 * sin_phi)
     n = floor(d / cell_size)
     m = floor((lup+ldown) / cell_size)
     q = floor((Href - domainSize["z_min"]) / cell_size)
     if n == 0 or m == 0 or q == 0:
         self._r.error("invalid input to block mesh dict:\n" +
                       ("d = %(d)f, l = %(l)f, Href = %(Href)f, cell = %(cell)f, cell_size = %(cell_size)f" % locals()) +
                       ("n = %(n)f, m = %(m)f, q = %(q)f" % locals()))
     assert(n > 0 and m > 0 and q > 0)
     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),
         'z_min':domainSize["z_min"]})
Example #4
0
 def testTemplateFileString(self):
     t=TemplateFile(content=template1,expressionDelimiter="$")
     self.assertEqual(t.getString({"x":-1}),"This should be 1")
     fName=mktemp()
     t.writeToFile(fName,{"x":1+2.})
     result=open(fName).read()
     self.assertEqual(result,"This should be 9.0")
 def searchAndReplaceTemplates(self,
                               startDir,
                               values,
                               templateExt):
     """Go through the directory recursively and replate foo.template with
     foo after inserting the values"""
     self.info("Looking for templates with extension",templateExt,"in ",startDir)
     for f,t in self.listdir(startDir,templateExt):
         if f[0]==".":
             self.info("Skipping",f)
             continue
         if path.isdir(path.join(startDir,f)):
             self.searchAndReplaceTemplates(
                 path.join(startDir,f),
                 values,
                 templateExt)
         elif t!=None:
             tName=path.join(startDir,t)
             fName=path.join(startDir,f)
             self.info("Found template for",tName)
             t=TemplateFile(name=fName,
                            tolerantRender=self.opts.tolerantRender,
                            allowExec=self.opts.allowExec,
                            expressionDelimiter=self.opts.expressionDelimiter,
                            assignmentDebug=self.pickAssignmentDebug(fName),
                            assignmentLineStart=self.opts.assignmentLineStart)
             t.writeToFile(tName,values)
             copymode(fName,tName)
Example #6
0
 def searchAndReplaceTemplates(self, startDir, values, templateExt):
     """Go through the directory recursively and replate foo.template with
     foo after inserting the values"""
     if self.opts.verbose:
         print_("Looking for templates with extension", templateExt, "in ",
                startDir)
     for f in listdir(startDir):
         if f[0] == ".":
             if self.opts.verbose:
                 print_("Skipping", f)
             continue
         if path.isdir(path.join(startDir, f)):
             self.searchAndReplaceTemplates(path.join(startDir, f), values,
                                            templateExt)
         elif path.splitext(f)[1] == templateExt:
             fName = path.join(startDir, path.splitext(f)[0])
             if self.opts.verbose:
                 print_("Found template for", fName)
             t = TemplateFile(
                 name=fName + templateExt,
                 tolerantRender=self.opts.tolerantRender,
                 allowExec=self.opts.allowExec,
                 expressionDelimiter=self.opts.expressionDelimiter,
                 assignmentDebug=self.pickAssignmentDebug(fName),
                 assignmentLineStart=self.opts.assignmentLineStart)
             t.writeToFile(fName, values)
             copymode(fName + templateExt, fName)
Example #7
0
 def create_block_mesh_dict(self, work, wind_dict, params):
     phi = params['phi']
     cell_size = params["cell_size"]
     SHM = wind_dict["SHMParams"]
     Href = SHM["domainSize"]["domZ"]
     domainSize = SHM["domainSize"]
     lup, ldown, d = domainSize["fXup"], domainSize["fXdown"], domainSize["fY"]
     x0, y0 = (SHM["centerOfDomain"]["x0"],
             SHM["centerOfDomain"]["y0"])
     sin_phi = sin(phi)
     cos_phi = cos(phi)
     x1 = x0 - (lup * sin_phi + d / 2 * cos_phi)
     y1 = y0 - (lup * cos_phi - d / 2 * sin_phi)
     x2 = x0 - (lup * sin_phi - d / 2 * cos_phi)
     y2 = y0 - (lup * cos_phi + d / 2 * sin_phi)
     x3 = x0 + (ldown * sin_phi + d / 2 * cos_phi)
     y3 = y0 + (ldown * cos_phi - d / 2 * sin_phi)
     x4 = x0 + (ldown * sin_phi - d / 2 * cos_phi)
     y4 = y0 + (ldown * cos_phi + d / 2 * sin_phi)
     n = floor(d / cell_size)
     m = floor((lup+ldown) / cell_size)
     q = floor((Href - domainSize["z_min"]) / cell_size)
     if n == 0 or m == 0 or q == 0:
         self._r.error("invalid input to block mesh dict:\n" +
                       ("d = %(d)f, l = %(l)f, Href = %(Href)f, cell = %(cell)f, cell_size = %(cell_size)f" % locals()) +
                       ("n = %(n)f, m = %(m)f, q = %(q)f" % locals()))
     assert(n > 0 and m > 0 and q > 0)
     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),
         'z_min':domainSize["z_min"]})
Example #8
0
 def testTemplateFileMacro(self):
     t = TemplateFile(content=templateMacro)
     if PY3 and sys.version_info.minor > 1:
         self.assertEqual(
             t.getString({"vals": [2, 3.3, -1]}),
             "2 \t = 4\n3.3 \t = 10.889999999999999\n-1 \t = 1\n")
     else:
         self.assertEqual(t.getString({"vals": [2, 3.3, -1]}),
                          "2 \t = 4\n3.3 \t = 10.89\n-1 \t = 1\n")
Example #9
0
    def run(self):
        fName=self.parser.getArgs()[0]
        vals=eval(self.parser.getArgs()[1])

        if self.opts.template==None:
            template=fName+".template"
        else:
            template=self.opts.template

        t=TemplateFile(name=template)

        if self.opts.test:
            print t.getString(vals)
        else:
            t.writeToFile(fName,vals)
Example #10
0
 def create_boundary_conditions_dict(self, work, wind_dict, params):
     #--------------------------------------------------------------------------------------
     # changing inlet profile - - - - according to Martinez 2010
     #--------------------------------------------------------------------------------------
     phi = params['phi']
     i = params['i']
     SHM = wind_dict['SHMParams']
     kEpsParams = wind_dict['kEpsParams']
     k = kEpsParams['k']  # von karman constant
     z0 = wind_dict["caseTypes"]["windRose"]["windDir"][i][
         2]  # TODO: calculated per wind direction using roughness2foam
     us = wind_dict["caseTypes"]["windRose"]["windDir"][i][4]
     Href = SHM['domainSize']['domZ']
     TKE = us**2 * wind_dict["caseTypes"]["windRose"]["windDir"][i][3]
     Cmu = us / TKE**2
     # change inlet profile
     z_min = wind_dict['SHMParams']['domainSize']['z_min']
     Uref = Utop = us / k * log((Href - z_min) / z0)
     # 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 z0
     # changing z0 in nut, inside nutkAtmRoughWallFunction - for rectanguleDomainSTL = 0 for both terrain and ground patches
     nutFile = ParsedParameterFile(path.join(work.initialDir(), "nut"))
     if SHM["rectanguleDomainSTL"]:
         nutFile["boundaryField"]["ground"]["z0"].setUniform(z0)
         nutFile["boundaryField"]["terrain_.*"]["z0"].setUniform(z0)
     else:
         nutFile["boundaryField"]["ground"]["z0"].setUniform(
             SHM["ground_z0"])
         nutFile["boundaryField"]["terrain_.*"]["z0"].setUniform(
             SHM["terrain_z0"])
     nutFile.writeFile()
     # 3: changing transport properties
     transportFile = ParsedParameterFile(
         path.join(work.constantDir(), 'transportProperties'))
     transportFile['nu'] = "nu [0 2 -1 0 0 0 0] " + str(
         wind_dict['simParams']['nu'])
     transportFile.writeFile()
Example #11
0
 def searchAndReplaceTemplates(self,
                               startDir,
                               values,
                               templateExt,
                               ignoreDirectories=[]):
     """Go through the directory recursively and replate foo.template with
     foo after inserting the values"""
     self.info("Looking for templates with extension", templateExt, "in ",
               startDir)
     for f, t in self.listdir(startDir, templateExt):
         if f[0] == ".":
             self.info("Skipping", f)
             continue
         if path.isdir(path.join(startDir, f)):
             matches = None
             for p in ignoreDirectories:
                 if re.compile(p + "$").match(f):
                     matches = p
                     break
             if matches:
                 self.info("Skipping directory", f, "because it matches",
                           matches)
                 continue
             self.searchAndReplaceTemplates(path.join(startDir, f), values,
                                            templateExt)
         elif t != None:
             tName = path.join(startDir, t)
             fName = path.join(startDir, f)
             self.info("Found template for", tName)
             t = TemplateFile(
                 name=fName,
                 tolerantRender=self.opts.tolerantRender,
                 allowExec=self.opts.allowExec,
                 expressionDelimiter=self.opts.expressionDelimiter,
                 assignmentDebug=self.pickAssignmentDebug(fName),
                 assignmentLineStart=self.opts.assignmentLineStart)
             t.writeToFile(tName, values)
             copymode(fName, tName)
Example #12
0
    def write(self):
        """
        Writes the ``blockMeshDict``
        """
        self.check()

        target = join(self.case.polyMeshDir(),"blockMeshDict")

        template = TemplateFile(content="""
FoamFile
{
	version     2.0;
	format      ascii;
	class       dictionary;
	object      blockMeshDict;
}
convertToMeters    1.0;
vertices
(
);
blocks
(
);

patches
(
);
edges
();
// ************************************************************************* //
""")

        template.writeToFile(target,{})
        template = ParsedBlockMeshDict(
                                        join(
                                            self.case.polyMeshDir(),
                                            'blockMeshDict'
                                            )
                                        )
        # Adopted from
        # http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
        #template['vertices'] = self.getVertices() #[bI for blockI in self.blocks for bI in blockI.vertices]
        template['vertices'] = self.getVertices()

        template['blocks'] = self.getBlocks()

        template['patches'] = self.patchEntries()

        template.writeFile()
Example #13
0
 def create_boundary_conditions_dict(self, work, wind_dict, params):
     #--------------------------------------------------------------------------------------
     # changing inlet profile - - - - according to Martinez 2010
     #--------------------------------------------------------------------------------------
     phi = params['phi']
     i = params['i']
     SHM = wind_dict['SHMParams']
     kEpsParams = wind_dict['kEpsParams']
     k = kEpsParams['k'] # von karman constant
     z0 = wind_dict["caseTypes"]["windRose"]["windDir"][i][2] # TODO: calculated per wind direction using roughness2foam
     us = wind_dict["caseTypes"]["windRose"]["windDir"][i][4] 
     Href = SHM['domainSize']['domZ']
     TKE = us**2 * wind_dict["caseTypes"]["windRose"]["windDir"][i][3]
     Cmu = us / TKE**2
     # change inlet profile
     z_min = wind_dict['SHMParams']['domainSize']['z_min']
     Uref = Utop = us / k * log((Href - z_min) / z0)
     # 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 z0
     # changing z0 in nut, inside nutkAtmRoughWallFunction - for rectanguleDomainSTL = 0 for both terrain and ground patches
     nutFile = ParsedParameterFile(path.join(work.initialDir(), "nut"))
     if SHM["rectanguleDomainSTL"]:
         nutFile["boundaryField"]["ground"]["z0"].setUniform(z0)
         nutFile["boundaryField"]["terrain_.*"]["z0"].setUniform(z0)
     else:
         nutFile["boundaryField"]["ground"]["z0"].setUniform(SHM["ground_z0"])
         nutFile["boundaryField"]["terrain_.*"]["z0"].setUniform(SHM["terrain_z0"])
     nutFile.writeFile()
     # 3: changing transport properties
     transportFile = ParsedParameterFile(path.join(work.constantDir(),'transportProperties'))
     transportFile['nu'] = "nu [0 2 -1 0 0 0 0] " + str(wind_dict['simParams']['nu'])
     transportFile.writeFile()
Example #14
0
 # calculating turbulentKE
 Cmu = 0.03
 TKE = us*us/math.sqrt(Cmu)
 print "TKE = "+str(TKE)
 
 # cloaning case
 work = orig.cloneCase(target)
 
 # 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()
 # 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"
Example #15
0
    def run(self):
        if self.opts.template == "stdin" and self.opts.pickledFileRead == "stdin":
            self.error(
                "Can't simultanously read pickled data and the tempalte from the standard input"
            )

        content = None
        if self.opts.template == "stdin":
            content = sys.stdin.read()
        data = None
        if self.opts.pickledFileRead:
            data = self.readPickledData()
        fName = None

        if len(self.parser.getArgs()) == 2:
            if self.opts.pickledFileRead:
                self.error("old-format mode does not work with pickled input")
            if self.opts.outputFile:
                self.error("--output-file is not valid for the old format")
            # old school implementation
            fName = self.parser.getArgs()[0]
            vals = eval(self.parser.getArgs()[1])
            if type(vals) == str:
                # fix a problem with certain shells
                vals = eval(vals)

            if self.opts.template == None:
                template = fName + ".template"
            else:
                template = self.opts.template

            if content:
                t = TemplateFileOldFormat(content=content)
            else:
                t = TemplateFileOldFormat(name=template)
        elif len(self.parser.getArgs()) == 0:
            if self.opts.template == None and self.opts.outputFile != None and self.opts.outputFile != "stdin":
                self.opts.template = self.opts.outputFile + ".template"
                self.warning("Automatically setting template to",
                             self.opts.template)
            vals = {}
            if self.opts.useDefaults and self.opts.template != None and self.opts.template != "stdin":
                name, ext = path.splitext(self.opts.template)
                defaultName = name + ".defaults"
                if path.exists(defaultName):
                    self.warning("Reading default values from", defaultName)
                    vals = ParsedParameterFile(
                        defaultName, noHeader=True,
                        doMacroExpansion=True).getValueDict()

            vals.update(self.parameters)

            if self.opts.values:
                vals.update(eval(self.opts.values))
            elif self.opts.valuesDict:
                vals.update(
                    ParsedParameterFile(self.opts.valuesDict,
                                        noHeader=True,
                                        doMacroExpansion=True).getValueDict())
            elif data:
                vals.update(data["values"])
            elif len(self.parameters) == 0:
                self.error(
                    "Either specify the values with --values-string or --values-dictionary or in the pickled input data"
                )

            if self.opts.dumpUsed:
                maxLen = max([len(k) for k in vals.keys()])
                formatString = " %%%ds | %%s" % maxLen
                print_("Used values")
                print_(formatString % ("Name", "Value"))
                print_("-" * (maxLen + 30))
                for k, v in iteritems(vals):
                    print_(formatString % (k, v))

            if content:
                t = TemplateFile(
                    content=content,
                    tolerantRender=self.opts.tolerantRender,
                    allowExec=self.opts.allowExec,
                    expressionDelimiter=self.opts.expressionDelimiter,
                    assignmentLineStart=self.opts.assignmentLineStart)
            elif data:
                t = TemplateFile(
                    content=data["template"],
                    tolerantRender=self.opts.tolerantRender,
                    allowExec=self.opts.allowExec,
                    expressionDelimiter=self.opts.expressionDelimiter,
                    assignmentLineStart=self.opts.assignmentLineStart)
            elif self.opts.template:
                t = TemplateFile(
                    name=self.opts.template,
                    tolerantRender=self.opts.tolerantRender,
                    allowExec=self.opts.allowExec,
                    expressionDelimiter=self.opts.expressionDelimiter,
                    assignmentLineStart=self.opts.assignmentLineStart)
            else:
                self.error("Template unspecified")

            if self.opts.outputFile:
                fName = self.opts.outputFile
        else:
            self.error(
                "Either specify 2 arguments (file and values) for old format or no arguments for the new format"
            )

        if self.opts.stdout:
            print_(t.getString(vals))
        elif fName:
            try:
                t.writeToFile(fName, vals)
            except (NameError, SyntaxError):
                e = sys.exc_info()[
                    1]  # Needed because python 2.5 does not support 'as e'
                print_("While processing file", fName)
                raise e
        else:
            self.error("No destination for the output specified")
Example #16
0
 def testTemplateFilePercentDelimiter(self):
     t=TemplateFile(content="x=$!x!$")
     self.assertEqual(t.getString({"x":4}),"x=4")
Example #17
0
 def testTemplateFileLongMath(self):
     t=TemplateFile(content=templateMath,expressionDelimiter="$")
     self.assertEqual(t.getString({"x":4}),"sqrt(x) = 2.0")
Example #18
0
 def testTemplateFileMacro(self):
     t=TemplateFile(content=templateMacro)
     if PY3 and sys.version_info.minor>1:
         self.assertEqual(t.getString({"vals":[2,3.3,-1]}),"2 \t = 4\n3.3 \t = 10.889999999999999\n-1 \t = 1\n")
     else:
         self.assertEqual(t.getString({"vals":[2,3.3,-1]}),"2 \t = 4\n3.3 \t = 10.89\n-1 \t = 1\n")
Example #19
0
 def testTemplateFileLongVars(self):
     t=TemplateFile(content=template2,expressionDelimiter="$")
     self.assertEqual(int(t.getString({"x":1})),36)
 def __call__(self):
     print("Data:", pformat(self.runner.getData()))
     template = TemplateFile(content=self.message,
                             expressionDelimiter="|-",
                             encoding="ascii")
     print(template.getString(self.runner.getData()))
Example #21
0
   energyFluid_In_|name| {
        type swakExpression;
        region |name|;
        expression "h*vol()";
        accumulations ( sum );
        valueType internalField;
        verbose true;
   }
<!--(end)-->
<!--(for name in solids)-->
   energySolid_In_|name| {
        type swakExpression;
        region |name|;
        expression "rho*cp*T*vol()";
        accumulations ( sum );
        valueType internalField;
        verbose true;
   }
<!--(end)-->
}
"""

t = TemplateFile(content=template)

values = {
    'fluids': rInfo["fluidRegionNames"],
    'solids': rInfo["solidRegionNames"]
}

print t.getString(values)
    def testAssignmentNotWorkingInPython3(self):
        t=TemplateFile(content=templateVariablesIn3,
                       expressionDelimiter="|-",
                       allowExec=True)

        self.assertEqual(t.getString({}),"\nB30\nB29_1\nB28_2\n")
Example #23
0
	#--------------------------------------------------------------------------------------
	# 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.)
	print "Hill block: ny = " +str(ny) + " ,Ry = " + str(Ry) 
	nx = int(L/x0-1)
	rx = max(r,1.1)
	ns = int(round(math.log((Ls-L)/x0*(rx-1)+1)/math.log(rx)))    # number of cells in the y direction of the hill block
	Rx = rx**(ns-1)
	print "Side blocks: ns = " +str(ns) + " ,Rx = " + str(Rx) 
	# changing blockMeshDict - from template file
	bmName = path.join(work.constantDir(),"polyMesh/blockMeshDict")
	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
	import writeGroundShape
	sampleName = path.join(work.systemDir(),"sampleDict.template")
	writeGroundShape.main(bmName,H,L,sampleName,hSample)
	# changing Y line limits
	bmName = path.join(work.systemDir(),"sampleDict")
	template = TemplateFile(bmName + ".template")
	template.writeToFile(bmName,{'hillTopY':h,'maxY':500})
	
	# running blockMesh
	blockRun = BasicRunner(argv=["blockMesh",'-case',work.name],silent=True,server=False,logname="blockMesh")
	print "Running blockMesh"
	blockRun.start()
 def __call__(self):
     print("Data:",pformat(self.runner.getData()))
     template=TemplateFile(content=self.message,
                           expressionDelimiter="|-",
                           encoding="ascii")
     print(template.getString(self.runner.getData()))
Example #25
0
    def testAssignmentNotWorkingInPython3(self):
        t = TemplateFile(content=templateVariablesIn3,
                         expressionDelimiter="|-",
                         allowExec=True)

        self.assertEqual(t.getString({}), "\nB30\nB29_1\nB28_2\n")
Example #26
0
 def testTemplateFileFile(self):
     fName=mktemp()
     open(fName,"w").write(template1)
     t=TemplateFile(name=fName,expressionDelimiter="$")
     self.assertEqual(t.getString({"x":-1}),"This should be 1")
Example #27
0
 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.)
 print "Hill block: ny = " + str(ny) + " ,Ry = " + str(Ry)
 nx = int(L / x0 - 1)
 rx = max(r, 1.1)
 ns = int(round(
     math.log((Ls - L) / x0 * (rx - 1) + 1) /
     math.log(rx)))  # number of cells in the y direction of the hill block
 Rx = rx**(ns - 1)
 print "Side blocks: ns = " + str(ns) + " ,Rx = " + str(Rx)
 # changing blockMeshDict - from template file
 bmName = path.join(work.constantDir(), "polyMesh/blockMeshDict")
 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
Example #28
0
 def testTemplateFileForLoop(self):
     t=TemplateFile(content=templateFor)
     self.assertEqual(t.getString({"x":2})," 0  1  2  3 ")
Example #29
0
    # calculating turbulentKE
    Cmu = 0.03
    TKE = us * us / math.sqrt(Cmu)
    print "TKE = " + str(TKE)

    # cloaning case
    work = orig.cloneCase(target)

    # 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()
    # 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()
Example #30
0
 def testTemplateFileListLoop(self):
     t=TemplateFile(content=templateList)
     self.assertEqual(t.getString({"theList":["Henry","Joe","joe","Tom"]}),"Little Henry\nBig Joe\nBig joe\nLittle Tom\n")
Example #31
0
 def testTemplateFileFile(self):
     open("/tmp/writenTemplate","w").write(template1)
     t=TemplateFile(name="/tmp/writenTemplate")
     self.assertEqual(t.getString({"x":-1}),"This should be 1\n")
Example #32
0
 def testTemplateFileMathRealDelim(self):
     t=TemplateFile(content=templateMath.replace("$","|"))
     self.assertEqual(t.getString({"x":4}),"sqrt(x) = 2.0")
Example #33
0
 def testTemplateFileLongVars(self):
     t=TemplateFile(content=template2)
     self.assertEqual(int(t.getString({"x":1})),36)
Example #34
0
 def testTemplateFileBuiltinStuff(self):
     t=TemplateFile(content=templateBuiltIn)
     self.assertEqual(t.getString({}),"\nTRUE\nFALSE\n2 3\n* 32\n")
Example #35
0
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)
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)
    })
Example #36
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
# creating blockMeshDict
#--------------------------------------------------------------------------------------
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)
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 
#--------------------------------------------------------------------------------------
Example #38
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
Example #39
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()
<!--(for name in fluids)-->
   energyFluid_In_|name| {
        type swakExpression;
        region |name|;
        expression "h*vol()";
        accumulations ( sum );
        valueType internalField;
        verbose true;
   }
<!--(end)-->
<!--(for name in solids)-->
   energySolid_In_|name| {
        type swakExpression;
        region |name|;
//        expression "rho*cp*T*vol()";
        expression "rho*T*vol()";
        accumulations ( sum );
        valueType internalField;
        verbose true;
   }
<!--(end)-->
}
"""

t=TemplateFile(content=template)

values = { 'fluids' : rInfo["fluidRegionNames"],
           'solids' : rInfo["solidRegionNames"] }

print t.getString(values)
Example #41
0
 def testTemplateFileString(self):
     t=TemplateFile(content=template1)
     self.assertEqual(t.getString({"x":-1}),"This should be 1\n")
     t.writeToFile("/tmp/testTemplate",{"x":"1+sqrt(4)"})
     result=open("/tmp/testTemplate").read()
     self.assertEqual(result,"This should be 9.0\n")