本文整理汇总了Python中PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory类的典型用法代码示例。如果您正苦于以下问题:Python SolutionDirectory类的具体用法?Python SolutionDirectory怎么用?Python SolutionDirectory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SolutionDirectory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: case_setup
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()
示例2: case_setup
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()
示例3: run
def run(self):
if not self.opts.keepPostprocessing:
self.opts.additional.append("postProcessing")
for cName in self.parser.getArgs():
if self.checkCase(cName,fatal=self.opts.fatal,verbose=not self.opts.silent):
self.addLocalConfig(cName)
if self.opts.verbose:
print_("Clearing",cName)
sol=SolutionDirectory(cName,archive=None,paraviewLink=False)
sol.clear(after=self.parser.getOptions().after,
processor=self.parser.getOptions().processor,
pyfoam=self.parser.getOptions().pyfoam,
vtk=self.parser.getOptions().vtk,
removeAnalyzed=self.parser.getOptions().removeAnalyzed,
keepRegular=self.parser.getOptions().keepRegular,
keepParallel=self.parser.getOptions().keepParallel,
keepLast=self.parser.getOptions().latest,
keepInterval=self.parser.getOptions().keepInterval,
clearHistory=self.parser.getOptions().clearHistory,
clearParameters=self.parser.getOptions().clearParameters,
additional=self.parser.getOptions().additional,
functionObjectData=self.parser.getOptions().functionObjectData)
self.addToCaseLog(cName)
示例4: __init__
def __init__(self,sol,correctors,tolerance,relTol,pRefValue=None,pRefCell=None):
self.solution=ParsedParameterFile(path.join(sol.systemDir(),"fvSolution"),backup=True)
self.schemes=ParsedParameterFile(path.join(sol.systemDir(),"fvSchemes"),backup=True)
self.control=ParsedParameterFile(path.join(sol.systemDir(),"controlDict"),backup=True)
self.controlOrig=ParsedParameterFile(path.join(sol.systemDir(),"controlDict"),backup=False)
pre=environ["FOAM_TUTORIALS"]
if not oldTutorialStructure():
pre=path.join(pre,"basic")
pot=SolutionDirectory(path.join(pre,"potentialFoam","cylinder"),archive=None,paraviewLink=False)
self.fresh=True
try:
if "SIMPLE" not in self.solution:
self.solution["SIMPLE"]=ParsedParameterFile(path.join(pot.systemDir(),"fvSolution"),backup=False)["SIMPLE"]
if "nNonOrthogonalCorrectors" not in self.solution["SIMPLE"] and correctors==None:
correctors=3
warning("Setting number of correctors to default value",correctors)
if correctors!=None:
self.solution["SIMPLE"]["nNonOrthogonalCorrectors"]=correctors
if pRefCell!=None:
self.solution["SIMPLE"]["pRefCell"]=pRefCell
if pRefValue!=None:
self.solution["SIMPLE"]["pRefValue"]=pRefValue
if tolerance!=None:
try:
self.solution["solvers"]["p"][1]["tolerance"]=tolerance
except KeyError:
# 1.6 format
self.solution["solvers"]["p"]["tolerance"]=tolerance
if relTol!=None:
try:
self.solution["solvers"]["p"][1]["relTol"]=relTol
except KeyError:
# 1.6 format
self.solution["solvers"]["p"]["relTol"]=relTol
self.schemes.content=ParsedParameterFile(path.join(pot.systemDir(),"fvSchemes"),backup=False).content
self.control.content=ParsedParameterFile(path.join(pot.systemDir(),"controlDict"),backup=False).content
if "functions" in self.controlOrig:
print "Copying functions over"
self.control["functions"]=self.controlOrig["functions"]
if "libs" in self.controlOrig:
print "Copying libs over"
self.control["libs"]=self.controlOrig["libs"]
self.solution.writeFile()
self.schemes.writeFile()
self.control.writeFile()
except Exception,e:
warning("Restoring defaults")
self.solution.restore()
self.schemes.restore()
self.control.restore()
raise e
示例5: run
def run(self):
files=self.parser.getArgs()[0:]
if len(files)==1 and path.isdir(files[0]):
sol=SolutionDirectory(
self.parser.getArgs()[0],
archive=None,
parallel=self.opts.parallelTimes,
paraviewLink=False)
self.processTimestepOptions(sol)
if len(self.opts.time)<1:
self.error("No time specified")
globStr=self.parser.getArgs()[0]
if self.opts.parallelTimes:
globStr=path.join(globStr,"processor*")
usedTime=sol.timeName(self.opts.time[0])
globStr=path.join(globStr,
usedTime,
"uniform","profiling*")
files=glob(globStr)
print_("Profiling info from time",usedTime)
if len(files)<1:
self.error("No profiling data found")
elif len(files)>1:
lst=[]
for f in files:
lst.append(self.readProfilingInfo(f))
dataAll,children0,root0=lst[0]
for i in dataAll:
d=dataAll[i]
d["totalTimeMin"]=d["totalTime"]
d["totalTimeMax"]=d["totalTime"]
d["callsMin"]=d["calls"]
d["callsMax"]=d["calls"]
for data,children,root in lst[1:]:
if root0!=root or children!=children0 or data.keys()!=dataAll.keys():
self.error("Inconsistent profiling data. Probably not from same run/timestep")
for i in data:
d=data[i]
s=dataAll[i]
s["totalTime"]+=d["totalTime"]
s["totalTimeMin"]=min(s["totalTimeMin"],d["totalTime"])
s["totalTimeMax"]=max(s["totalTimeMax"],d["totalTime"])
s["calls"]+=d["calls"]
s["callsMin"]=min(s["callsMin"],d["calls"])
s["callsMax"]=max(s["callsMax"],d["calls"])
s["childTime"]+=d["childTime"]
for i in dataAll:
d=dataAll[i]
d["totalTime"]=d["totalTime"]/len(lst)
d["childTime"]=d["childTime"]/len(lst)
d["calls"]=d["calls"]/len(lst)
self.printProfilingInfo(dataAll,children,root,True)
else:
data,children,root=self.readProfilingInfo(files[0])
self.printProfilingInfo(data,children,root)
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:56,代码来源:ListProfilingInfo.py
示例6: additionalReconstruct
def additionalReconstruct(self,parameters):
sol=SolutionDirectory(self.casename())
if len(sol.processorDirs())>0:
for t in listdir(path.join(self.casename(),sol.processorDirs()[0])):
try:
tm=float(t)
self.foamRun("reconstructParMesh",foamArgs=["-time",t])
self.foamRun("reconstructPar",foamArgs=["-time",t])
except ValueError:
print "Skipping",t
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder1.7-libraries-swak4Foam,代码行数:10,代码来源:runSplash.py
示例7: test_with_broyden
def test_with_broyden(self):
"""
broyden test
"""
if not foamVersionNumber() in [(2,3),(2,2)]:
raise unittest.SkipTest("need ver.2.3 or 2.2 for this unittest.")
cavityTut = os.path.join(foamTutorials(),
"incompressible/icoFoam/cavity")
if not os.path.exists(cavityTut):
raise unittest.SkipTest("need $FOAM_TUTORIALS/incompressible/cavity \
for unittest.")
try:
shutil.copytree(cavityTut, os.path.join(self.tmpDir,"cavity"))
cavityCase = SolutionDirectory(os.path.join(self.tmpDir,"cavity"))
except:
raise unittest.SkipTest("can not copy cavity case to temp_dir.")
#create Allrun
with open(os.path.join(cavityCase.name,"Allrun"),'w') as fp:
fp.write('#!/bin/sh\nblockMesh>log.blockMesh\nicoFoam>log.icoFoam\n')
os.chmod(os.path.join(cavityCase.name,"Allrun"),0777)
#append controlDict
fObj="""
functions
{
probes
{
type probes;
functionObjectLibs ("libsampling.so");
enabled true;
outputControl timeStep;
outputInterval 1;
fields
(
p
);
probeLocations
(
( 0.1 0.0925 0.005 )
);
}
}
"""
with open(cavityCase.controlDict(),'a') as fp:
fp.write(fObj)
#test start
sim = set_as_top(BroydenCavityInstance())
sim.cavity.case_dir = cavityCase.name
sim.run()
self.assertEqual(round(sim.cavity.nu,4),0.01)
示例8: case_setup
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()
示例9: run
def run(self):
if self.opts.file:
sys.stdout = open(self.opts.file, "w")
if self.opts.allRegions:
sol = SolutionDirectory(
self.parser.getArgs()[0], archive=None, parallel=self.opts.parallel, paraviewLink=False
)
for r in sol.getRegions():
self.doRegion(r)
else:
self.doRegion(self.opts.region)
示例10: run
def run(self):
if not self.opts.keepPostprocessing:
self.opts.additional.append("postProcessing")
notCleared=[]
if self.opts.dryRun:
self.opts.verbose=True
self.opts.verboseClear=True
for cName in self.parser.getArgs():
if self.checkCase(cName,fatal=self.opts.fatal,verbose=not self.opts.silent):
if self.opts.allcleanScript:
scr=path.join(cName,"Allclean")
if(path.exists(scr)):
if self.opts.verbose or self.opts.verboseClear:
print("Executing",scr)
execute(scr,workdir=cName)
try:
self.addLocalConfig(cName)
if self.opts.verbose:
print_("Clearing",cName)
sol=SolutionDirectory(cName,
archive=None,
parallel=True,
paraviewLink=False)
sol.clear(after=self.parser.getOptions().after,
processor=self.parser.getOptions().processor,
pyfoam=self.parser.getOptions().pyfoam,
vtk=self.parser.getOptions().vtk,
verbose=self.parser.getOptions().verboseClear,
removeAnalyzed=self.parser.getOptions().removeAnalyzed,
keepRegular=self.parser.getOptions().keepRegular,
keepParallel=self.parser.getOptions().keepParallel,
keepLast=self.parser.getOptions().latest,
keepInterval=self.parser.getOptions().keepInterval,
keepTimes=self.opts.keepTimes,
clearHistory=self.parser.getOptions().clearHistory,
clearParameters=self.parser.getOptions().clearParameters,
additional=self.parser.getOptions().additional,
dryRun=self.opts.dryRun,
functionObjectData=self.parser.getOptions().functionObjectData)
self.addToCaseLog(cName)
except OSError:
e = sys.exc_info()[1] # compatible with 2.x and 3.x
self.warning("Can not clear",cName,"because of OSError",e)
notCleared.append(cName)
if len(notCleared)>0:
self.warning("These case not cleared because of OS-problems:",
", ".join(notCleared))
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:53,代码来源:ClearCase.py
示例11: create_case
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
示例12: timeChanged
def timeChanged(self):
self.nSteps+=1
self.currTime=self.analyzer.time
self.progressString=self.analyzer.progressOut.lastProgress()
if self.analyzer.hasAnalyzer("Execution"):
self.clockTime=self.analyzer.getAnalyzer("Execution").clockTotal()
if self.startTime is None:
if self.runner:
self.startTime=self.runner.createTime
else:
self.startTime=self.analyzer.getAnalyzer("Time").createTime()
if self.endTime is None:
sol=None
if self.runner:
sol=self.runner.getSolutionDirectory()
else:
if self.analyzer.hasAnalyzer("ExecName"):
caseName=self.analyzer.getAnalyzer("ExecName").caseName
if caseName and path.isdir(caseName):
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory
sol=SolutionDirectory(caseName,paraviewLink=False)
if sol:
from PyFoam.RunDictionary.ParameterFile import ParameterFile
control=ParameterFile(sol.controlDict())
try:
self.endTime=float(control.readParameter("endTime"))
except ValueError:
self.endTime=-1
if self.caseName is None or self.execName is None:
if self.analyzer.hasAnalyzer("ExecName"):
self.caseName=self.analyzer.getAnalyzer("ExecName").caseName
self.execName=self.analyzer.getAnalyzer("ExecName").execName
self.headerChanged=True
from PyFoam.LogAnalysis.LogLineAnalyzer import LogLineAnalyzer
for e in LogLineAnalyzer.allRegexp:
addExpr(e)
if self.firstTime:
self.update(resize=True)
self.firstTime=False
else:
self._checkHeaders(force=True)
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:47,代码来源:CursesApplicationWrapper.py
示例13: testSolutionDirectoryBasicContainerStuff
def testSolutionDirectoryBasicContainerStuff(self):
test=SolutionDirectory(self.theFile)
self.assertEqual(len(test),1)
self.assert_("0" in test)
self.assert_("1e-7" in test)
self.assert_("1e-4" not in test)
self.assert_(0. in test)
td=test["0"]
self.assertEqual(type(td),TimeDirectory)
self.assertRaises(KeyError,test.__getitem__,"42")
td=test[-1]
self.assertEqual(type(td),TimeDirectory)
lst=[]
for t in test:
lst.append(t.baseName())
self.assertEqual(len(test),len(lst))
self.assertEqual(lst,test.getTimes())
示例14: run
def run(self):
sName=self.parser.getArgs()[0]
if sName[-1]==path.sep:
sName=sName[:-1]
if self.parser.getOptions().tarname!=None:
dName=self.parser.getOptions().tarname
else:
dName=sName+".tgz"
if self.parser.getOptions().pyfoam:
self.parser.getOptions().additional.append("PyFoam*")
sol=SolutionDirectory(sName,archive=None,paraviewLink=False)
if not sol.isValid():
self.error(sName,"does not look like real OpenFOAM-case because",sol.missingFiles(),"are missing or of the wrong type")
if self.parser.getOptions().chemkin:
sol.addToClone("chemkin")
if self.opts.noPloyMesh:
self.parser.getOptions().exclude.append("polyMesh")
sol.packCase(dName,
last=self.parser.getOptions().last,
additional=self.parser.getOptions().additional,
exclude=self.parser.getOptions().exclude,
base=self.parser.getOptions().basename)
示例15: run
def run(self):
for cName in self.parser.getArgs():
if self.checkCase(cName,fatal=self.opts.fatal,verbose=not self.opts.silent):
self.addLocalConfig(cName)
if self.opts.verbose:
print "Clearing",cName
sol=SolutionDirectory(cName,archive=None,paraviewLink=False)
sol.clear(after=self.parser.getOptions().after,
processor=self.parser.getOptions().processor,
pyfoam=self.parser.getOptions().pyfoam,
vtk=self.parser.getOptions().vtk,
keepRegular=self.parser.getOptions().keepRegular,
keepLast=self.parser.getOptions().latest,
clearHistory=self.parser.getOptions().clearHistory,
functionObjectData=self.parser.getOptions().functionObjectData)
self.addToCaseLog(cName)