def run(self): if len(self.parser.getArgs())>2: error("Too many arguments:",self.parser.getArgs()[2:],"can not be used") sName=self.parser.getArgs()[0] dName=self.parser.getArgs()[1] if path.exists(dName): if self.parser.getOptions().force: warning("Replacing",dName,"(--force option)") elif path.exists(path.join(dName,"system","controlDict")): error("Destination",dName,"already existing and a Foam-Case") elif path.isdir(dName): dName=path.join(dName,path.basename(sName)) if path.exists(dName) and not self.parser.getOptions().force: error(dName,"already existing") elif not path.exists(path.dirname(dName)): warning("Directory",path.dirname(dName),"does not exist. Creating") sol=SolutionDirectory(sName, archive=None, paraviewLink=False, addLocalConfig=True, parallel=self.opts.parallel) if sol.determineVCS()!=None and self.opts.vcs: if self.opts.chemkin or self.opts.additional or self.opts.latest: self.error("Using an unimplemented option together with VCS") vcsInter=getVCS(sol.determineVCS(), path=sol.name) vcsInter.clone(dName) return if self.parser.getOptions().chemkin: sol.addToClone("chemkin") if self.parser.getOptions().dopyfoam: sol.addToClone("customRegexp") for a in self.parser.getOptions().additional: sol.addToClone(a) if self.parser.getOptions().latest: sol.addToClone(sol.getLast()) if self.opts.symlinkMode: sol.symlinkCase( dName, followSymlinks=self.parser.getOptions().followSymlinks, maxLevel=self.opts.symlinkLevel, relPath=self.opts.symlinkRelative ) else: sol.cloneCase( dName, followSymlinks=self.parser.getOptions().followSymlinks ) self.addToCaseLog(dName,"Cloned to",dName)
def case_setup(ci): template_case = SolutionDirectory( "template", archive=None, paraviewLink=False) case = template_case.cloneCase( "{0}{1}".format(ci.name, ci.quadrature_order) ) phase_properties = ParsedParameterFile( path.join("./diffs", ci.phase_properties_name)) phase_properties["air"]["PBEDiameterCoeffs"]["QMOMCoeffs"]["quadratureOrder"] = ci.quadrature_order # manually fix bad pyfoam parsing phase_properties["blending"]["default"]["type"] = "none" phase_properties["drag"][1]["swarmCorrection"]["type"] = "none" phase_properties.writeFileAs(path.join( case.name, "constant", "phaseProperties" )) m0 = ParsedParameterFile(path.join(template_case.name, "0", "m0")) for i in range(ci.number_of_moments): m0.header["object"] = "m" + str(i) m0["internalField"].setUniform(ci.initial_moments[i]) m0["dimensions"] = "[0 {0} 0 0 0 0 0]".format(3 * i) m0.writeFileAs(path.join(case.name, "0", "m" + str(i))) controlDict = ParsedParameterFile( path.join(case.name, "system", "controlDict") ) controlDict["functions"]["probes"]["fields"] = [ "m{0}".format(m) for m in range(ci.number_of_moments)] controlDict["endTime"] = ci.end_time controlDict["deltaT"] = ci.delta_t controlDict.writeFile()
def case_setup(ci): template_case = SolutionDirectory("template", archive=None, paraviewLink=False) case = template_case.cloneCase("{0}{1}".format(ci.name, ci.nr_classes)) phase_properties = ParsedParameterFile( path.join("./diffs", ci.phase_properties_name)) phase_properties["air"]["PBEDiameterCoeffs"]["MOCCoeffs"][ "numberOfClasses"] = ci.nr_classes phase_properties["air"]["PBEDiameterCoeffs"]["MOCCoeffs"]["xi1"] = ci.dv # manually fix bad pyfoam parsing phase_properties["blending"]["default"]["type"] = "none" phase_properties["drag"][1]["swarmCorrection"]["type"] = "none" phase_properties.writeFileAs( path.join(case.name, "constant", "phaseProperties")) v = ci.dv + ci.dv * arange(ci.nr_classes) n0 = ParsedParameterFile(path.join(template_case.name, "0", "n0")) for i in range(ci.nr_classes): n0.header["object"] = "n" + str(i) n0["internalField"].setUniform(ci.Ninit(v[i])) n0.writeFileAs(path.join(case.name, "0", "n" + str(i))) controlDict = ParsedParameterFile( path.join(case.name, "system", "controlDict")) controlDict["functions"]["probes"]["fields"] = [ "n{0}".format(n) for n in range(ci.nr_classes) ] controlDict["endTime"] = ci.end_time controlDict["deltaT"] = ci.delta_t controlDict.writeFile()
def reset(self): pid = self.worker_index #os.getpid() # logger_g.info(f'{pid}') self.casename = 'baseCase_'+str(pid) self.csvfile = 'progress_'+str(pid)+'.csv' orig = SolutionDirectory(origcase,archive=None,paraviewLink=False) case = orig.cloneCase(self.casename ) control_dict = ParsedParameterFile(path.join(self.casename,"system", "controlDict")) control_dict["endTime"] = self.end_time control_dict["writeInterval"] = self.write_interval control_dict.writeFile() # remove old log files with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm {self.casename}/log.*', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # remove old solution directories with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm -r {self.casename}/0.* {self.casename}/[1-9]*', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # remove old solution directories with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm -r {self.casename}/VTK', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # remove old solution directories # subprocess.run( # f'rm -r postProcessing', # shell=True, # stderr=subprocess.STDOUT # ) self.count_parameters = 0 if self.states_type == 1: #self.actions[self.count_parameters] = self.a1[0] self.state = np.array([self.a1[0]]) elif self.states_type == 2: self.state = np.hstack((self.a1,self.reward)) return np.array(self.state)
def cloneCase(self, srcPath, dstName): dName = self.parser.getArgs()[1] srcCase = SolutionDirectory(srcPath, archive=None, paraviewLink=False, addLocalConfig=True, parallel=self.opts.parallel) if self.parser.getOptions().symlink: srcCase.symlinkCase(dstName, followSymlinks=True, maxLevel=1, relPath=True) else: srcCase.cloneCase(dstName, followSymlinks=False) print 'Copied to {:s}'.format(os.path.join(dName, dstName))
def run(self): cName = self.parser.getArgs()[0] if self.opts.cloneCase: if self.opts.autoCasename: cName = path.join( cName, path.basename(self.opts.cloneCase) + buildFilenameExtension(self.opts.valuesDicts, self.opts.values)) if path.exists(cName): self.error( cName, "already existing (case should not exist when used with --clone-case)" ) if self.checkCase(self.opts.cloneCase, fatal=self.opts.fatal, verbose=not self.opts.noComplain): self.addLocalConfig(self.opts.cloneCase) orig = SolutionDirectory(self.opts.cloneCase, archive=None, paraviewLink=False) sol = orig.cloneCase(cName) else: if self.checkCase(cName, fatal=self.opts.fatal, verbose=not self.opts.noComplain): self.addLocalConfig(cName) sol = SolutionDirectory(cName, archive=None, paraviewLink=False) try: self.__lastMessage = None self.prepare(sol, cName=cName) except: if self.__lastMessage: self.__writeToStateFile(sol, self.__lastMessage + " failed") raise
def case_setup(ci): template_case = SolutionDirectory( "template", archive=None, paraviewLink=False) case = template_case.cloneCase( "{0}NC{1}".format(ci.name, ci.nr_classes) ) phase_properties = ParsedParameterFile( path.join(template_case.name, "constant", "phaseProperties")) phase_properties["oil"]["PBEDiameterCoeffs"]["MOCCoeffs"]["numberOfClasses"] = ci.nr_classes phase_properties["oil"]["PBEDiameterCoeffs"]["MOCCoeffs"]["xi1"] = ci.dv # manually fix bad pyfoam parsing phase_properties["blending"]["default"]["type"] = "none" phase_properties["drag"][1]["swarmCorrection"]["type"] = "none" phase_properties.writeFileAs(path.join( case.name, "constant", "phaseProperties" )) n0 = ParsedParameterFile(path.join(template_case.name, "0", "n0")) for i in range(ci.nr_classes): n0.header["object"] = "n" + str(i) n0["internalField"].setUniform(ci.Ninit[i]) n0.writeFileAs(path.join(case.name, "0", "n" + str(i))) controlDict = ParsedParameterFile( path.join(case.name, "system", "controlDict") ) controlDict["functions"]["probes"]["fields"] = [ "n{0}".format(n) for n in range(ci.nr_classes)] controlDict.writeFile()
def cloneCase(self, name, svnRemove=True, followSymlinks=False): out = SolutionDirectory.cloneCase(self, name, svnRemove=svnRemove, followSymlinks=followSymlinks) out.inletPatch = self.inletPatch out.updateInletVelocity() return out
def case_setup(ci): template_case = SolutionDirectory( "template", archive=None, paraviewLink=False) case = template_case.cloneCase("{0}".format(ci.name)) stfproperties = ParsedParameterFile(path.join( case.name, "constant", "STFProperties")) stfproperties["apparentMass"] = ci.ma stfproperties["mass"] = ci.m stfproperties.writeFile()
def case_setup(ci): template_case = SolutionDirectory("c01", archive=None, paraviewLink=False) case = template_case.cloneCase("{0}NC{1}".format(ci.name, ci.nr_classes)) phase_properties = ParsedParameterFile( path.join(template_case.name, "constant", "phaseProperties")) a, b, c = "acps", "PBEDiameterCoeffs", "MOCCoeffs" phase_properties[a][b][c]["numberOfClasses"] = ci.nr_classes phase_properties[a][b][c]["xi1"] = ci.dv # manually fix bad pyfoam parsing phase_properties["blending"]["default"]["type"] = "none" phase_properties["drag"][1]["swarmCorrection"]["type"] = "none" phase_properties.writeFileAs( path.join(case.name, "constant", "phaseProperties")) n0 = ParsedParameterFile(path.join(template_case.name, "0", "n0")) for i in range(ci.nr_classes): n0.header["object"] = "n" + str(i) n0["internalField"].setUniform(ci.Ninit[i]) n0.writeFileAs(path.join(case.name, "0", "n" + str(i)))
def create_case(self, wind_dict, params): """ 0. cloning case 1. creating snappyHexMeshDict and blockMeshdict according to flow direction and other parameters 2. creating the blockMesh 3. change the boundary conditions 4. decomposing the domain 5. creating the snappyHexMesh - running in parallel (sfoam.py or not - depending on user input) 6. decomposing the created mesh """ #-------------------------------------------------------------------------------------- # cloning case #-------------------------------------------------------------------------------------- target = params['case_dir'] target = os.path.realpath(target) if not os.path.exists(target): makedirs(target) template = read_dict_string(wind_dict, 'template') self._r.debug("template = %r, target = %r" % (template, target)) orig = SolutionDirectory(template, archive=None, paraviewLink=False) work = orig.cloneCase(target) #-- # creating dictionaries #-- if wind_dict['procnr'] > multiprocessing.cpu_count(): self._r.warn( 'wind_dict contains a higher processor number then the machine has' ) wind_dict['procnr'] = min(wind_dict['procnr'], multiprocessing.cpu_count()) phi = params['wind_dir'] * pi / 180 params['phi'] = phi # - pi/180 * 90 self._r.status('creating block mesh dictionary') self.create_block_mesh_dict(work, wind_dict, params) self._r.status('creating snappy hex mesh dictionary') self.create_SHM_dict(work, wind_dict, params) self._r.status('creating boundary conditions dictionary') self.create_boundary_conditions_dict(work, wind_dict, params) self._r.status('running block mesh') self.run_block_mesh(work) self._r.status('running decompose') self.run_decompose(work, wind_dict) self._r.status('running snappy hex mesh') self.run_SHM(work, wind_dict) self._r.status('running second decompose') self.run_decompose(work, wind_dict) return work
def create_case(self, wind_dict, params): """ 0. cloning case 1. creating snappyHexMeshDict and blockMeshdict according to flow direction and other parameters 2. creating the blockMesh 3. change the boundary conditions 4. decomposing the domain 5. creating the snappyHexMesh - running in parallel (sfoam.py or not - depending on user input) 6. decomposing the created mesh """ #-------------------------------------------------------------------------------------- # cloning case #-------------------------------------------------------------------------------------- target = params['case_dir'] target = os.path.realpath(target) if not os.path.exists(target): makedirs(target) template = read_dict_string(wind_dict, 'template') self._r.debug("template = %r, target = %r" % (template, target)) orig = SolutionDirectory(template, archive=None, paraviewLink=False) work = orig.cloneCase(target) #-- # creating dictionaries #-- if wind_dict['procnr'] > multiprocessing.cpu_count(): self._r.warn('wind_dict contains a higher processor number then the machine has') wind_dict['procnr'] = min(wind_dict['procnr'], multiprocessing.cpu_count()) phi = params['wind_dir'] * pi / 180 params['phi'] = phi # - pi/180 * 90 self._r.status('creating block mesh dictionary') self.create_block_mesh_dict(work, wind_dict, params) self._r.status('creating snappy hex mesh dictionary') self.create_SHM_dict(work, wind_dict, params) self._r.status('creating boundary conditions dictionary') self.create_boundary_conditions_dict(work, wind_dict, params) self._r.status('running block mesh') self.run_block_mesh(work) self._r.status('running decompose') self.run_decompose(work, wind_dict) self._r.status('running snappy hex mesh') self.run_SHM(work, wind_dict) self._r.status('running second decompose') self.run_decompose(work, wind_dict) return work
def create(self, caseName, input_parameters): direTemplate = SolutionDirectory(self.template) for f in self.clone_files: direTemplate.addToClone(f) dire = direTemplate.cloneCase(caseName) parameters = ParsedParameterFile(os.path.join(dire.name, "parameters")) for key, value in input_parameters.items(): parameters[key] = value parameters.writeFile() if self.np > 1: decomposeParDict = ParsedParameterFile( os.path.join(dire.systemDir(), "decomposeParDict")) decomposeParDict["numberOfSubdomains"] = self.np decomposeParDict.writeFile() self.dire = dire
def run(self): cName=self.parser.getArgs()[0] if self.opts.cloneCase: if self.opts.autoCasename: cName=path.join(cName, path.basename(self.opts.cloneCase)+ buildFilenameExtension(self.opts.valuesDicts, self.opts.values)) if path.exists(cName): self.error(cName,"already existing (case should not exist when used with --clone-case)") if self.checkCase(self.opts.cloneCase, fatal=self.opts.fatal, verbose=not self.opts.noComplain): self.addLocalConfig(self.opts.cloneCase) orig=SolutionDirectory(self.opts.cloneCase, archive=None,paraviewLink=False) sol=orig.cloneCase(cName) else: if self.checkCase(cName, fatal=self.opts.fatal, verbose=not self.opts.noComplain): self.addLocalConfig(cName) sol=SolutionDirectory(cName,archive=None,paraviewLink=False) self.prepare(sol,cName=cName)
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 reset(self): pid = self.worker_index #os.getpid() # logger_g.info(f'{pid}') self.casename = 'baseCase_' + str(pid) self.csvfile = 'progress_' + str(pid) + '.csv' orig = SolutionDirectory(origcase, archive=None, paraviewLink=False) case = orig.cloneCase(self.casename) if self.states_type == 1: write_interval = ParsedParameterFile( path.join(self.casename, "system", "controlDict")) write_interval["writeInterval"] = self.update_frequency write_interval.writeFile() elif self.states_type == 2: write_interval = ParsedParameterFile( path.join(self.casename, "system", "controlDict")) write_interval["writeInterval"] = self.update_frequency write_interval.writeFile() # remove old log files with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run(f'rm {self.casename}/log.*', shell=True, stdout=fp, stderr=subprocess.STDOUT) # remove old solution directories with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run(f'rm -r {self.casename}/0.* {self.casename}/[1-9]*', shell=True, stdout=fp, stderr=subprocess.STDOUT) # remove old solution directories with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run(f'rm -r {self.casename}/VTK', shell=True, stdout=fp, stderr=subprocess.STDOUT) # remove old solution directories # subprocess.run( # f'rm -r postProcessing', # shell=True, # stderr=subprocess.STDOUT # ) # set number of steps to 0 and start dynamic update self.number_steps = 0 self.stateFolders = [(i + 1) * self.write_interval - 1 for i in range(self.stateFrequency)] self.vel_square = [] self.itercount_prev = 0 # set up the case with random velicity condition between u = 4 to 8 m/s if self.single_velocity: self.vx = np.array( [self.vx_all[0]] ) #self.np_random.uniform(low=self.vx_low, high=self.vx_high, size=(1,)) #self.vx_all[0] # additional velicities to be added else: self.vx = self.np_random.uniform( low=self.vx_low, high=self.vx_high, size=( 1, )) #self.vx_all[0] # additional velicities to be added velBC = ParsedParameterFile(path.join(self.casename, "0", "U")) velBC["boundaryField"]["inlet"]["value"].setUniform( Vector(self.vx, 0, 0)) velBC.writeFile() # turbulence inlet parameters from experimental study nu = 6.7e-7 intensity = 0.00061 eddy_visc = 0.009 kinetic_energy = ParsedParameterFile(path.join(self.casename, "0", "k")) k = 1.5 * (self.vx[0] * intensity)**2 kinetic_energy["internalField"] = f"uniform {k}" kinetic_energy.writeFile() dissipation = ParsedParameterFile( path.join(self.casename, "0", "omega")) diss = int(k / (nu * eddy_visc)) dissipation["internalField"] = f"uniform {diss}" dissipation.writeFile() # convert solution files to vtk format with open(f'{self.casename}/logr.vtkoutput', 'wb') as fp: subprocess.run( f'$FOAM_APPBIN/foamToVTK {solveroptions} {self.casename}', shell=True, stdout=fp, stderr=subprocess.STDOUT) inlet = vtki.PolyData(f'./{self.casename}/VTK/inlet/inlet_0.vtk') Ub = inlet.cell_arrays['U'] Ub = np.array(Ub) mesh = vtki.UnstructuredGrid( f'./{self.casename}/VTK/{self.casename}_0.vtk') Um = mesh.cell_arrays['U'] Um = np.array(Um) Um = (np.sum(np.square(Um), axis=1)) Ub = (np.sum(np.square(Ub), axis=1)) U2 = np.average(Ub) + np.average(Um) if self.states_type == 1: self.state = np.array([U2]) elif self.states_type == 2: self.state = np.array([U2 for i in range(5)]) logger_m = logging.getLogger(__name__) logging.basicConfig(filename=f'foamstatus_{pid}.log', format='%(asctime)s | %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) # logger_m.info(f'{self.worker_index}') logger_m.info(f'{self.vx[0]} velocity assigned for {pid}') return np.array(self.state)
def run(self): if len(self.parser.getArgs())!=2: error("Need two arguments.",len(self.parser.getArgs()),"found") # get directory names sName=self.parser.getArgs()[0] dName=self.parser.getArgs()[1] # check if the destination directory exists if path.exists(dName): if self.parser.getOptions().force: warning("Replacing",dName,"(--force option)") elif path.exists(path.join(dName,"system","controlDict")): error("Destination",dName,"already existing and a Foam-Case") elif path.isdir(dName): dName=path.join(dName,path.basename(sName)) if path.exists(dName) and not self.parser.getOptions().force: error(dName,"already existing") elif not path.exists(path.dirname(dName)): warning("Directory",path.dirname(dName),"does not exist. Creating") # copy domain and lagrangian.org mkdir(dName) chdir(dName) domainSrc=SolutionDirectory('../%s/%s' % (sName, 'domain'), archive=None, paraviewLink=False, addLocalConfig=True, parallel=self.opts.parallel) if self.parser.getOptions().symlink: domainSrc.symlinkCase( 'domain', followSymlinks=True, maxLevel=1, relPath=True ) else: domainSrc.cloneCase( 'domain', followSymlinks=False ) print 'Copied to %s/%s' % (dName, 'domain.') lagSrc=SolutionDirectory('../%s/%s' % (sName, 'lagrangian.org'), archive=None, paraviewLink=False, addLocalConfig=True, parallel=self.opts.parallel) if self.parser.getOptions().symlink: lagSrc.symlinkCase( 'lagrangian.org', followSymlinks=True, maxLevel=1, relPath=True ) else: lagSrc.cloneCase( 'lagrangian.org', followSymlinks=False ) print 'Copied to %s/%s' % (dName, 'lagrangian.org.') # replace domain.foam by <eulerianCaseName>.foam system('mv domain/domain.foam domain/%s.foam' % dName) # replace list of files by their original if self.parser.getOptions().symlink: replaceFiles = ['domain/system/controlDict', 'domain/system/fvSchemes', 'domain/system/fvSolution', 'domain/system/RBCInletDict', 'domain/constant/polyMesh/blockMeshDict'] for f in replaceFiles: system('pyFoamSymlinkToFile.py %s' % f) system('pyFoamSymlinkToFile.py domain/0/*') # creates list of files to copy or to link to copyFiles = ['config_vars', 'geometricData', 'initialConditions', 'simParams.json', '.gitignore', 'domain/.gitignore', 'lagrangian.org/.gitignore'] symlinkFiles = [] for f in os.listdir('../%s' % sName): if f.endswith('.stl'): symlinkFiles.append(f) optionDependentFiles = \ ['Allrun', 'AllrunRestart', 'cleanCase', 'createMesh', 'makeLinks', 'prepareEulerianCase', 'prepareLagrangianCases', 'removeLinks', 'runCase'] if self.parser.getOptions().symlink: symlinkFiles.extend(optionDependentFiles) else: copyFiles.extend(optionDependentFiles) for f in copyFiles: srcName = os.path.join('..', sName,f) if os.path.isdir(srcName): if os.path.isdir(f): shutil.rmtree(f) try: shutil.copytree(srcName, f) except IOError: print 'Could not copy the directory {}'.format(srcName) else: try: shutil.copy(srcName, f) except IOError: print 'Could not copy the directory {}'.format(srcName) for f in symlinkFiles: system('ln -s ../%s/%s %s' % (sName, f, f))
def reset(self): ''' This function resets the environment. In distributed RL training, the environment will be evaluated simultaneosuly on different processors. Each processor will evaluate multiple episodes (i.e., one episode is a single CFD simulation for this problem) Tis function initilizaes the OpenFoam baseCase corresponding to a specific processor ''' pid = self.worker_index # logger_g.info(f'{pid}') # make a replica of the baseCase using PyFoam self.casename = 'baseCase_' + str(pid) self.csvfile = 'progress_' + str(pid) + '.csv' orig = SolutionDirectory(origcase, archive=None, paraviewLink=False) case = orig.cloneCase(self.casename) # PyFoam library is a library that will allow the user to modify the parameters # of the CFD simulations in a user-friendly manner control_dict = ParsedParameterFile( path.join(self.casename, "system", "controlDict")) control_dict["endTime"] = self.end_time control_dict["writeInterval"] = self.write_interval control_dict.writeFile() # copy the blockMeshDictGenerator.xlsx file from baseCase to baseCase folder corresponding # a specific processor # blockMeshDictGenerator.xlsx file has all formulas that uses and airfoil shape to # generate a mesh around an airfoil # taken from : https://www.phanquocthien.org/mesh-geometry/blockmesh/airfoil with open(f'log.convert', 'a') as fp: subprocess.run( f'cp blockMeshDictGenerator.xlsx ./{self.casename}/blockMeshDictGenerator.xlsx', shell=True, stdout=fp, stderr=subprocess.STDOUT) # the baseCase_{pid} folder will be updated for every episode of the RL as new CFD simulation # will be performed fro each episode. Therefore, this folder will have some solution # from older simulation that needs to be remove at the start of new episode with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run(f'rm {self.casename}/log.*', shell=True, stdout=fp, stderr=subprocess.STDOUT) # remove old solution directories with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run(f'rm -r {self.casename}/0.* {self.casename}/[1-9]*', shell=True, stdout=fp, stderr=subprocess.STDOUT) # remove old solution saved in the VTK format with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run(f'rm -r {self.casename}/VTK', shell=True, stdout=fp, stderr=subprocess.STDOUT) # remove additional directories # subprocess.run( # f'rm -r postProcessing', # shell=True, # stderr=subprocess.STDOUT # ) # assign the state if self.states_type == 1: # inlet velocty as the state of the RL algorithm self.state = np.array([self.vx]) elif self.states_type == 2: # no state None return np.array(self.state)
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile from PyFoam.Basics.DataStructures import Vector from load_surface_data import load_raw_postdata solver = "pisoFoam" base_case = "base" templateCase = SolutionDirectory(base_case, archive=None, paraviewLink=False) omegas = nm.linspace(0, 3, 13) nus = nm.ones(omegas.shape) * 1e-6 for i, eps in enumerate(omegas): case = templateCase.cloneCase("testCase{:02}".format(i)) epsilonBC = ParsedParameterFile(path.join(case.name, "0", "omega")) epsilonBC["boundaryField"]["fixedWalltop_patch1"]["value"].setUniform(eps) epsilonBC["boundaryField"]["fixedWallbot_patch1"]["value"].setUniform(eps) epsilonBC.writeFile() run = BasicRunner(argv=[solver, "-case", case.name], silent=False) # run.start() case = SolutionDirectory(case.name, archive=None, paraviewLink=False) if float(max(case.times)) < .28: case.clear() case.clearResults() trans = ParameterFile(
from load_surface_data import load_raw_postdata solver = "pisoFoam" base_case_name = "base" template_case = SolutionDirectory(base_case_name, archive=None, paraviewLink=False) epsilons = nm.linspace(0, 3, 13) nus = nm.ones(epsilons.shape) * 1e-6 for i, eps in enumerate(epsilons): if i < 2: continue case = template_case.cloneCase("walls/testCase{:02}".format(i)) epsilonBC = ParsedParameterFile(path.join(case.name, "0", "epsilon")) # epsilonBC["boundaryField"]["inletBoundary_patch0"]["value"].setUniform(eps) epsilonBC["boundaryField"]["fixedWalltop_patch1"]["value"].setUniform(eps) epsilonBC["boundaryField"]["fixedWallbot_patch1"]["value"].setUniform(eps) epsilonBC.writeFile() # epsilonBC.closeFile() run = BasicRunner(argv=[solver, "-case", case.name], silent=False) run.start() case = SolutionDirectory(case.name, archive=None, paraviewLink=False) if float(max(case.times)) < .28: case.clear()
#create empty log file logTable = open("results.csv", "w") writer = csv.writer(logTable) writer.writerow(['Ux', 'Uy', 'U', 'angle', 'Cd', 'Cl']) logTable.close() copy_dir = 'openfoamruns' base_case = 'airFoil2D' for mach in machs: for angle in angles: #clone template #copies directories 0, constant, and system clone_name = "/%s/airfoil-u%.1f-a%0.1f" % (path.join( getcwd(), copy_dir), mach, angle) clone = dire.cloneCase(clone_name) Ux = mach * speedOfSound * cos(radians(angle)) Uy = mach * speedOfSound * sin(radians(angle)) #read correct parameter file and change parameter velBC = ParsedParameterFile(path.join(clone_name, "0", "U")) velBC["internalField"].setUniform(Vector(Ux, Uy, 0)) velBC.writeFile() #edit controlDict to account for change in U controlDict = ParsedParameterFile( path.join(clone_name, "system", "controlDict")) controlDict["functions"]["forcesCoeffs"]["liftDir"] = Vector( -sin(radians(angle)), cos(radians(angle)), 0) controlDict["functions"]["forcesCoeffs"]["dragDir"] = Vector(
z0 = 0.03 # [m] ks = 19.58 * z0 # [m] Martinez 2011 Href = 6500 # [m] artinez 2011 us = 0.6110 # [m/s] k = 0.4 Uref = us / k * log(Href / z0) # [m/s] zz = 1111.0 # [m] procnr = 8 orig = SolutionDirectory(template0, archive=None, paraviewLink=False) #-------------------------------------------------------------------------------------- # cloaning case #-------------------------------------------------------------------------------------- print "cloaning case (if stl file is large - this will take a while)" work = orig.cloneCase(target0) #-------------------------------------------------------------------------------------- # 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(
if __name__ == '__main__': # The working directory os.chdir( "/media/timo/sharedParti/cp501/parameterStudies/grid003_parameterStudy_lambdaOb_001" ) # The varibale range of parameter lambdaOb lambdaOb = linspace(0.033, 0.1, 4) print(lambdaOb) # The template case template = SolutionDirectory( os.path.join( "/media/timo/sharedParti/cp501/parameterStudies/2DWedge_grid003_template_002" )) for lambdaObi in lambdaOb: currentCaseName = "2DWedge_grid003_lambdaOb{}".format(lambdaObi) print(currentCaseName) currentCase = template.cloneCase(path.join(getcwd(), currentCaseName)) propertiesFilepath = path.join(currentCase.name, "constant", "viscoelasticProperties") parsedPropertiesFile = ParsedParameterFile(propertiesFilepath) rheologyDict = parsedPropertiesFile["rheology"] print(rheologyDict) lambdaOb_case = rheologyDict.get('lambdaOb') lambdaOb_case[2] = lambdaObi print(lambdaOb_case[2]) parsedPropertiesFile.writeFile()
# ***USER*** liczba wątków procesora/procesorów wykorzystywanych w obliczeniach cpu_number = 2 cases_numbers = [] detachment_point_coordinates = [] # Pętla obliczeń for i in range(1,iter_number+1): print "\nCase " + str(i) print "======" # Utworzenie folderu case'u i-tej serii obliczeń i przekopiowanie do niego folderów "0", "constant" i "system" z case'u obliczanego w poprzedniej serii case_i_dir = case_dir + "_" + str(i) orig=SolutionDirectory(case_prev_dir, archive=None, paraviewLink=False) work=orig.cloneCase(case_i_dir) # Modyfikacja w pliku "turbulenceProperties" wartości wybranych współczynników modelu turbulencji i ich sczytanie turb_coeffs_values_updated = write_read_turbulence_coefficients(i, case_i_dir, turb_coeffs, turb_coeffs_values, delta_turb_coeffs) turb_coeffs_values = turb_coeffs_values_updated # Dekompozycja case'u na potrzeby obliczeń równoległych print "\nDecomposing case" Decomposer(args=["--progress", work.name, cpu_number]) CaseReport(args=["--decomposition", work.name]) machine=LAMMachine(nr=cpu_number) # Obliczenia print "Running calculations\n" theRun=BasicRunner(argv=["simpleFoam", "-case", work.name], silent=True, lam=machine) theRun.start()
dataFrame.drop(0, axis=0, inplace=True) dataFrame.drop(list(range(4, 25, 1)), axis=0, inplace=True) print(dataFrame) #Loading the openFoam template case sol = SolutionDirectory( "/media/timo/linuxSimData/NonNewtonian/cp501/2DWedge_grid003_templates/2DWedge_grid003_template_002" ) #Creating the cases for all parameters for measurePoint in dataFrame.Messpkt: caseName = "cp501_xpp-se_measurement_{}".format(measurePoint) print("Creating case: {}".format(caseName)) #Clone the case and currentCase = sol.cloneCase(os.path.join(wd, caseName)) index = dataFrame.loc[measurePoint] file_U = os.path.join(currentCase.name, "0.0/U") file_viscProperties = os.path.join(currentCase.name, "constant/viscoelasticProperties") parsed_file_U = ParsedParameterFile(file_U) parsed_file_viscProperties = ParsedParameterFile(file_viscProperties) rheologyDict = parsed_file_viscProperties["rheology"] lambdaOb = rheologyDict.get('lambdaOb') lambdaOb[2] = 0.1401 etaP = rheologyDict.get('etaP') etaP[2] = index.Viskosität
def run(self): origPath = self.parser.getArgs()[0] parameterFile = self.parser.getArgs()[1] self.addLocalConfig(origPath) self.checkCase(origPath) nrModes=(1 if self.opts.inplaceExecution else 0) + \ (1 if self.opts.oneClonedCase else 0) + \ (1 if self.opts.listVariations else 0) + \ (1 if self.opts.everyVariantOneCase else 0) if nrModes == 0: self.error( "Specify one of the modes --list-variations, --inplace-execution, --one-cloned-case-execution or --every-variant-one-case-execution" ) elif nrModes > 1: self.error( "The modes --list-variations, --inplace-execution, --one-cloned-case-execution or --every-variant-one-case-execution are mutual exclusive" ) if self.opts.noExecuteSolver: if not self.opts.everyVariantOneCase and self.opts.singleVariation == None and not self.opts.listVariations: self.error( "--no-execute-solver only works with --every-variant-one-case-execution" ) if not self.opts.clonedCasePrefix: self.opts.clonedCasePrefix = path.basename(parameterFile) if not self.opts.clonedCasePostfix: self.opts.clonedCasePostfix = "" else: self.opts.clonedCasePostfix = "." + self.opts.clonedCasePostfix if not self.opts.cloneToDirectory: self.opts.cloneToDirectory = path.dirname(path.abspath(origPath)) if not self.opts.database: self.opts.database = parameterFile + ".database" variationData = ParsedParameterFile( parameterFile, noHeader=True, noVectorOrTensor=True).getValueDict() if not "values" in variationData: self.error("Entry 'values' (dictionary) needed in", parameterFile) if not "solver" in variationData["values"]: self.error("Entry 'solver' (list or string) needed in 'values' in", parameterFile) fixed = {} defaults = {} varied = [] nrVariations = 1 for k in variationData["values"]: v = variationData["values"][k] if type(v) != list: self.error("Entry", k, "is not a list") if len(v) == 1: fixed[k] = v[0] elif len(v) > 1: varied.append((k, v)) nrVariations *= len(v) else: self.warning("Entry", k, "is empty") if "defaults" in variationData: defaults = variationData["defaults"] if len(varied) == 0: self.error("No parameters to vary") self.printPhase(nrVariations, "variations with", len(varied), "parameters") def makeVariations(vList): name, vals = vList[0] if len(vList) > 1: var = makeVariations(vList[1:]) variation = [] for orig in var: for v in vals: d = orig.copy() if isinstance(v, (dict, DictProxy)): d.update(v) else: d[name] = v variation.append(d) return variation else: return [ v if isinstance(v, (dict, DictProxy)) else { name: v } for v in vals ] variations = [dict(defaults, **d) for d in makeVariations(varied)] self["variations"] = variations self["fixed"] = fixed if self.opts.startVariation != None: start = self.opts.startVariation else: start = 0 if self.opts.endVariation != None: end = self.opts.endVariation if end >= len(variations): end = len(variations) - 1 else: end = len(variations) - 1 if self.opts.singleVariation != None: if self.opts.startVariation or self.opts.endVariation: self.error( "--single-variation not possible with --end-variation-number or --start-variation-number" ) if self.opts.singleVariation < 0: self.error("--single-variation must be greater or equal to 0") if self.opts.singleVariation >= len(variations): self.error("Only", len(variations)) start = self.opts.singleVariation end = self.opts.singleVariation if end < start: self.error("Start value", start, "bigger than end value", end) if self.opts.listVariations: self.printPhase("Listing variations") for i in range(start, end + 1): print_("Variation", i, ":", variations[i]) return if not hasDatabase or self.opts.noDatabaseWrite: if path.exists(self.opts.database) and self.opts.createDatabase: self.error("database-file", self.opts.database, "exists already.") elif not path.exists( self.opts.database ) and not self.opts.createDatabase and not self.opts.autoCreateDatabase: self.error("database-file", self.opts.database, "does not exist") createDatabase = self.opts.createDatabase if self.opts.autoCreateDatabase and not path.exists( self.opts.database): createDatabase = True if not hasDatabase or self.opts.noDatabaseWrite: db = None else: db = RunDatabase(self.opts.database, create=createDatabase, verbose=self.opts.verbose) origCase = SolutionDirectory(origPath, archive=None) if self.opts.oneClonedCase: self.printPhase("Cloning work case") workCase = origCase.cloneCase( path.join( self.opts.cloneToDirectory, self.opts.clonedCasePrefix + "_" + path.basename(origPath)) + self.opts.clonedCasePostfix) self.printPhase("Starting actual variations") for i in range(start, end + 1): self.printPhase("Variation", i, "of [", start, ",", end, "]") usedVals = variations[i].copy() usedVals.update(fixed) self.prepareHooks() clone = False if self.opts.inplaceExecution: workCase = origCase elif self.opts.oneClonedCase: pass else: self.printPhase("Cloning work case") workCase = origCase.cloneCase( path.join( self.opts.cloneToDirectory, self.opts.clonedCasePrefix + "_" + ("%05d" % i) + "_" + path.basename(origPath)) + self.opts.clonedCasePostfix) self.processPlotLineOptions(autoPath=workCase.name) self.printPhase("Setting up the case") self.prepare(workCase, overrideParameters=usedVals) if self.opts.noExecuteSolver: self.printPhase("Not executing the solver") continue if self.opts.oneClonedCase or self.opts.inplaceExecution: self.setLogname(self.opts.clonedCasePrefix + ("_%05d_" % i) + usedVals["solver"], useApplication=False, force=True) else: self.setLogname(self.opts.clonedCasePrefix + "_" + usedVals["solver"], useApplication=False, force=True) lam = self.getParallel(workCase) allLines().clear() allPlots().clear() resetCustomCounter() run = AnalyzedRunner( BoundingLogAnalyzer(progress=self.opts.progress, doFiles=self.opts.writeFiles, singleFile=self.opts.singleDataFilesOnly, doTimelines=True), silent=self.opts.progress or self.opts.silent, splitThres=self.opts.splitDataPointsThreshold if self.opts.doSplitDataPoints else None, argv=[usedVals["solver"], "-case", workCase.name], server=self.opts.server, lam=lam, logname=self.opts.logname, compressLog=self.opts.compress, logTail=self.opts.logTail, noLog=self.opts.noLog, remark=self.opts.remark, parameters=usedVals, echoCommandLine=self.opts.echoCommandPrefix, jobId=self.opts.jobId) run.createPlots(customRegexp=self.lines_, splitThres=self.opts.splitDataPointsThreshold if self.opts.doSplitDataPoints else None, writeFiles=self.opts.writeFiles) self.runPreHooks() self.printPhase("Running") run.start() self.printPhase("Getting data") self["run%05d" % i] = run.data if db: db.add(run.data) self.runPostHooks() self.reportUsage(run) self.reportRunnerData(run) self.printPhase("Ending variation")
def run(self): config=ConfigParser.ConfigParser() files=self.parser.getArgs() good=config.read(files) # will work with 2.4 # if len(good)!=len(files): # print "Problem while trying to parse files",files # print "Only ",good," could be parsed" # sys.exit(-1) benchName=config.get("General","name") if self.opts.nameAddition!=None: benchName+="_"+self.opts.nameAddition if self.opts.foamVersion!=None: benchName+="_v"+self.opts.foamVersion isParallel=config.getboolean("General","parallel") lam=None if isParallel: nrCpus=config.getint("General","nProcs") machineFile=config.get("General","machines") if not path.exists(machineFile): self.error("Machine file ",machineFile,"needed for parallel run") lam=LAMMachine(machineFile,nr=nrCpus) if lam.cpuNr()>nrCpus: self.error("Wrong number of CPUs: ",lam.cpuNr()) print "Running parallel on",lam.cpuNr(),"CPUs" if config.has_option("General","casesDirectory"): casesDirectory=path.expanduser(config.get("General","casesDirectory")) else: casesDirectory=foamTutorials() if not path.exists(casesDirectory): self.error("Directory",casesDirectory,"needed with the benchmark cases is missing") else: print "Using cases from directory",casesDirectory benchCases=[] config.remove_section("General") for sec in config.sections(): print "Reading: ",sec skipIt=False skipReason="" if config.has_option(sec,"skip"): skipIt=config.getboolean(sec,"skip") skipReason="Switched off in file" if self.opts.excases!=None and not skipIt: for p in self.opts.excases: if fnmatch(sec,p): skipIt=True skipReason="Switched off by pattern '"+p+"'" if self.opts.cases!=None: for p in self.opts.cases: if fnmatch(sec,p): skipIt=False skipReason="" if skipIt: print "Skipping case ..... Reason:"+skipReason continue sol=config.get(sec,"solver") cas=config.get(sec,"case") pre=eval(config.get(sec,"prepare")) preCon=[] if config.has_option(sec,"preControlDict"): preCon=eval(config.get(sec,"preControlDict")) con=eval(config.get(sec,"controlDict")) bas=config.getfloat(sec,"baseline") wei=config.getfloat(sec,"weight") add=[] if config.has_option(sec,"additional"): add=eval(config.get(sec,"additional")) print "Adding: ", add util=[] if config.has_option(sec,"utilities"): util=eval(config.get(sec,"utilities")) print "Utilities: ", util nr=99999 if config.has_option(sec,"nr"): nr=eval(config.get(sec,"nr")) sp=None if config.has_option(sec,"blockSplit"): sp=eval(config.get(sec,"blockSplit")) toRm=[] if config.has_option(sec,"filesToRemove"): toRm=eval(config.get(sec,"filesToRemove")) setInit=[] if config.has_option(sec,"setInitial"): setInit=eval(config.get(sec,"setInitial")) parallelOK=False if config.has_option(sec,"parallelOK"): parallelOK=config.getboolean(sec,"parallelOK") deMet=["metis"] if config.has_option(sec,"decomposition"): deMet=config.get(sec,"decomposition").split() if deMet[0]=="metis": pass elif deMet[0]=="simple": if len(deMet)<2: deMet.append(0) else: deMet[1]=int(deMet[1]) else: print "Unimplemented decomposition method",deMet[0],"switching to metis" deMet=["metis"] if isParallel==False or parallelOK==True: if path.exists(path.join(casesDirectory,sol,cas)): benchCases.append( (nr,sec,sol,cas,pre,con,preCon,bas,wei,add,util,sp,toRm,setInit,deMet) ) else: print "Skipping",sec,"because directory",path.join(casesDirectory,sol,cas),"could not be found" else: print "Skipping",sec,"because not parallel" benchCases.sort() parallelString="" if isParallel: parallelString=".cpus="+str(nrCpus) resultFile=open("Benchmark."+benchName+"."+uname()[1]+parallelString+".results","w") totalSpeedup=0 minSpeedup=None maxSpeedup=None totalWeight =0 runsOK=0 currentEstimate = 1. print "\nStart Benching\n" csv=CSVCollection("Benchmark."+benchName+"."+uname()[1]+parallelString+".csv") # csvHeaders=["description","solver","case","caseDir","base", # "benchmark","machine","arch","cpus","os","version", # "wallclocktime","cputime","cputimeuser","cputimesystem","maxmemory","cpuusage","speedup"] for nr,description,solver,case,prepare,control,preControl,base,weight,additional,utilities,split,toRemove,setInit,decomposition in benchCases: # control.append( ("endTime",-2000) ) print "Running Benchmark: ",description print "Solver: ",solver print "Case: ",case caseName=solver+"_"+case+"_"+benchName+"."+uname()[1]+".case" print "Short name: ",caseName caseDir=caseName+".runDir" csv["description"]=description csv["solver"]=solver csv["case"]=case csv["caseDir"]=caseDir csv["base"]=base csv["benchmark"]=benchName csv["machine"]=uname()[1] csv["arch"]=uname()[4] if lam==None: csv["cpus"]=1 else: csv["cpus"]=lam.cpuNr() csv["os"]=uname()[0] csv["version"]=uname()[2] workDir=path.realpath(path.curdir) orig=SolutionDirectory(path.join(casesDirectory,solver,case), archive=None, paraviewLink=False) for a in additional+utilities: orig.addToClone(a) orig.cloneCase(path.join(workDir,caseDir)) if oldApp(): argv=[solver,workDir,caseDir] else: argv=[solver,"-case",path.join(workDir,caseDir)] run=BasicRunner(silent=True,argv=argv,logname="BenchRunning",lam=lam) runDir=run.getSolutionDirectory() controlFile=ParameterFile(runDir.controlDict()) for name,value in preControl: print "Setting parameter",name,"to",value,"in controlDict" controlFile.replaceParameter(name,value) for rm in toRemove: fn=path.join(caseDir,rm) print "Removing file",fn remove(fn) for field,bc,val in setInit: print "Setting",field,"on",bc,"to",val SolutionFile(runDir.initialDir(),field).replaceBoundary(bc,val) oldDeltaT=controlFile.replaceParameter("deltaT",0) for u in utilities: print "Building utility ",u execute("wmake 2>&1 >%s %s" % (path.join(caseDir,"BenchCompile."+u),path.join(caseDir,u))) print "Preparing the case: " if lam!=None: prepare=prepare+[("decomposePar","")] if decomposition[0]=="metis": lam.writeMetis(SolutionDirectory(path.join(workDir,caseDir))) elif decomposition[0]=="simple": lam.writeSimple(SolutionDirectory(path.join(workDir,caseDir)),decomposition[1]) if split: print "Splitting the mesh:",split bm=BlockMesh(runDir.blockMesh()) bm.refineMesh(split) for pre,post in prepare: print "Doing ",pre," ...." post=post.replace("%case%",caseDir) if oldApp(): args=string.split("%s %s %s %s" % (pre,workDir,caseDir,post)) else: args=string.split("%s -case %s %s" % (pre,path.join(workDir,caseDir),post)) util=BasicRunner(silent=True,argv=args,logname="BenchPrepare_"+pre) util.start() controlFile.replaceParameter("deltaT",oldDeltaT) # control.append(("endTime",-1000)) for name,value in control: print "Setting parameter",name,"to",value,"in controlDict" controlFile.replaceParameter(name,value) print "Starting at ",asctime(localtime(time())) print " Baseline is %f, estimated speedup %f -> estimated end at %s " % (base,currentEstimate,asctime(localtime(time()+base/currentEstimate))) print "Running the case ...." run.start() speedup=None cpuUsage=0 speedupOut=-1 try: speedup=base/run.run.wallTime() cpuUsage=100.*run.run.cpuTime()/run.run.wallTime() except ZeroDivisionError: print "Division by Zero: ",run.run.wallTime() if not run.runOK(): print "\nWARNING!!!!" print "Run had a problem, not using the results. Check the log\n" speedup=None if speedup!=None: speedupOut=speedup totalSpeedup+=speedup*weight totalWeight +=weight runsOK+=1 if maxSpeedup==None: maxSpeedup=speedup elif speedup>maxSpeedup: maxSpeedup=speedup if minSpeedup==None: minSpeedup=speedup elif speedup<minSpeedup: minSpeedup=speedup print "Wall clock: ",run.run.wallTime() print "Speedup: ",speedup," (Baseline: ",base,")" print "CPU Time: ",run.run.cpuTime() print "CPU Time User: "******"CPU Time System: ",run.run.cpuSystemTime() print "Memory: ",run.run.usedMemory() print "CPU Usage: %6.2f%%" % (cpuUsage) csv["wallclocktime"]=run.run.wallTime() csv["cputime"]=run.run.cpuTime() csv["cputimeuser"]=run.run.cpuUserTime() csv["cputimesystem"]=run.run.cpuSystemTime() csv["maxmemory"]=run.run.usedMemory() csv["cpuusage"]=cpuUsage if speedup!=None: csv["speedup"]=speedup else: csv["speedup"]="##" csv.write() resultFile.write("Case %s WallTime %g CPUTime %g UserTime %g SystemTime %g Memory %g MB Speedup %g\n" %(caseName,run.run.wallTime(),run.run.cpuTime(),run.run.cpuUserTime(),run.run.cpuSystemTime(),run.run.usedMemory(),speedupOut)) resultFile.flush() if speedup!=None: currentEstimate=totalSpeedup/totalWeight if self.opts.removeCases: print "Clearing case", if speedup==None: print "not ... because it failed" else: print "completely" rmtree(caseDir,ignore_errors=True) print print if lam!=None: lam.stop() print "Total Speedup: ",currentEstimate," ( ",totalSpeedup," / ",totalWeight, " ) Range: [",minSpeedup,",",maxSpeedup,"]" print runsOK,"of",len(benchCases),"ran OK" resultFile.write("Total Speedup: %g\n" % (currentEstimate)) if minSpeedup and maxSpeedup: resultFile.write("Range: [ %g , %g ]\n" % (minSpeedup,maxSpeedup)) resultFile.close()
class OpenFoamCase(AbstractCase): def __init__(self, folder): self._folder = folder self._case = SolutionDirectory(folder) self._path = self._case.name self.name = os.path.basename(self._path) self.__dict__.update({ 'set_snappyHexMesh': partial(self.set_dictSettings, 'snappyHexMeshDict'), 'set_fvSchemes': partial(self.set_dictSettings, 'fvSchemes'), 'set_fvSolution': partial(self.set_dictSettings, 'fvSolution'), }) def set_name(self, name): ''' handle the case renaming ''' new_path = os.path.join(os.path.dirname(self._path), name) os.rename(self._path, new_path) self._case = SolutionDirectory(new_path) self._path = new_path self.name = name def run(self): pass def runApp(self, app, args={}, quiet=False): ''' Run an application with the specified arguments ''' quiet_options = { 'silent': True if quiet else False, } cmd = [app, '-case', self._path] cmd += sum([['-{}'.format(k), v] for k, v in args.items()], []) return UtilityRunner(cmd, **quiet_options).start() def clone(self, newName=None): ''' Creates a clone of current case ''' if not newName: newName = self._path + '_clone' cloned_case = self._case.cloneCase(newName) ncase = self.__class__(cloned_case.name) return ncase def set_dictSettings(self, dictName, setting, value): ''' Change a dictionary value ''' f = self.findFile(dictName) if not f: raise OSError('no "{}" found in the case {}'.format( dictName, self.name)) if len(f) > 1: raise OSError('multiple "{}" found!'.format(dictName)) dictFile = OpenFoamDictionary(f[0]) dictFile.set_parameter(setting, value) dictFile.writeFile() def findFile(self, filename): return [ os.path.join(root, filename) for root, dirs, files in os.walk(self._path) if filename in files ]
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile from scipy.stats import gamma class_number = 160 vmax = 1 dv = vmax / class_number m0 = 2 prob = gamma(a=50, scale=1.0e-2) v = dv + dv * arange(class_number) if __name__ == "__main__": template_case = SolutionDirectory( "MOC-template", archive=None, paraviewLink=False) case = template_case.cloneCase( "{0}{1}".format("MOC", class_number) ) n0 = ParsedParameterFile(path.join(template_case.name, "0", "n0")) for i in range(class_number): n0.header["object"] = "n" + str(i) n0["internalField"].setUniform( m0 * (prob.cdf(v[i]) - prob.cdf(v[i] - dv)) ) n0.writeFileAs(path.join(case.name, "0", "n" + str(i))) phase_properties = ParsedParameterFile( path.join(case.name, "constant", "phaseProperties") ) phase_properties["air"]["PBEDiameterCoeffs"]["MOCCoeffs"]["numberOfClasses"] = class_number
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()
# calculating ks according to Martinez 2011 ks = 19.58 * z0 print "ks = "+str(ks) # calculating ABLconditions - Ustar=$US according to logarithmic law k = 0.4 Href = 700 Uref = 17.4 us = (Uref*k)/math.log((Href/z0)); print "us = "+str(us) # 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})
def reset(self): """ Reset the state """ pid = self.worker_index #selecting the environment (can differ in the model and / or the Inlet state) #if the current model converged, then check for the model, else, directly sample the state if self.modelSwitch and self.convFlag == True: #If there's a possibility to make a switch and the current model has #converged then select the new model self.modelSelector() self.stateSelector() reynoldsNumber = self.uinf*1/(8.6834e-6) #nu=8.6834E-6;chord length = 1 #resetting Model (1) - Potential Flow if self.modelID == 1: self.casename_1 = 'baseCase_potential_' + str(pid) if os.path.isdir(self.casename_1): shutil.rmtree(self.casename_1) shutil.copytree(origcase_1, self.casename_1) lines = open("./"+self.casename_1+'/xfoil_input.in').read().splitlines() lines[0] = "LOAD ./"+self.casename_1+"/airfoil_data.dat" lines[4] = "Visc "+str(reynoldsNumber.item()) lines[6] = "./"+self.casename_1+"/polar_file.txt" open("./"+self.casename_1+'/xfoil_input.in', 'w').write('\n'.join(lines)) #resetitng Model (2) - RANS if self.modelID == 2: self.casename = 'baseCase_' + str(pid) self.csvfile = 'progress_' + str(pid) + '.csv' orig = SolutionDirectory(origcase, archive=None, paraviewLink=False) case = orig.cloneCase(self.casename) control_dict = ParsedParameterFile(path.join(self.casename, "system", "controlDict")) control_dict["endTime"] = self.end_time control_dict["writeInterval"] = self.write_interval control_dict.writeFile() shutil.copy('Inputs', self.casename) lines = open("./" + self.casename + '/Inputs').read().splitlines() lines[10] = "UINF "+str(self.uinf.item())+";" open("./" + self.casename + '/Inputs', 'w').write('\n'.join(lines)) #Resetting the log files with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm {self.casename}/log.*', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # remove old solution directories generated during the simulation with open(f'{self.casename}/logr.remove', 'a') as fp: subprocess.run( f'rm -r {self.casename}/0.* {self.casename}/[1-9]*', shell=True, stdout=fp, stderr=subprocess.STDOUT ) # assign the state if self.states_type == 1: # inlet velocty as the state of the RL algorithm self.state = self.uinf elif self.states_type == 2: # no state None return np.array(self.state)
def execute(self,para,log): print_(" Copy last result") sol=SolutionDirectory(para["case"],archive=None) sol.addToClone(sol.getLast()) sol.cloneCase(path.join(para["results"],para["id"])) return True,None
def run(self): origPath=self.parser.getArgs()[0] parameterFile=self.parser.getArgs()[1] self.addLocalConfig(origPath) self.checkCase(origPath) nrModes=(1 if self.opts.inplaceExecution else 0) + \ (1 if self.opts.oneClonedCase else 0) + \ (1 if self.opts.listVariations else 0) + \ (1 if self.opts.everyVariantOneCase else 0) if nrModes==0: self.error("Specify one of the modes --list-variations, --inplace-execution, --one-cloned-case-execution or --every-variant-one-case-execution") elif nrModes>1: self.error("The modes --list-variations, --inplace-execution, --one-cloned-case-execution or --every-variant-one-case-execution are mutual exclusive") if self.opts.noExecuteSolver: if not self.opts.everyVariantOneCase and self.opts.singleVariation==None and not self.opts.listVariations: self.error("--no-execute-solver only works with --every-variant-one-case-execution") if not self.opts.clonedCasePrefix: self.opts.clonedCasePrefix=path.basename(parameterFile) if not self.opts.cloneToDirectory: self.opts.cloneToDirectory=path.dirname(path.abspath(origPath)) if not self.opts.database: self.opts.database=parameterFile+".database" variationData=ParsedParameterFile(parameterFile, noHeader=True, noVectorOrTensor=True) if not "values" in variationData: self.error("Entry 'values' (dictionary) needed in",parameterFile) if not "solver" in variationData["values"]: self.error("Entry 'solver' (list or string) needed in 'values' in",parameterFile) fixed={} varied=[] nrVariations=1 for k in variationData["values"]: v=variationData["values"][k] if type(v)!=list: self.error("Entry",k,"is not a list") if len(v)==1: fixed[k]=v[0] elif len(v)>1: varied.append((k,v)) nrVariations*=len(v) else: self.warning("Entry",k,"is empty") if len(varied)==0: self.error("No parameters to vary") self.printPhase(nrVariations,"variations with",len(varied),"parameters") def makeVariations(vList): name,vals=vList[0] if len(vList)>1: var=makeVariations(vList[1:]) variation=[] for orig in var: for v in vals: d=orig.copy() d[name]=v variation.append(d) return variation else: return [{name:v} for v in vals] variations=makeVariations(varied) self["variations"]=variations self["fixed"]=fixed if self.opts.startVariation!=None: start=self.opts.startVariation else: start=0 if self.opts.endVariation!=None: end=self.opts.endVariation if end>=len(variations): end=len(variations)-1 else: end=len(variations)-1 if self.opts.singleVariation!=None: if self.opts.startVariation or self.opts.endVariation: self.error("--single-variation not possible with --end-variation-number or --start-variation-number") if self.opts.singleVariation<0: self.error("--single-variation must be greater or equal to 0") if self.opts.singleVariation>=len(variations): self.error("Only",len(variations)) start=self.opts.singleVariation end =self.opts.singleVariation if end<start: self.error("Start value",start,"bigger than end value",end) if self.opts.listVariations: self.printPhase("Listing variations") for i in range(start,end+1): print_("Variation",i,":",variations[i]) return if not hasDatabase or self.opts.noDatabaseWrite: if path.exists(self.opts.database) and self.opts.createDatabase: self.error("database-file",self.opts.database,"exists already.") elif not path.exists(self.opts.database) and not self.opts.createDatabase and not self.opts.autoCreateDatabase: self.error("database-file",self.opts.database,"does not exist") createDatabase=self.opts.createDatabase if self.opts.autoCreateDatabase and not path.exists(self.opts.database): createDatabase=True if not hasDatabase or self.opts.noDatabaseWrite: db=None else: db=RunDatabase(self.opts.database, create=createDatabase, verbose=self.opts.verbose) origCase=SolutionDirectory(origPath,archive=None) if self.opts.oneClonedCase: self.printPhase("Cloning work case") workCase=origCase.cloneCase(path.join(self.opts.cloneToDirectory, self.opts.clonedCasePrefix+"_"+path.basename(origPath))) self.printPhase("Starting actual variations") for i in range(start,end+1): self.printPhase("Variation",i,"of [",start,",",end,"]") usedVals=variations[i].copy() usedVals.update(fixed) self.prepareHooks() clone=False if self.opts.inplaceExecution: workCase=origCase elif self.opts.oneClonedCase: pass else: self.printPhase("Cloning work case") workCase=origCase.cloneCase(path.join(self.opts.cloneToDirectory, self.opts.clonedCasePrefix+"_"+ ("%05d" % i)+"_"+path.basename(origPath))) self.processPlotLineOptions(autoPath=workCase.name) self.printPhase("Setting up the case") self.prepare(workCase,overrideParameters=usedVals) if self.opts.noExecuteSolver: self.printPhase("Not executing the solver") continue if self.opts.oneClonedCase or self.opts.inplaceExecution: self.setLogname(self.opts.clonedCasePrefix+("_%05d_"%i)+usedVals["solver"], useApplication=False, force=True) else: self.setLogname(self.opts.clonedCasePrefix+"_"+usedVals["solver"], useApplication=False, force=True) lam=self.getParallel(workCase) allLines().clear() allPlots().clear() resetCustomCounter() run=AnalyzedRunner(BoundingLogAnalyzer(progress=self.opts.progress, doFiles=self.opts.writeFiles, singleFile=self.opts.singleDataFilesOnly, doTimelines=True), silent=self.opts.progress or self.opts.silent, argv=[usedVals["solver"],"-case",workCase.name], server=self.opts.server, lam=lam, logname=self.opts.logname, compressLog=self.opts.compress, logTail=self.opts.logTail, noLog=self.opts.noLog, remark=self.opts.remark, parameters=usedVals, echoCommandLine=self.opts.echoCommandPrefix, jobId=self.opts.jobId) run.createPlots(customRegexp=self.lines_, writeFiles=self.opts.writeFiles) self.runPreHooks() self.printPhase("Running") run.start() self.printPhase("Getting data") self["run%05d" % i]=run.data if db: db.add(run.data) self.runPostHooks() self.reportUsage(run) self.reportRunnerData(run) self.printPhase("Ending variation")
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile from scipy.stats import gamma class_number = 160 vmax = 1 dv = vmax / class_number m0 = 2 prob = gamma(a=50, scale=1.0e-2) v = dv + dv * arange(class_number) if __name__ == "__main__": template_case = SolutionDirectory("MOC-template", archive=None, paraviewLink=False) case = template_case.cloneCase("{0}{1}".format("MOC", class_number)) n0 = ParsedParameterFile(path.join(template_case.name, "0", "n0")) for i in range(class_number): n0.header["object"] = "n" + str(i) n0["internalField"].setUniform(m0 * (prob.cdf(v[i]) - prob.cdf(v[i] - dv))) n0.writeFileAs(path.join(case.name, "0", "n" + str(i))) phase_properties = ParsedParameterFile( path.join(case.name, "constant", "phaseProperties")) phase_properties["air"]["PBEDiameterCoeffs"]["MOCCoeffs"][ "numberOfClasses"] = class_number phase_properties["air"]["PBEDiameterCoeffs"]["MOCCoeffs"]["xi1"] = dv phase_properties["blending"]["default"]["type"] = "none"