本文整理汇总了Python中PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory.controlDict方法的典型用法代码示例。如果您正苦于以下问题:Python SolutionDirectory.controlDict方法的具体用法?Python SolutionDirectory.controlDict怎么用?Python SolutionDirectory.controlDict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory
的用法示例。
在下文中一共展示了SolutionDirectory.controlDict方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_with_broyden
# 需要导入模块: from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory [as 别名]
# 或者: from PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory import controlDict [as 别名]
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)
示例2: timeChanged
# 需要导入模块: from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory [as 别名]
# 或者: from PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory import controlDict [as 别名]
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,代码行数:49,代码来源:CursesApplicationWrapper.py
示例3: FoamBaseComponent
# 需要导入模块: from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory [as 别名]
# 或者: from PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory import controlDict [as 别名]
class FoamBaseComponent(Component):
"""This class is base Component to execute OpenFOAM pre,main and post commands"""
case_dir = Str("", iotype="in", desc='OpenFOAM Case Dir. Absolute path or relative path in $FOAM_RUN.')
force_fd = Bool(True, iotype='in', framework_var=True, deriv_ignore=True,
desc="If True, always finite difference this component.")
def __init__(self):
"""Component.__init__() and check the path to icoFoam."""
super(FoamBaseComponent, self).__init__()
self.foam_case = None
#Check OpenFOAM commands in $PATH.
if not self._which("icoFoam"):
self.raise_exception("OpenFOAM command is not found. Check $PATH.", RuntimeError)
if not self.case_dir == '':
caseDir = self.getPath(self.case_dir, False)
if not caseDir == None:
#type(caseDir) is str or unicode
self.foam_case = SolutionDirectory(str(caseDir))
def check_config(self):
if not self.foam_case and self.case_dir == "":
self.raise_exception("Not set self.case_dir.", RuntimeError)
if not os.path.exists(self.foam_case.controlDict()):
self.raise_exception("%s is not found. Check self.case_dir." % (self.foam_case.controlDict()),
RuntimeError)
def _which(self, cmd):
"""which command with python."""
def is_exe(val):
return os.path.isfile(val) and os.access(val, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, cmd)
if is_exe(exe_file):
return exe_file
return None
def getPath(self, fdpath, riseError=True):
"""check and get the absolute path or relative path in $FOAM_RUN."""
if os.path.exists(fdpath):
return fdpath
bool_foam_run = True
foam_run = ""
try:
foam_run = os.environ['FOAM_RUN']
fpath = os.path.join(foam_run, fdpath)
except KeyError:
bool_foam_run = False
if bool_foam_run and os.path.exists(fpath):
return fpath
if riseError:
self.raise_exception(" '%s' was not found." % fdpath, RuntimeError)
return None
def _input_trait_modified(self, obj, name, old, new):
"""hook th changing a trait."""
super(FoamBaseComponent, self)._input_trait_modified(obj, name, old, new)
if name == 'case_dir':
caseDir = self.getPath(new,False)
if not caseDir == None:
#type(caseDir) is str or unicode
self.foam_case = SolutionDirectory(str(caseDir))
else:
self.raise_exception("case_dir '%s' was"
" not found." % new, RuntimeError)
示例4: lookForCases
# 需要导入模块: from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory [as 别名]
# 或者: from PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory import controlDict [as 别名]
def lookForCases(d):
for n in tqdm(listdir(d),
unit="entries",
leave=False,
desc=path.basename(path.abspath(d)),
disable=not self.opts.progressBar):
if not self.fnmatch(n):
continue
cName=path.join(d,n)
if path.isdir(cName):
try:
sol=SolutionDirectory(cName,archive=None,paraviewLink=False)
if sol.isValid():
if self.opts.progress:
print_("Processing",cName)
data={}
data["mtime"]=stat(cName)[ST_MTIME]
times=sol.getTimes()
try:
data["first"]=times[0]
except IndexError:
data["first"]="None"
try:
data["last"]=times[-1]
except IndexError:
data["last"]="None"
data["nrSteps"]=len(times)
data["procs"]=sol.nrProcs()
data["pFirst"]=-1
data["pLast"]=-1
data["nrParallel"]=-1
if self.opts.parallel:
pTimes=sol.getParallelTimes()
data["nrParallel"]=len(pTimes)
if len(pTimes)>0:
data["pFirst"]=pTimes[0]
data["pLast"]=pTimes[-1]
data["name"]=cName
data["diskusage"]=-1
if self.opts.diskusage:
data["diskusage"]=diskUsage(cName)
totalDiskusage+=data["diskusage"]
if self.opts.parallel:
for f in listdir(cName):
if re.compile("processor[0-9]+").match(f):
data["mtime"]=max(stat(path.join(cName,f))[ST_MTIME],data["mtime"])
if self.opts.state or self.opts.estimateEndTime:
try:
data["startedAt"]=time.mktime(time.strptime(self.readState(sol,"StartedAt")))
except ValueError:
data["startedAt"]="nix"
if self.opts.state:
try:
data["nowTime"]=float(self.readState(sol,"CurrentTime"))
except ValueError:
data["nowTime"]=None
try:
data["lastOutput"]=time.mktime(time.strptime(self.readState(sol,"LastOutputSeen")))
except ValueError:
data["lastOutput"]="nix"
data["state"]=self.readState(sol,"TheState")
if data["state"]=="Running":
try:
gone=time.time()-data["lastOutput"]
if gone>self.opts.deadThreshold:
data["state"]="Dead "+humanReadableDuration(gone)
except KeyError:
pass
except TypeError:
pass
if self.opts.startEndTime or self.opts.estimateEndTime:
try:
ctrlDict=ParsedParameterFile(sol.controlDict(),doMacroExpansion=True)
except PyFoamParserError:
# Didn't work with Macro expansion. Let's try without
try:
ctrlDict=ParsedParameterFile(sol.controlDict())
except PyFoamParserError:
ctrlDict=None
if ctrlDict:
data["startTime"]=ctrlDict["startTime"]
data["endTime"]=ctrlDict["endTime"]
else:
data["startTime"]=None
data["endTime"]=None
if self.opts.estimateEndTime:
data["endTimeEstimate"]=None
if self.readState(sol,"TheState")=="Running":
gone=time.time()-data["startedAt"]
try:
current=float(self.readState(sol,"CurrentTime"))
frac=(current-data["startTime"])/(data["endTime"]-data["startTime"])
#.........这里部分代码省略.........
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:103,代码来源:ListCases.py
示例5: run
# 需要导入模块: from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory [as 别名]
# 或者: from PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory import controlDict [as 别名]
def run(self):
dirs=self.parser.getArgs()
if len(dirs)==0:
dirs=[path.curdir]
cData=[]
totalDiskusage=0
useSolverInData=False
self.hasState=False
customData=[]
for i,c in enumerate(self.opts.customData):
lst=c.split("=")
if len(lst)==2:
name,spec=lst
name+="_" # Make sure that there is no collision with standard-names
elif len(lst)==1:
name,spec="Custom%d" % (i+1),c
else:
self.error("Custom specification",c,"does not fit the pattern 'name=subs1::subs2::..'")
customData.append((name,spec.split("::")))
if len(customData)>0 and not self.opts.solverNameForCustom:
self.warning("Parameter '--solver-name-for-custom-data' should be set if '--custom-data' is used")
useSolverInData=True
for d in dirs:
for n in listdir(d):
cName=path.join(d,n)
if path.isdir(cName):
try:
sol=SolutionDirectory(cName,archive=None,paraviewLink=False)
if sol.isValid():
if self.opts.progress:
print_("Processing",cName)
data={}
data["mtime"]=stat(cName)[ST_MTIME]
times=sol.getTimes()
try:
data["first"]=times[0]
except IndexError:
data["first"]="None"
try:
data["last"]=times[-1]
except IndexError:
data["last"]="None"
data["nrSteps"]=len(times)
data["procs"]=sol.nrProcs()
data["pFirst"]=-1
data["pLast"]=-1
data["nrParallel"]=-1
if self.opts.parallel:
pTimes=sol.getParallelTimes()
data["nrParallel"]=len(pTimes)
if len(pTimes)>0:
data["pFirst"]=pTimes[0]
data["pLast"]=pTimes[-1]
data["name"]=cName
data["diskusage"]=-1
if self.opts.diskusage:
data["diskusage"]=diskUsage(cName)
totalDiskusage+=data["diskusage"]
if self.opts.parallel:
for f in listdir(cName):
if re.compile("processor[0-9]+").match(f):
data["mtime"]=max(stat(path.join(cName,f))[ST_MTIME],data["mtime"])
if self.opts.state:
try:
data["nowTime"]=float(self.readState(sol,"CurrentTime"))
except ValueError:
data["nowTime"]=None
try:
data["lastOutput"]=time.mktime(time.strptime(self.readState(sol,"LastOutputSeen")))
except ValueError:
data["lastOutput"]="nix"
data["state"]=self.readState(sol,"TheState")
if self.opts.state or self.opts.estimateEndTime:
try:
data["startedAt"]=time.mktime(time.strptime(self.readState(sol,"StartedAt")))
except ValueError:
data["startedAt"]="nix"
if self.opts.startEndTime or self.opts.estimateEndTime:
try:
ctrlDict=ParsedParameterFile(sol.controlDict(),doMacroExpansion=True)
except PyFoamParserError:
# Didn't work with Macro expansion. Let's try without
try:
ctrlDict=ParsedParameterFile(sol.controlDict())
except PyFoamParserError:
ctrlDict=None
if ctrlDict:
#.........这里部分代码省略.........
示例6: run
# 需要导入模块: from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory [as 别名]
# 或者: from PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory import controlDict [as 别名]
def run(self):
dirs=self.parser.getArgs()
if len(dirs)==0:
dirs=[path.curdir]
cData=[]
totalDiskusage=0
self.hasState=False
for d in dirs:
for n in listdir(d):
cName=path.join(d,n)
if path.isdir(cName):
try:
sol=SolutionDirectory(cName,archive=None,paraviewLink=False)
if sol.isValid():
if self.opts.progress:
print_("Processing",cName)
data={}
data["mtime"]=stat(cName)[ST_MTIME]
times=sol.getTimes()
try:
data["first"]=times[0]
except IndexError:
data["first"]="None"
try:
data["last"]=times[-1]
except IndexError:
data["last"]="None"
data["nrSteps"]=len(times)
data["procs"]=sol.nrProcs()
data["pFirst"]=-1
data["pLast"]=-1
data["nrParallel"]=-1
if self.opts.parallel:
pTimes=sol.getParallelTimes()
data["nrParallel"]=len(pTimes)
if len(pTimes)>0:
data["pFirst"]=pTimes[0]
data["pLast"]=pTimes[-1]
data["name"]=cName
data["diskusage"]=-1
if self.opts.diskusage:
try:
data["diskusage"]=int(
subprocess.Popen(
["du","-sb",cName],
stdout=subprocess.PIPE,
stderr=open(os.devnull,"w")
).communicate()[0].split()[0])
except IndexError:
# assume that this du does not support -b
data["diskusage"]=int(
subprocess.Popen(
["du","-sk",cName],
stdout=subprocess.PIPE
).communicate()[0].split()[0])*1024
totalDiskusage+=data["diskusage"]
if self.opts.parallel:
for f in listdir(cName):
if re.compile("processor[0-9]+").match(f):
data["mtime"]=max(stat(path.join(cName,f))[ST_MTIME],data["mtime"])
if self.opts.state:
try:
data["nowTime"]=float(self.readState(sol,"CurrentTime"))
except ValueError:
data["nowTime"]=None
try:
data["lastOutput"]=time.mktime(time.strptime(self.readState(sol,"LastOutputSeen")))
except ValueError:
data["lastOutput"]="nix"
data["state"]=self.readState(sol,"TheState")
if self.opts.state or self.opts.estimateEndTime:
try:
data["startedAt"]=time.mktime(time.strptime(self.readState(sol,"StartedAt")))
except ValueError:
data["startedAt"]="nix"
if self.opts.startEndTime or self.opts.estimateEndTime:
try:
ctrlDict=ParsedParameterFile(sol.controlDict(),doMacroExpansion=True)
except PyFoamParserError:
# Didn't work with Macro expansion. Let's try without
ctrlDict=ParsedParameterFile(sol.controlDict())
data["startTime"]=ctrlDict["startTime"]
data["endTime"]=ctrlDict["endTime"]
if self.opts.estimateEndTime:
data["endTimeEstimate"]=None
if self.readState(sol,"TheState")=="Running":
#.........这里部分代码省略.........
示例7: test_with_moga
# 需要导入模块: from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory [as 别名]
# 或者: from PyFoam.RunDictionary.SolutionDirectory.SolutionDirectory import controlDict [as 别名]
def test_with_moga(self):
"""
moga test with pyopt_driver.
create meta and optimization with nsga2.
"""
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 U
);
probeLocations
(
( 0.015 0.015 0.005 )
( 0.085 0.015 0.005 )
);
}
}
"""
with open(cavityCase.controlDict(),'a') as fp:
fp.write(fObj)
#test start
sim = set_as_top(MultiObjectiveCavity())
sim.DeformationCavity_meta.model.case_dir = cavityCase.name
sim.DeformationCavity.case_dir = cavityCase.name
try:
sim.NSGA2.optimizer = 'NSGA2'
except ValueError:
raise SkipTest("NSGA2 not present on this system")
sim.NSGA2.options['PrintOut'] = 0
sim.run()