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"]})
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)
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)
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()
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()
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)
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()
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)
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
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
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})
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" Decomposer(args=["--progress",work.name,2])
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")
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()
#-------------------------------------------------------------------------------------- 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 #-------------------------------------------------------------------------------------- # 1: changing ABLConditions
#-------------------------------------------------------------------------------------- # 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() if not blockRun.runOK(): error("there was an error with blockMesh")
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")
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")