Пример #1
0
 def __init__(self):
     BoundingLogAnalyzer.__init__(self)
     self.addAnalyzer("deltaT",
                      SimpleLineAnalyzer("deltaT", "^deltaT = (.+)$"))
     self.addAnalyzer(
         "LiquidPhase",
         SimpleLineAnalyzer(
             "liquid",
             "^Liquid phase volume fraction = (.+) Min\((.+)\) = (.+) Max\(.+\) = (.+)$",
             idNr=2))
    def Optimisationrun(self): #run simpleFoam
        run=ConvergenceRunner(BoundingLogAnalyzer(),argv=[self.solver1,"-case",self.case_path],silent=True)
        run.start()

        subprocess.call(['pyFoamCopyLastToFirst.py',self.case_path, self.case_path])
        subprocess.call(['pyFoamClearCase.py', self.case_path])
        subprocess.call(['rm', self.case_path+'0/cellLevel'])
Пример #3
0
    def run(self):
        cName = self.parser.casePath()
        self.checkCase(cName)

        self.processPlotLineOptions(autoPath=cName)

        sol = SolutionDirectory(cName, archive=None)

        lam = self.getParallel(sol)

        self.clearCase(
            SolutionDirectory(cName, archive=None, parallel=lam is not None))

        self.setLogname()

        self.checkAndCommit(sol)

        run = ConvergenceRunner(BoundingLogAnalyzer(
            progress=self.opts.progress,
            doFiles=self.opts.writeFiles,
            singleFile=self.opts.singleDataFilesOnly,
            doTimelines=True),
                                silent=self.opts.progress or self.opts.silent,
                                argv=self.parser.getArgs(),
                                restart=self.opts.restart,
                                server=self.opts.server,
                                logname=self.opts.logname,
                                compressLog=self.opts.compress,
                                lam=lam,
                                logTail=self.opts.logTail,
                                noLog=self.opts.noLog,
                                remark=self.opts.remark,
                                parameters=self.getRunParameters(),
                                echoCommandLine=self.opts.echoCommandPrefix,
                                jobId=self.opts.jobId)

        run.createPlots(customRegexp=self.lines_,
                        writeFiles=self.opts.writeFiles)

        if self.cursesWindow:
            self.cursesWindow.setAnalyzer(run.analyzer)
            self.cursesWindow.setRunner(run)
            run.analyzer.addTimeListener(self.cursesWindow)

        self.addSafeTrigger(run, sol)
        self.addWriteAllTrigger(run, sol)

        self.addToCaseLog(cName, "Starting")

        run.start()

        self.addToCaseLog(cName, "Ending")

        self.setData(run.data)

        self.reportUsage(run)
        self.reportRunnerData(run)

        return run.data
Пример #4
0
 def run_solver(self):
     run_command = self.solver
     if self.np != 1:
         np_substring = "" if self.hpc else f"-np {self.np} "
         run_command = f"mpiexec {np_substring}{self.solver} -parallel"
     runner = ConvergenceRunner(
         BoundingLogAnalyzer(),
         argv=[run_command, "-case", self.dire.name],
         silent=True,
         logname=self.solver,
     )
     runner.start()
     if not runner.data["OK"]:
         raise RuntimeError("Failed running solver")
Пример #5
0
    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")
Пример #6
0
 def __init__(self):
     BoundingLogAnalyzer.__init__(self)
     self.addAnalyzer("deltaT",SimpleLineAnalyzer("deltaT","^deltaT = (.+)$"))
     self.addAnalyzer("LiquidPhase",SimpleLineAnalyzer("liquid","^Liquid phase volume fraction = (.+) Min\((.+)\) = (.+) Max\(.+\) = (.+)$",idNr=2))
Пример #7
0
    def run(self):
        if self.opts.keeppseudo and (not self.opts.regions
                                     and self.opts.region == None):
            warning(
                "Option --keep-pseudocases only makes sense for multi-region-cases"
            )

        if self.opts.region:
            regionNames = self.opts.region
        else:
            regionNames = [None]

        regions = None

        casePath = self.parser.casePath()
        self.checkCase(casePath)
        #        self.addLocalConfig(casePath)

        self.addToCaseLog(casePath, "Starting")
        self.prepareHooks()

        if self.opts.regions or self.opts.region != None:
            print_("Building Pseudocases")
            sol = SolutionDirectory(casePath, archive=None)
            regions = RegionCases(sol, clean=True)

            if self.opts.regions:
                regionNames = sol.getRegions()

        self.processPlotLineOptions(autoPath=casePath)

        lam = self.getParallel(SolutionDirectory(casePath, archive=None))

        self.clearCase(SolutionDirectory(casePath,
                                         archive=None,
                                         parallel=lam is not None),
                       runParallel=lam is not None)

        self.checkAndCommit(SolutionDirectory(casePath, archive=None))

        self.initBlink()

        for theRegion in regionNames:
            args = self.buildRegionArgv(casePath, theRegion)
            self.setLogname()
            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=self.replaceAutoInArgs(args),
                                 server=self.opts.server,
                                 lam=lam,
                                 restart=self.opts.restart,
                                 logname=self.opts.logname,
                                 compressLog=self.opts.compress,
                                 logTail=self.opts.logTail,
                                 noLog=self.opts.noLog,
                                 remark=self.opts.remark,
                                 parameters=self.getRunParameters(),
                                 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)

            if self.cursesWindow:
                self.cursesWindow.setAnalyzer(run.analyzer)
                self.cursesWindow.setRunner(run)
                run.analyzer.addTimeListener(self.cursesWindow)

            self.addWriteAllTrigger(run,
                                    SolutionDirectory(casePath, archive=None))
            self.addLibFunctionTrigger(
                run, SolutionDirectory(casePath, archive=None))
            self.runPreHooks()

            if self.blink1:
                run.addTicker(lambda: self.blink1.ticToc())

            run.start()

            if len(regionNames) > 1:
                self.setData({theRegion: run.data})
            else:
                self.setData(run.data)

            self.runPostHooks()

            self.reportUsage(run)
            self.reportRunnerData(run)

            if theRegion != None:
                print_("Syncing into master case")
                regions.resync(theRegion)

        self.stopBlink()

        if regions != None:
            if not self.opts.keeppseudo:
                print_("Removing pseudo-regions")
                regions.cleanAll()
            else:
                for r in sol.getRegions():
                    if r not in regionNames:
                        regions.clean(r)

        self.addToCaseLog(casePath, "Ended")
Пример #8
0
 def __init__(self):
     BoundingLogAnalyzer.__init__(self)
     self.addAnalyzer("Compact",CompactLineAnalyzer())
Пример #9
0
 def __init__(self):
     BoundingLogAnalyzer.__init__(self)
     self.addAnalyzer("Compact", CompactLineAnalyzer())
Пример #10
0
    def run(self):
        casePath = self.parser.casePath()
        self.checkCase(casePath)
        #        self.addLocalConfig(casePath)

        self.addToCaseLog(casePath, "Starting")
        self.prepareHooks()

        self.processPlotLineOptions(autoPath=casePath)

        lam = self.getParallel(SolutionDirectory(casePath, archive=None))

        isParallel = lam is not None

        self.lastWrittenTime = None

        sol = SolutionDirectory(casePath, archive=None, parallel=isParallel)
        ctrlDict = ParameterFile(sol.controlDict(), backup=False)
        if ctrlDict.readParameter("startFrom") != "latestTime":
            self.error(
                "In", casePath,
                "the value of 'startFrom' is not 'latestTime' (required for this script)"
            )

        args = self.replaceAutoInArgs(self.parser.getArgs())

        def checkRestart(data=None):
            lastTimeName = sol.getLast()
            lastTime = float(lastTimeName)
            ctrlDict = ParameterFile(sol.controlDict(), backup=False)
            endTime = float(ctrlDict.readParameter("endTime"))
            if abs(endTime - lastTime) / endTime < 1e-5:
                return "Reached endTime {}".format(endTime)
            logfile = calcLogname(self.opts.logname, args)
            isRestart, restartnr, restartName, lastlog = findRestartFiles(
                logfile, sol)
            # TODO: look into the logfile
            if self.lastWrittenTime is not None:
                if self.lastWrittenTime == lastTimeName:
                    return "Last restart didn't improve on {}. Further restarts make no sense".format(
                        lastTime)
            self.lastWrittenTime = lastTimeName
            if data:
                if "stepNr" in data and data["stepNr"] < self.opts.minimumSteps:
                    return "Only {} steps done while {} are required".format(
                        data["stepNr"], self.opts.minimumSteps)

        redo = True

        reason = checkRestart()
        if reason is not None:
            self.warning("Not starting:", reason)
            redo = False

        self.checkAndCommit(sol)

        self.initBlink()

        startNr = 0

        self.setLogname()

        while redo:
            startNr += 1
            print_()
            print_("Starting restart nr", startNr, "on case", casePath)
            print_()
            self.addToCaseLog(casePath, "Restart nr", startNr, "started")
            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=args,
                                 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=self.getRunParameters(),
                                 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)

            if self.cursesWindow:
                self.cursesWindow.setAnalyzer(run.analyzer)
                self.cursesWindow.setRunner(run)
                run.analyzer.addTimeListener(self.cursesWindow)

            self.addWriteAllTrigger(run,
                                    SolutionDirectory(casePath, archive=None))
            self.addLibFunctionTrigger(
                run, SolutionDirectory(casePath, archive=None))
            self.runPreHooks()

            if self.blink1:
                run.addTicker(lambda: self.blink1.ticToc())

            run.start()

            if run.data["keyboardInterrupt"]:
                print_()
                self.warning("Not restarting because of keyboard interrupt")

                redo = False

            self.setData({startNr: run.data})

            self.runPostHooks()

            self.reportUsage(run)
            self.reportRunnerData(run)

            self.addToCaseLog(casePath, "Restart nr", startNr, "ended")

            reason = checkRestart(data=run.data)
            if reason is not None:
                print_()
                self.warning("Not starting:", reason)
                self.addToCaseLog(casePath, "Stopping because of", reason)

                redo = False

            if startNr >= self.opts.maximumRestarts:
                print_()
                self.warning("Maximum number", self.opts.maximumRestarts,
                             "restarts reached")
                self.addToCaseLog(casePath, "Stopping because maximum number",
                                  self.opts.maximumRestarts,
                                  "of restarts reached")
                redo = False

        self.stopBlink()

        self.addToCaseLog(casePath, "Ended")

        print_()
        print_("Ended after", startNr, "restarts")
        print_()
Пример #11
0
    def run(self):
        fName=self.parser.getArgs()[0]

        dom=parse(fName)
        doc=dom.documentElement

        if doc.tagName!='comparator':
            error("Wrong root-element",doc.tagName,"Expected: 'comparator'")

        self.data=ComparatorData(doc)

        purge=False
        if doc.hasAttribute('purge'):
            purge=eval(doc.getAttribute('purge'))
        if self.opts.purge:
            purge=self.opts.purge
        if self.opts.nopurge:
            purge=False

        steady=False
        if doc.hasAttribute('steady'):
            steady=eval(doc.getAttribute('steady'))
        if self.opts.steady:
            purge=self.opts.steady

        print_(" Parameters read OK ")
        print_()

        aLog=open(self.data.id+".overview","w")
        csv=CSVCollection(self.data.id+".csv")

        rDir=self.data.id+".results"
        rmtree(rDir)
        mkdir(rDir)

        calculated=0
        format="%%0%dd" % len(str(len(self.data)))

        for i in range(len(self.data)):
            runID=(format % i)
            print_(runID,end=" ",file=aLog)
            csv["ID"]=runID

            use,para=self.data[i]
            para["template"]=self.data.template
            para["extension"]=self.data.extension
            para["id"]=self.data.id

            if use:
                calculated+=1

            print_("Executing Variation",i+1,"of",len(self.data),end=" ")
            if calculated!=i+1:
                print_("(",calculated,"actually calculated)")
            else:
                print_()

            print_("Parameters:",end=" ")
            for k,v in iteritems(para):
                print_("%s='%s' " % (k,v),end=" ")
                if v.find(" ")>=0 or v.find("\t")>=0:
                    v="'"+v+"'"
                print_(v,end=" ",file=aLog)
                csv[k]=v

            print_()

            if not use:
                print_("Skipping because not all conditions are satisfied")
                csv.clear()
                print_()
                continue

            cName=("%s."+format) % (self.data.id, i)
            log=open(cName+".log","w")

            para["case"]=cName
            print_("Case-directory:",cName)
            para["results"]=path.join(rDir,runID)
            print_("Results directory:",para["results"])
            mkdir(para["results"])

            if path.exists(cName):
                if self.opts.removeOld:
                    print_("   Removing old case-directory")
                    rmtree(cName)
                else:
                    error("Case-directory",cName,"exists")

            print_("   copying template")
            out=copytree(self.data.template,cName)
            print_("---- Copying",file=log)
            for l in out:
                print_(l,end=" ",file=log)

            print_("   preparing")
            ok,erg=self.data.prep.execute(para,log)
            print_(ok,end=" ",file=aLog)
            csv["prepare OK"]=ok

            for i in range(len(erg)):
                print_(erg[i],end=" ",file=aLog)
                csv["Prepare %02d" % i]=erg[i]

            aLog.flush()

            if self.opts.test:
                print_("   Skipping execution")
            else:
                print_("   running the solver")
                sys.stdout.flush()

                if steady:
                    runnerClass=ConvergenceRunner
                else:
                    runnerClass=AnalyzedRunner

                run=runnerClass(BoundingLogAnalyzer(doTimelines=True,progress=True),
                                argv=[self.data.solver,".",cName],
                                silent=True,
                                lam=Command.parallel,
                                server=self.opts.server)

                run.start()
                ok=run.runOK()
                if ok:
                    print_("   executed OK")
                else:
                    print_("   fatal error")

                for aName in run.listAnalyzers():
                    a=run.getAnalyzer(aName)
                    if 'titles' in dir(a):
                        for tit in a.lines.getValueNames():
                            t,v=a.getTimeline(tit)
                            if len(v)>0:
                                para["result_"+aName+"_"+tit]=v[-1]

                print_(run.runOK(),run.lastTime(),run.run.wallTime(),end=" ",file=aLog)
                csv["Run OK"]=run.runOK()
                csv["End Time"]=run.lastTime()
                csv["Wall Time"]=run.run.wallTime()
                csv["Wall Time (Foam)"]=run.totalClockTime()
                csv["CPU Time"]=run.totalCpuTime()
                csv["Wall Time First Step"]=run.firstClockTime()
                csv["CPU Time First Step"]=run.firstCpuTime()

                para["endTime"]=run.lastTime()
                para["runlog"]=run.logFile

                if self.opts.showDict:
                    print_(para)

                print_("   evaluating results")

                ok,erg=self.data.post.execute(para,log)

                if Command.parallel!=None:
                    print_("  Stoping LAM")
                    Command.parallel.stop()
                    Command.parallel=None

                if ok:
                    print_("  Evaluation OK",end=" ")
                else:
                    print_("  Evaluation failed",end=" ")

                if len(erg)>0:
                    print_(":",erg,end=" ")
                print_()

                print_(ok,end=" ",file=aLog)
                for i in range(len(erg)):
                    print_(erg[i],end=" ",file=aLog)
                    csv["Post %02d" % i]=erg[i]

            if purge:
                print_("   removing the case-directory")
                out=rmtree(cName)
                print_("---- Removing",file=log)
                for l in out:
                    print_(l,end=" ",file=log)

            log.close()
            print_()
            print_(file=log)
            aLog.flush()
            csv.write()

        aLog.close()
Пример #12
0
#! /usr/bin/env  python

description = """\
Analyzes a Log written by foamJob.  Needs the name of the Logfile to
be analyzed the data is being written to a directory that has the same
name with _analyzed appended
"""

from PyFoam.Basics.FoamOptionParser import FoamOptionParser

parse = FoamOptionParser(description=description,
                         usage="%prog [options] <logfile>",
                         interspersed=True)

parse.parse(nr=1)

from PyFoam.LogAnalysis.BoundingLogAnalyzer import BoundingLogAnalyzer
from PyFoam.LogAnalysis.LogAnalyzerApplication import LogAnalyzerApplication

analyze = LogAnalyzerApplication(BoundingLogAnalyzer())

analyze.run(pfad=parse.getArgs()[0])
Пример #13
0
    def __init__(self,
                 fname,
                 smallestFreq=0.,
                 persist=None,
                 splitThres=2048,
                 plotLinear=True,
                 plotCont=True,
                 plotBound=True,
                 plotIterations=False,
                 plotCourant=False,
                 plotExecution=False,
                 plotDeltaT=False,
                 hardcopy=False,
                 hardcopyFormat="png",
                 hardcopyPrefix=None,
                 hardcopyTerminalOptions=None,
                 customRegexp=None,
                 writeFiles=False,
                 raiseit=False,
                 progress=False,
                 start=None,
                 end=None,
                 singleFile=False,
                 writePickled=True,
                 plottingImplementation=None,
                 gnuplotTerminal=None,
                 adaptFrequency=True):
        """
        TODO: Docu
        """
        StepAnalyzedCommon.__init__(self,
                                    fname,
                                    BoundingLogAnalyzer(doTimelines=True,
                                                        doFiles=writeFiles,
                                                        progress=progress,
                                                        singleFile=singleFile,
                                                        startTime=start,
                                                        endTime=end),
                                    writePickled=writePickled,
                                    smallestFreq=smallestFreq,
                                    adaptFrequency=adaptFrequency)

        self.startTime = start
        self.endTime = end

        self.plots = {}
        self.createPlots(persist=persist,
                         raiseit=raiseit,
                         start=start,
                         end=end,
                         writeFiles=writeFiles,
                         splitThres=splitThres,
                         plotLinear=plotLinear,
                         plotCont=plotCont,
                         plotBound=plotBound,
                         plotIterations=plotIterations,
                         plotCourant=plotCourant,
                         plotExecution=plotExecution,
                         plotDeltaT=plotDeltaT,
                         customRegexp=customRegexp,
                         gnuplotTerminal=gnuplotTerminal,
                         plottingImplementation=plottingImplementation)

        self.hardcopy = hardcopy
        self.hardcopyFormat = hardcopyFormat
        self.hardcopyPrefix = hardcopyPrefix
        self.hardcopyTerminalOptions = hardcopyTerminalOptions
Пример #14
0
sol = SolutionFile(dire.initialDir(), "U")

maximum = 1.
nr = 10

f = dire.makeFile("InflowVariationResults")

for i in range(nr + 1):
    # Set the boundary condition at the inlet
    val = (maximum * i) / nr
    print "Inlet velocity:", val
    sol.replaceBoundary("inlet", "(%f 0 0)" % (val))

    # Run the solver
    run = ConvergenceRunner(BoundingLogAnalyzer(),
                            argv=[solver, "-case", case],
                            silent=True)
    run.start()

    print "Last Time = ", dire.getLast()

    # Get the pressure difference (Using an external utility)
    pUtil = UtilityRunner(argv=[pCmd, "-case", case],
                          silent=True,
                          logname="Pressure")
    pUtil.add("deltaP", "Pressure at .* Difference .*\] (.+)")
    pUtil.start()

    deltaP = pUtil.get("deltaP")[0]
    y_O2 = (1 - f)*0.2315
    y_N2 = 1-y_O2 -f
    for line in fileinput.input('0/O2',inplace=True):
        print(line.replace('uniform', 'uniform  %s; //' % str(y_O2))),

    for line in fileinput.input('0/N2',inplace=True):
        print(line.replace('uniform', 'uniform  %s; //' % str(y_N2))),

    for line in fileinput.input('0/T',inplace=True):
        print(line.replace('uniform', 'uniform  %s; //' % str(T_start))),

    # replace the
    for line in fileinput.input('system/controlDict',inplace=True):
        print(line.replace('endTime', 'endTime  %s; //' % str(t_end))),

    run=ConvergenceRunner(BoundingLogAnalyzer(),argv=[solver],silent=True)
    print('Starting: ',solver)
    run.start()
    print('Done!\n')

    # remove all the log files
    print('Cleaning up!')
    allFiles = os.listdir('.')

    rmFiles = [f for f in allFiles if f.startswith('PyFoam')]

    for file in rmFiles:
        try:
            os.remove(file)
        except:
            print('Could not remove: ', file)