Example #1
0
    def run(self):
        decomposeParWithRegion=(foamVersion()>=(1,6))

        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 decomposeParWithRegion and self.opts.keeppseudo:
            warning("Option --keep-pseudocases doesn't make sense since OpenFOAM 1.6 because decomposePar supports regions")

        nr=int(self.parser.getArgs()[1])
        if nr<2:
            error("Number of processors",nr,"too small (at least 2)")

        case=path.abspath(self.parser.getArgs()[0])
        method=self.opts.method

        result={}
        result["numberOfSubdomains"]=nr
        result["method"]=method

        coeff={}
        result[method+"Coeffs"]=coeff

        if self.opts.globalFaceZones!=None:
            try:
                fZones=eval(self.opts.globalFaceZones)
            except SyntaxError:
                fZones=FoamStringParser(
                    self.opts.globalFaceZones,
                    listDict=True
                ).data

            result["globalFaceZones"]=fZones

        if method in ["metis","scotch","parMetis"]:
            if self.opts.processorWeights!=None:
                weigh=eval(self.opts.processorWeights)
                if nr!=len(weigh):
                    error("Number of processors",nr,"and length of",weigh,"differ")
                coeff["processorWeights"]=weigh
        elif method=="manual":
            if self.opts.dataFile==None:
                error("Missing required option dataFile")
            else:
                coeff["dataFile"]="\""+self.opts.dataFile+"\""
        elif method=="simple" or method=="hierarchical":
            if self.opts.n==None or self.opts.delta==None:
                error("Missing required option n or delta")
            n=eval(self.opts.n)
            if len(n)!=3:
                error("Needs to be three elements, not",n)
            if nr!=n[0]*n[1]*n[2]:
                error("Subdomains",n,"inconsistent with processor number",nr)
            coeff["n"]="(%d %d %d)" % (n[0],n[1],n[2])

            coeff["delta"]=float(self.opts.delta)
            if method=="hierarchical":
                if self.opts.order==None:
                    error("Missing reuired option order")
                if len(self.opts.order)!=3:
                    error("Order needs to be three characters")
                coeff["order"]=self.opts.order
        else:
            error("Method",method,"not yet implementes")

        gen=FoamFileGenerator(result)

        if self.opts.test:
            print_(str(gen))
            return -1
        else:
            f=open(path.join(case,"system","decomposeParDict"),"w")
            writeDictionaryHeader(f)
            f.write(str(gen))
            f.close()

        if self.opts.clear:
            print_("Clearing processors")
            for p in glob(path.join(case,"processor*")):
                print_("Removing",p)
                rmtree(p,ignore_errors=True)

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

        if self.opts.doDecompose:
            if self.opts.region:
                regionNames=self.opts.region[:]
                while True:
                    try:
                        i=regionNames.index("region0")
                        regionNames[i]=None
                    except ValueError:
                        break
            else:
                regionNames=[None]

            regions=None

            sol=SolutionDirectory(case)
            if not decomposeParWithRegion:
                if self.opts.regions or self.opts.region!=None:
                    print_("Building Pseudocases")
                    regions=RegionCases(sol,clean=True,processorDirs=False)

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

            for theRegion in regionNames:
                theCase=path.normpath(case)
                if theRegion!=None and not decomposeParWithRegion:
                    theCase+="."+theRegion

                if oldApp():
                    argv=[self.opts.decomposer,".",theCase]
                else:
                    argv=[self.opts.decomposer,"-case",theCase]
                    if foamVersion()>=(2,0) and not self.opts.doFunctionObjects:
                        argv+=["-noFunctionObjects"]
                    if theRegion!=None and decomposeParWithRegion:
                        argv+=["-region",theRegion]

                        f=open(path.join(case,"system",theRegion,"decomposeParDict"),"w")
                        writeDictionaryHeader(f)
                        f.write(str(gen))
                        f.close()

                self.setLogname(default="Decomposer",useApplication=False)

                run=UtilityRunner(argv=argv,
                                  silent=self.opts.progress or self.opts.silent,
                                  logname=self.opts.logname,
                                  compressLog=self.opts.compress,
                                  server=self.opts.server,
                                  noLog=self.opts.noLog,
                                  logTail=self.opts.logTail,
                                  echoCommandLine=self.opts.echoCommandPrefix,
                                  jobId=self.opts.jobId)
                run.start()

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

            if regions!=None and not decomposeParWithRegion:
                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)

            if self.opts.doConstantLinks:
                print_("Adding symlinks in the constant directories")
                constPath=path.join(case,"constant")
                for f in listdir(constPath):
                    srcExpr=path.join(path.pardir,path.pardir,"constant",f)
                    for p in range(nr):
                        dest=path.join(case,"processor%d"%p,"constant",f)
                        if not path.exists(dest):
                            symlink(srcExpr,dest)

            self.addToCaseLog(case)
Example #2
0
    def run(self):
        decomposeParWithRegion = (foamVersion() >= (1, 6))

        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 decomposeParWithRegion and self.opts.keeppseudo:
            warning(
                "Option --keep-pseudocases doesn't make sense since OpenFOAM 1.6 because decomposePar supports regions"
            )

        nr = int(self.parser.getArgs()[1])
        if nr < 2:
            error("Number of processors", nr, "too small (at least 2)")

        case = path.abspath(self.parser.getArgs()[0])
        method = self.opts.method

        result = {}
        result["numberOfSubdomains"] = nr
        result["method"] = method

        coeff = {}
        result[method + "Coeffs"] = coeff

        if self.opts.globalFaceZones != None:
            try:
                fZones = eval(self.opts.globalFaceZones)
            except SyntaxError:
                fZones = FoamStringParser(self.opts.globalFaceZones,
                                          listDict=True).data

            result["globalFaceZones"] = fZones

        if method in ["metis", "scotch", "parMetis"]:
            if self.opts.processorWeights != None:
                weigh = eval(self.opts.processorWeights)
                if nr != len(weigh):
                    error("Number of processors", nr, "and length of", weigh,
                          "differ")
                coeff["processorWeights"] = weigh
        elif method == "manual":
            if self.opts.dataFile == None:
                error("Missing required option dataFile")
            else:
                coeff["dataFile"] = "\"" + self.opts.dataFile + "\""
        elif method == "simple" or method == "hierarchical":
            if self.opts.n == None or self.opts.delta == None:
                error("Missing required option n or delta")
            n = eval(self.opts.n)
            if len(n) != 3:
                error("Needs to be three elements, not", n)
            if nr != n[0] * n[1] * n[2]:
                error("Subdomains", n, "inconsistent with processor number",
                      nr)
            coeff["n"] = "(%d %d %d)" % (n[0], n[1], n[2])

            coeff["delta"] = float(self.opts.delta)
            if method == "hierarchical":
                if self.opts.order == None:
                    error("Missing reuired option order")
                if len(self.opts.order) != 3:
                    error("Order needs to be three characters")
                coeff["order"] = self.opts.order
        else:
            error("Method", method, "not yet implementes")

        gen = FoamFileGenerator(result)

        if self.opts.test:
            print_(str(gen))
            return -1
        else:
            f = open(path.join(case, "system", "decomposeParDict"), "w")
            writeDictionaryHeader(f)
            f.write(str(gen))
            f.close()

        if self.opts.clear:
            print_("Clearing processors")
            for p in glob(path.join(case, "processor*")):
                print_("Removing", p)
                rmtree(p, ignore_errors=True)
Example #3
0
    def addOptions(self):
        if foamVersion() >= (1, 6):
            self.defaultMethod = "scotch"
            self.decomposeChoices += [self.defaultMethod]
            self.decomposeChoices += ["parMetis"]

        spec = OptionGroup(self.parser, "Decomposition Specification",
                           "How the case should be decomposed")
        spec.add_option("--method",
                        type="choice",
                        default=self.defaultMethod,
                        dest="method",
                        action="store",
                        choices=self.decomposeChoices,
                        help="The method used for decomposing (Choices: " +
                        string.join(self.decomposeChoices, ", ") +
                        ") Default: %default")

        spec.add_option(
            "--n",
            dest="n",
            action="store",
            default=None,
            help=
            "Number of subdivisions in coordinate directions. A python list or tuple (for simple and hierarchical)"
        )

        spec.add_option("--delta",
                        dest="delta",
                        action="store",
                        type="float",
                        default=None,
                        help="Cell skew factor (for simple and hierarchical)")

        spec.add_option("--order",
                        dest="order",
                        action="store",
                        default=None,
                        help="Order of decomposition (for hierarchical)")

        spec.add_option(
            "--processorWeights",
            dest="processorWeights",
            action="store",
            default=None,
            help=
            "The weights of the processors. A python list. Used for metis, scotch and parMetis"
        )

        spec.add_option(
            "--globalFaceZones",
            dest="globalFaceZones",
            action="store",
            default=None,
            help=
            """Global face zones. A string with a python list or an OpenFOAM-list of words. Used for the GGI interface. Ex: '["GGI_Z1","GGI_Z2"]' or '(GGI_Z1 GGI_Z2)'"""
        )

        spec.add_option("--dataFile",
                        dest="dataFile",
                        action="store",
                        default=None,
                        help="File with the allocations. (for manual)")
        self.parser.add_option_group(spec)

        behave = OptionGroup(
            self.parser, "Decomposition behaviour",
            "How the program should behave during decomposition")
        behave.add_option("--test",
                          dest="test",
                          action="store_true",
                          default=False,
                          help="Just print the resulting dictionary")

        behave.add_option(
            "--clear",
            dest="clear",
            action="store_true",
            default=False,
            help="Clear the case of previous processor directories")

        behave.add_option(
            "--no-decompose",
            dest="doDecompose",
            action="store_false",
            default=True,
            help="Don't run the decomposer (only writes the dictionary")

        behave.add_option(
            "--do-function-objects",
            dest="doFunctionObjects",
            action="store_true",
            default=False,
            help=
            "Allow the execution of function objects (default behaviour is switching them off)"
        )

        behave.add_option("--decomposer",
                          dest="decomposer",
                          action="store",
                          default="decomposePar",
                          help="The decompose Utility that should be used")
        self.parser.add_option_group(behave)

        work = OptionGroup(
            self.parser, "Additional work",
            "What else should be done in addition to decomposing")
        work.add_option(
            "--constant-link",
            dest="doConstantLinks",
            action="store_true",
            default=False,
            help=
            "Add links to the contents of the constant directory to the constant directories of the processor-directories"
        )
        self.parser.add_option_group(work)

        CommonMultiRegion.addOptions(self)
        CommonStandardOutput.addOptions(self)
        CommonServer.addOptions(self, False)
        CommonVCSCommit.addOptions(self)
Example #4
0
    def run(self):
        if foamVersion()>=(1,6):
            self.warning("This utilitiy currently does not work with OF>=1.6 because the API in Paraview>=3.6 has changed. But we'll try")
            
        case=path.abspath(self.parser.getArgs()[0])
        short=path.basename(case)
        
        if self.opts.state==None:
            self.opts.state=path.join(case,"default.pvsm")

        if not path.exists(self.opts.state):
            self.error("The state file",self.opts.state,"does not exist")

        timeString=""
        
        if self.opts.casename:
            timeString+="_"+short
        timeString+="_%(nr)05d"
        if self.opts.timename:
            timeString+="_t=%(t)s"
        timeString+="."+self.opts.type

        sol=SolutionDirectory(case,
                              paraviewLink=False,
                              archive=None)
        
        times=self.processTimestepOptions(sol)
        if len(times)<1:
            self.warning("Can't continue without time-steps")
            return
        
        dataFile=path.join(case,short+".OpenFOAM")
        createdDataFile=False
        if not path.exists(dataFile):
            createdDataFile=True
            f=open(dataFile,"w")
            f.close()
            
        sf=StateFile(self.opts.state)
        sf.setCase(dataFile)
        
        values=eval(self.opts.replacements)
        values[self.opts.casenameKey]=short
        sf.rewriteTexts(values)
        newState=sf.writeTemp()

        sm=SM(requiredReader=sf.readerType())
        if not self.opts.progress:
            sm.ToggleProgressPrinting()

        #        print dir(sm.module())
        sm.LoadState(newState)
        views=sm.GetRenderViews()

        if len(views)>1:
            self.warning("More than 1 view in state-file. Generating multiple series")
            timeString="_View%(view)02d"+timeString
        timeString=self.opts.prefix+timeString
        
        for view in views:
            view.UseOffscreenRenderingForScreenshots=True
        
        for i,t in enumerate(times):
            print "Snapshot ",i," for t=",t
            for j,view in enumerate(views):
                view.ViewTime=float(t)
                fn = timeString % {'nr':i,'t':t,'view':j}
                if PVVersion()<(3,6):
                    view.WriteImage(fn,
                                    self.typeTable[self.opts.type],
                                    self.opts.magnification)
                else:
                    from paraview.simple import SetActiveView,Render,WriteImage
                    SetActiveView(view)
                    Render()
                    # This always produces segmentation fauklts for me 
                    WriteImage(fn,
                               view,
#                               Writer=self.typeTable[self.opts.type],
                               Magnification=self.opts.magnification)
                    
        if createdDataFile:
            self.warning("Removing pseudo-data-file",dataFile)
            unlink(dataFile)

        del sm
Example #5
0
                    print_("Building Pseudocases")
                    regions = RegionCases(sol, clean=True, processorDirs=False)

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

            for theRegion in regionNames:
                theCase = path.normpath(case)
                if theRegion != None and not decomposeParWithRegion:
                    theCase += "." + theRegion

                if oldApp():
                    argv = [self.opts.decomposer, ".", theCase]
                else:
                    argv = [self.opts.decomposer, "-case", theCase]
                    if foamVersion() >= (
                            2, 0) and not self.opts.doFunctionObjects:
                        argv += ["-noFunctionObjects"]
                    if theRegion != None and decomposeParWithRegion:
                        argv += ["-region", theRegion]

                        f = open(
                            path.join(case, "system", theRegion,
                                      "decomposeParDict"), "w")
                        writeDictionaryHeader(f)
                        f.write(str(gen))
                        f.close()

                self.setLogname(default="Decomposer", useApplication=False)

                run = UtilityRunner(
    def __init__(self,
                 sol,
                 correctors,
                 tolerance,
                 relTol,
                 pRefValue=None,
                 pRefCell=None,
                 removeLibs=False,
                 removeFunctions=False):
        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 and foamVersion()[0]<2:
                self.solution["SIMPLE"]=ParsedParameterFile(path.join(pot.systemDir(),"fvSolution"),backup=False)["SIMPLE"]

            if foamVersion()[0]<2:
                solutionBlock=self.solution["SIMPLE"]
            else:
                self.solution["potentialFlow"]={}
                solutionBlock=self.solution["potentialFlow"]

            if "nNonOrthogonalCorrectors" not in solutionBlock and correctors==None:
                correctors=3
                warning("Setting number of correctors to default value",correctors)
            if correctors!=None:
                solutionBlock["nNonOrthogonalCorrectors"]=correctors

            if pRefCell!=None:
                solutionBlock["pRefCell"]=pRefCell
            if pRefValue!=None:
                solutionBlock["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
            for k in ["functions","libs"]:
                if k in self.control:
                    print_("Remove",k,"from controlDict")
                    del self.control[k]

            if "functions" in self.controlOrig and not removeFunctions:
                print_("Copying functions over")
                self.control["functions"]=self.controlOrig["functions"]
            if "libs" in self.controlOrig and not removeLibs:
                print_("Copying libs over")
                self.control["libs"]=self.controlOrig["libs"]

            self.solution.writeFile()
            self.schemes.writeFile()
            self.control.writeFile()
        except Exception:
            e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e'
            warning("Restoring defaults")
            self.solution.restore()
            self.schemes.restore()
            self.control.restore()
            raise e
Example #7
0
    def __init__(self, requiredReader="PV3FoamReader"):
        """Sets up the Servermanager in such a way that it is usable
        with OpenFOAM-data.
        :param requiredReader: Reader that is needed. If not found, try to load plugins"""

        try:
            self.con = self.module().Connect()
        except RuntimeError:
            # 3.98 doesn't seem to need this naymore
            self.con = None

        dyExt = "so"
        if uname()[0] == "Darwin":
            dyExt = "dylib"
        elif uname()[0] == "Windows":
            dyExt = "DLL"

        if requiredReader in dir(simple) and not "OpenFOAMReader":
            warning("Reader", requiredReader,
                    "already present. No plugins loaded")
            return

        if requiredReader == "PV3FoamReader":
            if uname()[0] == "Darwin":
                import ctypes
                # lib=ctypes.CDLL("/Users/bgschaid/OpenFOAM/ThirdParty-1.6/paraview-3.6.2/platforms/darwinIntel64/lib/paraview-3.6/libpqComponents.dylib",mode=ctypes.RTLD_GLOBAL)
                lib = ctypes.CDLL(path.join(environ["FOAM_LIBBIN"],
                                            "libOpenFOAM.dylib"),
                                  mode=ctypes.RTLD_GLOBAL)
                # lib=ctypes.CDLL(path.join(environ["FOAM_LIBBIN"],"paraview","libPV3FoamReader.dylib"),mode=ctypes.RTLD_GLOBAL)
                print_(lib)
            elif uname()[0] == "Linux":
                try:
                    import ctypes
                    dirs = [environ["FOAM_LIBBIN"]
                            ] + environ["PV_PLUGIN_PATH"].split(":")
                    lib = None
                    for d in dirs:
                        try:
                            lib = ctypes.CDLL(path.join(
                                d, "libPV3FoamReader.so"),
                                              mode=ctypes.RTLD_GLOBAL)
                            break
                        except OSError:
                            pass
                    if not lib:
                        warning("Could not find libPV3FoamReader.so in", dirs)
                except ImportError:
                    error(
                        "The Workaround for Linux-Systems won't work because there is no ctypes library"
                    )

            plug1 = "libPV3FoamReader." + dyExt
            if foamVersion() >= (1, 7):
                plug1 = None

            plug2 = "libPV3FoamReader_SM." + dyExt

            loaded = False
            for p in environ["PV_PLUGIN_PATH"].split(":"):
                if path.exists(path.join(p, plug2)):
                    if version() >= (3, 6):
                        LoadPlugin(path.join(p, plug2), ns=globals())
                        try:
                            if plug1:
                                LoadPlugin(path.join(p, plug1), ns=globals())
                            pass
                        except NameError:
                            print_(dir(self.module()))
                            pass
                    else:
                        if plug1:
                            servermanager.LoadPlugin(path.join(p, plug1))
                        servermanager.LoadPlugin(path.join(p, plug2))
                    loaded = True
                    break

            if not loaded:
                error("The plugin", plug2,
                      "was not found in the PV_PLUGIN_PATH",
                      environ["PV_PLUGIN_PATH"])
            if not "PV3FoamReader" in dir(servermanager.sources):
                error(
                    "The plugin was not properly loaded. PV3FoamReader not found in the list of sources"
                )
        elif requiredReader == "OpenFOAMReader":
            if "ParaView_DIR" in environ:
                hasPlug = False
                for d in ["plugins", "Plugins"]:
                    plug = path.join(environ["ParaView_DIR"], "bin", d,
                                     "libPOpenFOAMReaderPlugin." + dyExt)
                    if path.exists(plug):
                        LoadPlugin(plug)
                        hasPlug = True
                        break
                if not hasPlug:
                    warning(
                        "Can't find expected plugin 'libPOpenFOAMReaderPlugin' assuming that correct reader is compiled in. Wish me luck"
                    )
            else:
                warning(
                    "Can't plugin without ParaView_DIR-variable. Continuing without"
                )
        else:
            warning("Loading of plugins for reader", requiredReader,
                    "not implemented")
    def run(self):
        doPic=True
        doGeom=False
        doSources=False
        if self.opts.geomType:
             if PVVersion()<(3,9):
                  self.error("This paraview version does not support geometry writing")
             doGeom=True
             doPic=self.opts.pictureWithGeometry
             if len(self.opts.sources)==0:
                 self.opts.sources=[""] # add empty string as token
        if self.opts.sourcesList:
             doPic=False
             doGeom=False
             doSources=True

        try:
            filterColors=eval(self.opts.filterColors)
        except TypeError:
            filterColors=self.opts.filterColors

        for f in filterColors:
            c=filterColors[f]
            if type(c)==tuple:
                if not c[1]:
                    filterColors[f]=(c[0],self.opts.defaultField)
            else:
                if not c:
                    filterColors[f]=self.opts.defaultField

        try:
            colorRanges=eval(self.opts.colorRanges)
        except TypeError:
            colorRanges=self.opts.colorRanges

        try:
            percentileRanges=eval(self.opts.percentileRanges)
        except TypeError:
            percentileRanges=self.opts.percentileRanges

        self.say("Paraview version",PVVersion(),"FoamVersion",foamVersion())
#        if PVVersion()>=(3,6):
#            self.warning("This is experimental because the API in Paraview>=3.6 has changed. But we'll try")

        case=path.abspath(self.parser.getArgs()[0])
        short=path.basename(case)

        stateString=""
        if self.opts.state==None:
            self.opts.state=path.join(case,"default.pvsm")
        else:
            stateString="_"+path.splitext(path.basename(self.opts.state))[0]

        if not path.exists(self.opts.state):
            self.error("The state file",self.opts.state,"does not exist")

        timeString=""

        if self.opts.casename:
            timeString+="_"+short
        timeString+="_%(nr)05d"
        if self.opts.timename:
            timeString+="_t=%(t)s"

        sol=SolutionDirectory(case,
                              paraviewLink=False,
                              archive=None)

        self.say("Opening state file",self.opts.state)
        sf=StateFile(self.opts.state)

        decoResult=None
        newParallelMode=None
        if self.opts.decomposeMode=="keep":
            pass
        elif self.opts.decomposeMode=="decomposed":
            decoResult=sf.setDecomposed(True)
            newParallelMode=True
        elif self.opts.decomposeMode=="reconstructed":
            decoResult=sf.setDecomposed(False)
            newParallelMode=False
        elif self.opts.decomposeMode=="auto":
            nrTimes=len(sol.getTimes())
            nrParTimes=len(sol.getParallelTimes())
            if nrTimes>nrParTimes:
                newParallelMode=False
                decoResult=sf.setDecomposed(False)
            else:
                newParallelMode=True
                decoResult=sf.setDecomposed(True)
        else:
            self.error("Setting decompose mode",self.opts.decomposeMode,"is not implemented")
        if decoResult:
            self.warning("Setting decomposed type to",self.opts.decomposeMode,":",decoResult)

        if newParallelMode:
            if self.opts.parallelTimes!=newParallelMode:
                self.warning("Resetting parallel mode",newParallelMode)
                self.opts.parallelTimes=newParallelMode

        times=self.processTimestepOptions(sol)
        if len(times)<1:
            self.warning("Can't continue without time-steps")
            return

        dataFile=path.join(case,short+".OpenFOAM")
        createdDataFile=False
        if not path.exists(dataFile):
            self.say("Creating",dataFile)
            createdDataFile=True
            f=open(dataFile,"w")
            f.close()

        self.say("Setting data to",dataFile)
        sf.setCase(dataFile)

        values={}
        if self.opts.addPrepareCaseParameters:
            fName=path.join(case,PrepareCase.parameterOutFile)
            if path.exists(fName):
                self.say("Adding vaules from",fName)
                pf=ParsedParameterFile(fName,noHeader=True)
                values.update(pf.content)
            else:
                self.say("No file",fName)

        values.update(eval(self.opts.replacements))
        values[self.opts.casenameKey]=short
        if self.opts.listReplacements:
            rKeys=sorted(values.keys())
            kLen=max([len(k) for k in rKeys])
            vLen=max([len(str(values[k])) for k in rKeys])
            kFormat=" %"+str(kLen)+"s | %"+str(vLen)+"s"
            print
            print kFormat % ("Key","Value")
            print "-"*(kLen+2)+"|"+"-"*(vLen+2)
            for k in rKeys:
                print kFormat % (k,str(values[k]))
            print

        sf.rewriteTexts(values)
        newState=sf.writeTemp()

        self.say("Setting session manager with reader type",sf.readerType())
        sm=SM(requiredReader=sf.readerType())
        exporterType=None
        if doGeom:
             self.say("Getting geometry exporter",self.geomTypeTable[self.opts.geomType])
             exporters=sm.createModule("exporters")
             exporterType=getattr(exporters,self.geomTypeTable[self.opts.geomType])

        # make sure that the first snapshot is rendered correctly
        import paraview.simple as pvs

        pvs._DisableFirstRenderCameraReset()

        if not self.opts.progress:
            self.say("Toggling progress")
            sm.ToggleProgressPrinting()

        self.say("Loading state")
        sm.LoadState(newState)
        self.say("Getting Views")
        rViews=sm.GetRenderViews()
        views=pvs.GetViews()
        if len(views)>1:
            self.warning("More than 1 view in state-file. Generating multiple series")
            timeString="_View%(view)02d"+timeString
        timeString=self.opts.prefix+timeString+stateString

        self.say("Setting Offscreen rendering")
        offWarn=True

        for iView,view in enumerate(views):
            self.say("Processing view",iView,"of",len(views))
            if self.opts.offscreenRender:
                view.UseOffscreenRenderingForScreenshots=True
                if offWarn:
                    self.warning("Trying offscreen rendering. If writing the file fails with a segmentation fault try --no-offscreen-rendering")
            elif offWarn:
                self.warning("No offscreen rendering. Camera perspective will probably be wrong")
            offWarn=False

        allSources=None
        alwaysSources=None

        self.say("Starting times",times)
        for i,t in enumerate(times):
            self.say("Nr",i,"time",t)
            print "Snapshot ",i," for t=",t,
            sys.stdout.flush()
            self.say()
            layouts=[]

            colorPrefix=""

            # from paraview.simple import UpdatePipeline
            # UpdatePipeline(time=float(t))

            if len(colorRanges)>0:
                for c in colorRanges:
                    rng=colorRanges[c]
                    self.say("Setting color",c,"to range",rng)
                    self.setColorTransferFunction(c,rng)

            if PVVersion()>=(4,2) and len(filterColors)>0:
                self.say("Switch colors")
                from paraview.simple import GetSources,GetDisplayProperties,GetColorTransferFunction,GetScalarBar,HideUnusedScalarBars,UpdatePipeline,ColorBy,SetActiveView,GetRepresentations
                sources=GetSources()
                changedSources=set()
                for j,view in enumerate(views):
                    for n in sources:
                        if n[0] in filterColors:
                            if view in rViews:
                                self.say("Found",n[0],"to be switched")
                                # This does not work as expected.
    #                            dp=GetDisplayProperties(sources[n],view)
                                display=sm.GetRepresentation(sources[n],view)
                                if display==None:
                                    self.say("No representation for",n[0],"in this view")
                                    continue
                                if display.Visibility==0:
                                    self.say("Not switching",n[0],"because it is not visible in this view")
                                    # Invisible Sources don't need a color-change
                                    # Currently Visibily does not work as I expect it (is always 1)
                                    continue

                                if type(filterColors[n[0]])==tuple:
                                    assoc,col=filterColors[n[0]]
                                else:
                                    assoc,col=display.ColorArrayName[0],filterColors[n[0]]
                                if display.ColorArrayName==[assoc,col]:
                                    self.say("Color already set to",assoc,col,".Skipping")
                                    continue
                                ColorBy(display,[assoc,col])

                                # display.ColorArrayName=[assoc,col]
                                changedSources.add(n[0])
                                color=GetColorTransferFunction(col)
                                # display.ColorArrayName=filterColors[n[0]]
                                # display.LookupTable=color
    #                            UpdatePipeline(proxy=sources[n])

                                if n[0] not in self.opts.noColorbar and (len(self.opts.colorbarView)==0 or j in self.opts.colorbarView):
                                    self.say("Adding a colorbar")
                                    scalar=GetScalarBar(color,view)
                                    scalar.Visibility=1
                            elif sources[n].__class__.__name__=="Histogram" \
                                   and view.__class__.__name__=="BarChartView":
                                self.say(n,"is a Histogram")
                                # dp=GetDisplayProperties(sources[n],view)
                                assoc,oldCol=sources[n].SelectInputArray
                                col=filterColors[n[0]]
                                self.say("Setting color from",oldCol,"to",col)
                                sources[n].SelectInputArray=[assoc,col]
                            else:
                                # self.say(n,"is unsuppored Source:",sources[n],
                                #         "View:",view)
                                pass
                    HideUnusedScalarBars(view)

                if self.opts.colorPrefix:
                    for s in changedSources:
                        if type(filterColors[s])==tuple:
                            colorPrefix+=s+"="+filterColors[s][1]+"_"
                        else:
                            colorPrefix+=s+"="+filterColors[s]+"_"

            for c in self.opts.rescaleToSource:
                found=False
                from paraview.simple import GetSources
                sources=GetSources()
                for n in sources:
                    if n[0]==c:
                        src=sources[n]
                        found=True
                        for view in views:
                            display=sm.GetRepresentation(sources[n],view)
                            if display==None:
                                continue
                            if display.Visibility==0:
                                continue
                            col=display.ColorArrayName[1]
                            src.UpdatePipeline(time=float(t))
                            if col in percentileRanges:
                                low,hig=percentileRanges[col]
                                if low is None:
                                    low=0
                                if hig is None:
                                    hig=100
                                else:
                                    hig=100-hig
                                rng=self.getDataRangePercentile(src,col,low=low,high=hig)
                            else:
                                rng=self.getDataRange(src,col)

                            if not rng is None:
                                self.say("Resetting color function",col,"to range",rng,"because of data set",c)
                                if col in colorRanges:
                                    low,hig=colorRanges[col]
                                    if low is not None:
                                        rng=low,rng[1]
                                    if hig is not None:
                                        rng=rng[0],hig
                                    self.say("Extremes overruled to",rng,"for resetting")
                                self.setColorTransferFunction(col,rng)
                            else:
                                self.warning("No field",col,"found on",c)
                        break

                if not found:
                    self.warning("Source",c,"not found")

            for j,view in enumerate(views):
                if len(views)>0:
                    print "View %d" % j,
                    sys.stdout.flush()
                    self.say()
                view.ViewTime=float(t)
                if doPic:
                     print self.opts.picType,
                     sys.stdout.flush()

                     fn = (timeString % {'nr':i,'t':t,'view':j})+"."+self.opts.picType
                     if PVVersion()<(3,6):
                         self.say("Very old Paraview writing")
                         view.WriteImage(fn,
                                         self.picTypeTable[self.opts.picType],
                                         self.opts.magnification)
                     elif PVVersion()<(4,2):
                         self.say("Old Paraview writing")
                         from paraview.simple import SetActiveView,Render,WriteImage
                         self.say("Setting view")
                         SetActiveView(view)
                         self.say("Rendering")
                         Render()
                         self.say("Writing image",fn,"type",self.picTypeTable[self.opts.picType])
                         # This may produce a segmentation fault with offscreen rendering
                         WriteImage(fn,
                                    view,
     #                               Writer=self.picTypeTable[self.opts.picType],
                                    Magnification=self.opts.magnification)
                         self.say("Finished writing")
                     else:
                         doRender=True
                         usedView=view
                         self.say("New Paraview writing")
                         from paraview.simple import SetActiveView,SaveScreenshot,GetLayout,GetSources

                         layout=GetLayout(view)
                         if self.opts.doLayouts:
                             usedView=None
                             if layout in layouts:
                                 doRender=False
                             else:
                                 layouts.append(layout)
                         else:
                             layout=None
                         if doRender:
                             self.say("Writing image",colorPrefix+fn,"type",self.picTypeTable[self.opts.picType])
                             # This may produce a segmentation fault with offscreen rendering
                             SaveScreenshot(colorPrefix+fn,
                                            view=usedView,
                                            layout=layout,
                                            magnification=self.opts.magnification)
                         else:
                             self.say("Skipping image",colorPrefix+fn)
                         self.say("Finished writing")
                if doGeom:
                     from paraview.simple import Show,Hide,GetSources

                     print self.opts.geomType,
                     sys.stdout.flush()
                     for select in self.opts.sources:
                         fn = (timeString % {'nr':i,'t':t,'view':j})
                         if select!="":
                             print "*"+select+"*",
                             sys.stdout.flush()
                             fn+="_"+select
                             sources=GetSources()
                             for n,s in sources.iteritems():
                                 if n[0].find(select)>=0:
                                     Show(s,view)
                                 else:
                                     Hide(s,view)
                         fn += "."+self.opts.geomType
                         self.say("Creating exporter for file",fn)
                         ex=exporterType(FileName=fn)
                         ex.SetView(view)
                         ex.Write()
                if doSources:
                    from paraview.simple import GetSources
                    srcNames=[]
                    sources=GetSources()
                    for n in sources:
                        srcNames.append(n[0])
                    if allSources==None:
                         allSources=set(srcNames)
                         alwaysSources=set(srcNames)
                    else:
                         allSources|=set(srcNames)
                         alwaysSources&=set(srcNames)
            print

        if doSources:
             print
             print "List of found sources (* means that it is present in all timesteps)"
             for n in allSources:
                  if n in alwaysSources:
                       flag="*"
                  else:
                       flag=" "
                  print "  %s  %s" % (flag,n)

        if createdDataFile:
            self.warning("Removing pseudo-data-file",dataFile)
            unlink(dataFile)

        del sm
Example #9
0
    def run(self):
        doPic=True
        doGeom=False
        doSources=False
        if self.opts.geomType:
             if PVVersion()<(3,9):
                  self.error("This paraview version does not support geometry writing")
             doGeom=True
             doPic=self.opts.pictureWithGeometry
             if len(self.opts.sources)==0:
                 self.opts.sources=[""] # add empty string as token
        if self.opts.sourcesList:
             doPic=False
             doGeom=False
             doSources=True

        try:
            filterColors=eval(self.opts.filterColors)
        except TypeError:
            filterColors=self.opts.filterColors

        for f in filterColors:
            c=filterColors[f]
            if type(c)==tuple:
                if not c[1]:
                    filterColors[f]=(c[0],self.opts.defaultField)
            else:
                if not c:
                    filterColors[f]=self.opts.defaultField

        try:
            colorRanges=eval(self.opts.colorRanges)
        except TypeError:
            colorRanges=self.opts.colorRanges

        try:
            percentileRanges=eval(self.opts.percentileRanges)
        except TypeError:
            percentileRanges=self.opts.percentileRanges

        self.say("Paraview version",PVVersion(),"FoamVersion",foamVersion())
#        if PVVersion()>=(3,6):
#            self.warning("This is experimental because the API in Paraview>=3.6 has changed. But we'll try")

        case=path.abspath(self.parser.getArgs()[0])
        short=path.basename(case)

        stateString=""
        if self.opts.state==None:
            self.opts.state=path.join(case,"default.pvsm")
        else:
            stateString="_"+path.splitext(path.basename(self.opts.state))[0]

        if not path.exists(self.opts.state):
            self.error("The state file",self.opts.state,"does not exist")

        timeString=""

        if self.opts.casename:
            timeString+="_"+short
        timeString+="_%(nr)05d"
        if self.opts.timename:
            timeString+="_t=%(t)s"

        sol=SolutionDirectory(case,
                              paraviewLink=False,
                              archive=None)

        self.say("Opening state file",self.opts.state)
        sf=StateFile(self.opts.state)

        decoResult=None
        newParallelMode=None
        if self.opts.decomposeMode=="keep":
            pass
        elif self.opts.decomposeMode=="decomposed":
            decoResult=sf.setDecomposed(True)
            newParallelMode=True
        elif self.opts.decomposeMode=="reconstructed":
            decoResult=sf.setDecomposed(False)
            newParallelMode=False
        elif self.opts.decomposeMode=="auto":
            nrTimes=len(sol.getTimes())
            nrParTimes=len(sol.getParallelTimes())
            if nrTimes>nrParTimes:
                newParallelMode=False
                decoResult=sf.setDecomposed(False)
            else:
                newParallelMode=True
                decoResult=sf.setDecomposed(True)
        else:
            self.error("Setting decompose mode",self.opts.decomposeMode,"is not implemented")
        if decoResult:
            self.warning("Setting decomposed type to",self.opts.decomposeMode,":",decoResult)

        if newParallelMode:
            if self.opts.parallelTimes!=newParallelMode:
                self.warning("Resetting parallel mode",newParallelMode)
                self.opts.parallelTimes=newParallelMode

        times=self.processTimestepOptions(sol)
        if len(times)<1:
            self.warning("Can't continue without time-steps")
            return

        dataFile=path.join(case,short+".OpenFOAM")
        createdDataFile=False
        if not path.exists(dataFile):
            self.say("Creating",dataFile)
            createdDataFile=True
            f=open(dataFile,"w")
            f.close()

        self.say("Setting data to",dataFile)
        sf.setCase(dataFile)

        values={}
        if self.opts.addPrepareCaseParameters:
            fName=path.join(case,PrepareCase.parameterOutFile)
            if path.exists(fName):
                self.say("Adding vaules from",fName)
                pf=ParsedParameterFile(fName,noHeader=True)
                values.update(pf.content)
            else:
                self.say("No file",fName)

        values.update(eval(self.opts.replacements))
        values[self.opts.casenameKey]=short
        if self.opts.listReplacements:
            rKeys=sorted(values.keys())
            kLen=max([len(k) for k in rKeys])
            vLen=max([len(str(values[k])) for k in rKeys])
            kFormat=" %"+str(kLen)+"s | %"+str(vLen)+"s"
            print
            print kFormat % ("Key","Value")
            print "-"*(kLen+2)+"|"+"-"*(vLen+2)
            for k in rKeys:
                print kFormat % (k,str(values[k]))
            print

        sf.rewriteTexts(values)
        newState=sf.writeTemp()

        self.say("Setting session manager with reader type",sf.readerType())
        sm=SM(requiredReader=sf.readerType())
        exporterType=None
        if doGeom:
             self.say("Getting geometry exporter",self.geomTypeTable[self.opts.geomType])
             exporters=sm.createModule("exporters")
             exporterType=getattr(exporters,self.geomTypeTable[self.opts.geomType])

        # make sure that the first snapshot is rendered correctly
        import paraview.simple as pvs

        pvs._DisableFirstRenderCameraReset()

        if not self.opts.progress:
            self.say("Toggling progress")
            sm.ToggleProgressPrinting()

        self.say("Loading state")
        sm.LoadState(newState)
        self.say("Getting Views")
        rViews=sm.GetRenderViews()
        views=pvs.GetViews()
        if (len(views)>1 and PVVersion()<(4,2)) or not self.opts.doLayouts:
            self.warning("More than 1 view in state-file. Generating multiple series")
            timeString="_View%(view)02d"+timeString
        timeString=self.opts.prefix+timeString+stateString

        self.say("Setting Offscreen rendering")
        offWarn=True

        for iView,view in enumerate(views):
            self.say("Processing view",iView,"of",len(views))
            if self.opts.offscreenRender:
                view.UseOffscreenRenderingForScreenshots=True
                if offWarn:
                    self.warning("Trying offscreen rendering. If writing the file fails with a segmentation fault try --no-offscreen-rendering")
            elif offWarn:
                self.warning("No offscreen rendering. Camera perspective will probably be wrong")
            offWarn=False

        allSources=None
        alwaysSources=None

        self.say("Starting times",times)
        for i,t in enumerate(times):
            self.say("Nr",i,"time",t)
            print "Snapshot ",i," for t=",t,
            sys.stdout.flush()
            self.say()
            layouts=[]

            colorPrefix=""

            # from paraview.simple import UpdatePipeline
            # UpdatePipeline(time=float(t))

            if len(colorRanges)>0:
                for c in colorRanges:
                    rng=colorRanges[c]
                    self.say("Setting color",c,"to range",rng)
                    self.setColorTransferFunction(c,rng)

            if PVVersion()>=(4,2) and len(filterColors)>0:
                self.say("Switch colors")
                from paraview.simple import GetSources,GetDisplayProperties,GetColorTransferFunction,GetScalarBar,HideUnusedScalarBars,UpdatePipeline,ColorBy,SetActiveView,GetRepresentations
                sources=GetSources()
                changedSources=set()
                for j,view in enumerate(views):
                    for n in sources:
                        if n[0] in filterColors:
                            if view in rViews:
                                self.say("Found",n[0],"to be switched")
                                # This does not work as expected.
    #                            dp=GetDisplayProperties(sources[n],view)
                                display=sm.GetRepresentation(sources[n],view)
                                if display==None:
                                    self.say("No representation for",n[0],"in this view")
                                    continue
                                if display.Visibility==0:
                                    self.say("Not switching",n[0],"because it is not visible in this view")
                                    # Invisible Sources don't need a color-change
                                    # Currently Visibily does not work as I expect it (is always 1)
                                    continue

                                if type(filterColors[n[0]])==tuple:
                                    assoc,col=filterColors[n[0]]
                                else:
                                    assoc,col=display.ColorArrayName[0],filterColors[n[0]]
                                if display.ColorArrayName==[assoc,col]:
                                    self.say("Color already set to",assoc,col,".Skipping")
                                    continue
                                ColorBy(display,[assoc,col])

                                # display.ColorArrayName=[assoc,col]
                                changedSources.add(n[0])
                                color=GetColorTransferFunction(col)
                                # display.ColorArrayName=filterColors[n[0]]
                                # display.LookupTable=color
    #                            UpdatePipeline(proxy=sources[n])

                                if n[0] not in self.opts.noColorbar and (len(self.opts.colorbarView)==0 or j in self.opts.colorbarView):
                                    self.say("Adding a colorbar")
                                    scalar=GetScalarBar(color,view)
                                    scalar.Visibility=1
                            elif sources[n].__class__.__name__=="Histogram" \
                                   and view.__class__.__name__=="BarChartView":
                                self.say(n,"is a Histogram")
                                # dp=GetDisplayProperties(sources[n],view)
                                assoc,oldCol=sources[n].SelectInputArray
                                col=filterColors[n[0]]
                                self.say("Setting color from",oldCol,"to",col)
                                sources[n].SelectInputArray=[assoc,col]
                            else:
                                # self.say(n,"is unsuppored Source:",sources[n],
                                #         "View:",view)
                                pass
                    HideUnusedScalarBars(view)

                if self.opts.colorPrefix:
                    for s in changedSources:
                        if type(filterColors[s])==tuple:
                            colorPrefix+=s+"="+filterColors[s][1]+"_"
                        else:
                            colorPrefix+=s+"="+filterColors[s]+"_"

            for c in self.opts.rescaleToSource:
                found=False
                from paraview.simple import GetSources
                sources=GetSources()
                for n in sources:
                    if n[0]==c:
                        src=sources[n]
                        found=True
                        for view in views:
                            display=sm.GetRepresentation(sources[n],view)
                            if display==None:
                                continue
                            if display.Visibility==0:
                                continue
                            col=display.ColorArrayName[1]
                            src.UpdatePipeline(time=float(t))
                            if col in percentileRanges:
                                low,hig=percentileRanges[col]
                                if low is None:
                                    low=0
                                if hig is None:
                                    hig=100
                                else:
                                    hig=100-hig
                                rng=self.getDataRangePercentile(src,col,low=low,high=hig)
                            else:
                                rng=self.getDataRange(src,col)

                            if not rng is None:
                                self.say("Resetting color function",col,"to range",rng,"because of data set",c)
                                if col in colorRanges:
                                    low,hig=colorRanges[col]
                                    if low is not None:
                                        rng=low,rng[1]
                                    if hig is not None:
                                        rng=rng[0],hig
                                    self.say("Extremes overruled to",rng,"for resetting")
                                self.setColorTransferFunction(col,rng)
                            else:
                                self.warning("No field",col,"found on",c)
                        break

                if not found:
                    self.warning("Source",c,"not found")

            for j,view in enumerate(views):
                self.say("Preparing views")
                view.ViewTime=float(t)

            for j,view in enumerate(views):
                if len(views)>0:
                    print "View %d" % j,
                    sys.stdout.flush()
                    self.say()

                if doPic:
                     print self.opts.picType,
                     sys.stdout.flush()

                     fn = (timeString % {'nr':i,'t':t,'view':j})+"."+self.opts.picType
                     if PVVersion()<(3,6):
                         self.say("Very old Paraview writing")
                         view.WriteImage(fn,
                                         self.picTypeTable[self.opts.picType],
                                         self.opts.magnification)
                     elif PVVersion()<(4,2):
                         self.say("Old Paraview writing")
                         from paraview.simple import SetActiveView,Render,WriteImage
                         self.say("Setting view")
                         SetActiveView(view)
                         self.say("Rendering")
                         Render()
                         self.say("Writing image",fn,"type",self.picTypeTable[self.opts.picType])
                         # This may produce a segmentation fault with offscreen rendering
                         WriteImage(fn,
                                    view,
     #                               Writer=self.picTypeTable[self.opts.picType],
                                    Magnification=self.opts.magnification)
                         self.say("Finished writing")
                     else:
                         doRender=True
                         usedView=view
                         self.say("New Paraview writing")
                         from paraview.simple import SetActiveView,SaveScreenshot,GetLayout,GetSources

                         layout=GetLayout(view)
                         if self.opts.doLayouts:
                             usedView=None
                             if layout in layouts:
                                 doRender=False
                             else:
                                 layouts.append(layout)
                         else:
                             layout=None
                         if doRender:
                             self.say("Writing image",colorPrefix+fn,"type",self.picTypeTable[self.opts.picType])
                             # This may produce a segmentation fault with offscreen rendering
                             SaveScreenshot(colorPrefix+fn,
                                            view=usedView,
                                            layout=layout,
                                            magnification=self.opts.magnification)
                         else:
                             self.say("Skipping image",colorPrefix+fn)
                         self.say("Finished writing")
                if doGeom:
                     from paraview.simple import Show,Hide,GetSources

                     print self.opts.geomType,
                     sys.stdout.flush()
                     for select in self.opts.sources:
                         fn = (timeString % {'nr':i,'t':t,'view':j})
                         if select!="":
                             print "*"+select+"*",
                             sys.stdout.flush()
                             fn+="_"+select
                             sources=GetSources()
                             for n,s in sources.iteritems():
                                 if n[0].find(select)>=0:
                                     Show(s,view)
                                 else:
                                     Hide(s,view)
                         fn += "."+self.opts.geomType
                         self.say("Creating exporter for file",fn)
                         ex=exporterType(FileName=fn)
                         ex.SetView(view)
                         ex.Write()
                if doSources:
                    from paraview.simple import GetSources
                    srcNames=[]
                    sources=GetSources()
                    for n in sources:
                        srcNames.append(n[0])
                    if allSources==None:
                         allSources=set(srcNames)
                         alwaysSources=set(srcNames)
                    else:
                         allSources|=set(srcNames)
                         alwaysSources&=set(srcNames)
            print

        if doSources:
             print
             print "List of found sources (* means that it is present in all timesteps)"
             for n in allSources:
                  if n in alwaysSources:
                       flag="*"
                  else:
                       flag=" "
                  print "  %s  %s" % (flag,n)

        if createdDataFile:
            self.warning("Removing pseudo-data-file",dataFile)
            unlink(dataFile)

        del sm
Example #10
0
    def run(self):
        doPic = True
        doGeom = False
        doSources = False
        if self.opts.geomType:
            if PVVersion() < (3, 9):
                self.error(
                    "This paraview version does not support geometry writing")
            doGeom = True
            doPic = self.opts.pictureWithGeometry
            if len(self.opts.sources) == 0:
                self.opts.sources = [""]  # add empty string as token
        if self.opts.sourcesList or self.opts.viewList:
            doPic = False
            doGeom = False
            doSources = True

        try:
            filterColors = eval(self.opts.filterColors)
        except TypeError:
            filterColors = self.opts.filterColors

        for f in filterColors:
            c = filterColors[f]
            if isinstance(c, (tuple, )):
                if not c[1]:
                    filterColors[f] = (c[0], self.opts.defaultField)
            elif isinstance(c, (dict, )):
                for k in c:
                    v = c[k]
                    if isinstance(v, (tuple, )):
                        if not v[1]:
                            c[k] = (v[0], self.opts.defaultField)
                    else:
                        if not v:
                            c[k] = self.opts.defaultField
            else:
                if not c:
                    filterColors[f] = self.opts.defaultField

        try:
            colorRanges = eval(self.opts.colorRanges)
        except TypeError:
            colorRanges = self.opts.colorRanges

        try:
            percentileRanges = eval(self.opts.percentileRanges)
        except TypeError:
            percentileRanges = self.opts.percentileRanges

        self.say("Paraview version", PVVersion(), "FoamVersion", foamVersion())
        #        if PVVersion()>=(3,6):
        #            self.warning("This is experimental because the API in Paraview>=3.6 has changed. But we'll try")

        case = path.abspath(self.parser.getArgs()[0])
        short = path.basename(case)

        stateString = ""
        if self.opts.state == None:
            self.opts.state = path.join(case, "default.pvsm")
        else:
            stateString = "_" + path.splitext(path.basename(
                self.opts.state))[0]

        if not path.exists(self.opts.state):
            self.error("The state file", self.opts.state, "does not exist")

        timeString = ""

        if self.opts.casename:
            timeString += "_" + short
        timeString += "_%(nr)05d"
        if self.opts.timename:
            timeString += "_t=%(t)s"

        sol = SolutionDirectory(case, paraviewLink=False, archive=None)

        self.say("Opening state file", self.opts.state)
        sf = StateFile(self.opts.state)

        if self.opts.analyzeState:
            print_(
                "\n\nReaders:\n   ", "\n    ".join([
                    p.type_() + " \t: " + p.getProperty("FileName")
                    for p in sf.getProxy(".+Reader", regexp=True)
                ]))
            print_("Source Proxies:")
            for i, name in sf.sourceIds():
                print_("  ", name, " \t: ", sf[i].type_())
            return

        if self.opts.listProperties:
            print_("\n\nProperties for", self.opts.listProperties, ":")
            srcs = []
            for i, name in sf.sourceIds():
                srcs.append(name)
                if name == self.opts.listProperties:
                    for namee, el in sf[i].listProperties():
                        print_("  ", namee, " \t: ", end=" ")
                        if len(el) == 1:
                            print_("Single element:", el[0][1], end=" ")
                        elif len(el) > 1:
                            print_(len(el), "Elements:", end=" ")
                            for j, v in el:
                                print_("%d:%s" % (j, v), end=" ")
                        else:
                            print_("No value", end=" ")
                        print_()
                    return
            self.error("Not found. Available:", " ".join(srcs))

        decoResult = None
        newParallelMode = None
        if self.opts.decomposeMode == "keep":
            pass
        elif self.opts.decomposeMode == "decomposed":
            decoResult = sf.setDecomposed(True)
            newParallelMode = True
        elif self.opts.decomposeMode == "reconstructed":
            decoResult = sf.setDecomposed(False)
            newParallelMode = False
        elif self.opts.decomposeMode == "auto":
            nrTimes = len(sol.getTimes())
            nrParTimes = len(sol.getParallelTimes())
            if nrTimes > nrParTimes:
                newParallelMode = False
                decoResult = sf.setDecomposed(False)
            else:
                newParallelMode = True
                decoResult = sf.setDecomposed(True)
        else:
            self.error("Setting decompose mode", self.opts.decomposeMode,
                       "is not implemented")
        if decoResult:
            self.warning("Setting decomposed type to", self.opts.decomposeMode,
                         ":", decoResult)

        if newParallelMode:
            if self.opts.parallelTimes != newParallelMode:
                self.warning("Resetting parallel mode", newParallelMode)
                self.opts.parallelTimes = newParallelMode

        if self.opts.consecutiveIndex:
            times = self.processTimestepOptions(sol)
            times = zip(times, range(0, len(times)))
        else:
            times = self.processTimestepOptionsIndex(sol)

        if len(times) < 1:
            self.warning("Can't continue without time-steps")
            return

        dataFile = path.join(case, short + ".OpenFOAM")
        createdDataFile = False
        if not path.exists(dataFile):
            self.say("Creating", dataFile)
            createdDataFile = True
            f = open(dataFile, "w")
            f.close()

        self.say("Setting data to", dataFile)
        sf.setCase(dataFile)

        values = {}
        if self.opts.addPrepareCaseParameters:
            fName = path.join(case, PrepareCase.parameterOutFile)
            if path.exists(fName):
                self.say("Adding vaules from", fName)
                pf = ParsedParameterFile(fName, noHeader=True)
                values.update(pf.content)
            else:
                self.say("No file", fName)

        replString = self.opts.replacements.strip()
        if replString[0] == '{' and replString[-1] == '}':
            values.update(eval(self.opts.replacements))
        else:
            values.update(FoamStringParser(replString).data)
        values[self.opts.casenameKey] = short
        if self.opts.listReplacements:
            rKeys = sorted(values.keys())
            kLen = max([len(k) for k in rKeys])
            maxLen = 100
            vLen = min(max([len(str(values[k])) for k in rKeys]), maxLen)
            kFormat = " %" + str(kLen) + "s | %" + str(vLen) + "s"
            print_()
            print_(kFormat % ("Key", "Value"))
            print_("-" * (kLen + 2) + "|" + "-" * (vLen + 2))
            for k in rKeys:
                valStr = str(values[k])
                if len(valStr) > maxLen:
                    valStr = valStr[:maxLen] + " .. cut"
                print_(kFormat % (k, valStr))
            print_()

        sf.rewriteTexts(values)

        for setProp in self.opts.setProperties:
            parts = setProp.split("=", 1)
            if len(parts) != 2:
                self.error("'=' missing in", setProp)
            value = parts[1]
            left = parts[0].split(":")
            if len(left) == 2:
                src, prop = left
                index = None
            elif len(left) == 3:
                src, prop, index = left
            else:
                self.error(setProp, "not a proper left side")

            print_("Setting on", src, "the property", prop, "index", index,
                   "to", value)
            srcs = []
            for i, name in sf.sourceIds():
                srcs.append(name)
                if name == src:
                    srcs = None
                    props = []
                    for namee, el in sf[i].listProperties():
                        props.append(namee)
                        if namee == prop:
                            props = None
                            sf[i].setProperty(name=prop,
                                              index=index,
                                              value=value)
                            break
                    if props is not None:
                        self.error("No propery", prop, "in", src, "Available:",
                                   " ".join(props))
                    break
            if srcs is not None:
                self.error(src, "not found. Available:", " ".join(srcs))

        newState = sf.writeTemp()

        if self.opts.rewriteOnly:
            print_("Written new statefile to", newState)
            return

        self.say("Setting session manager with reader type", sf.readerType())
        sm = SM(requiredReader=sf.readerType())
        exporterType = None
        if doGeom:
            self.say("Getting geometry exporter",
                     self.geomTypeTable[self.opts.geomType])
            exporters = sm.createModule("exporters")
            exporterType = getattr(exporters,
                                   self.geomTypeTable[self.opts.geomType])

        # make sure that the first snapshot is rendered correctly
        import paraview.simple as pvs

        pvs._DisableFirstRenderCameraReset()

        if not self.opts.progress:
            self.say("Toggling progress")
            sm.ToggleProgressPrinting()

        self.say("Loading state")
        sm.LoadState(newState)

        self.say("Getting Views")
        rViews = sm.GetRenderViews()
        views = pvs.GetViews()
        if (len(views) > 1 and PVVersion() <
            (4, 2)) or not self.opts.doLayouts:
            self.warning(
                "More than 1 view in state-file. Generating multiple series")
            timeString = "_View%(view)02d" + timeString
        timeString = self.opts.prefix + timeString + stateString

        self.say("Setting Offscreen rendering")
        offWarn = True

        viewOrder = []
        for iView, view in enumerate(views):
            self.say("Processing view", iView, "of", len(views))
            viewOrder.append((iView, view.GetProperty("ViewPosition")))
            if self.opts.offscreenRender and PVVersion() < (5, 6):
                view.UseOffscreenRenderingForScreenshots = True
                if offWarn:
                    self.warning(
                        "Trying offscreen rendering. If writing the file fails with a segmentation fault try --no-offscreen-rendering"
                    )
            elif offWarn:
                self.warning(
                    "No offscreen rendering. Camera perspective will probably be wrong"
                )
            offWarn = False

        viewOrder.sort(key=lambda x: (x[1][1], x[1][0]))

        viewReorder = {viewOrder[k][0]: k for k in range(len(viewOrder))}

        allSources = None
        alwaysSources = None

        self.say("Starting times", times[0][0], "(Index", times[0][1], ")")
        for t, i in times:
            self.say("Nr", i, "time", t)
            print_("Snapshot ", i, " for t=", t, end=" ")
            sys.stdout.flush()
            self.say()
            layouts = []

            colorPrefix = ""

            # from paraview.simple import UpdatePipeline
            # UpdatePipeline(time=float(t))

            if len(colorRanges) > 0:
                for c in colorRanges:
                    rng = colorRanges[c]
                    self.say("Setting color", c, "to range", rng)
                    self.setColorTransferFunction(c, rng)

            if PVVersion() >= (4, 2) and len(filterColors) > 0:
                self.say("Switch colors")
                from paraview.simple import GetSources, GetDisplayProperties, GetColorTransferFunction, GetScalarBar, HideUnusedScalarBars, UpdatePipeline, ColorBy, SetActiveView, GetRepresentations
                sources = GetSources()
                changedSources = set()
                for j, view in enumerate(views):
                    viewNr = viewReorder[j]
                    for n in sources:
                        if n[0] in filterColors:
                            if view in rViews:
                                # print(dir(view),view.ListProperties())
                                # print(view.GetProperty("ViewSize"),view.GetProperty("ViewPosition"))
                                self.say("Found", n[0], "in view", viewNr,
                                         "to be switched")
                                # This does not work as expected.
                                #                            dp=GetDisplayProperties(sources[n],view)
                                display = sm.GetRepresentation(
                                    sources[n], view)
                                if display == None:
                                    self.say("No representation for", n[0],
                                             "in this view")
                                    continue
                                if display.Visibility == 0:
                                    self.say(
                                        "Not switching", n[0],
                                        "because it is not visible in this view"
                                    )
                                    # Invisible Sources don't need a color-change
                                    # Currently Visibily does not work as I expect it (is always 1)
                                    continue

                                if isinstance(filterColors[n[0]], (dict, )):
                                    try:
                                        if type(filterColors[n[0]]
                                                [viewNr]) == tuple:
                                            assoc, col = filterColors[
                                                n[0]][viewNr]
                                        else:
                                            assoc, col = display.ColorArrayName[
                                                0], filterColors[n[0]][viewNr]
                                    except KeyError:
                                        self.say("No color specified for",
                                                 n[0], "in view", viewNr)
                                        continue
                                elif type(filterColors[n[0]]) == tuple:
                                    assoc, col = filterColors[n[0]]
                                else:
                                    assoc, col = display.ColorArrayName[
                                        0], filterColors[n[0]]
                                if display.ColorArrayName == [assoc, col]:
                                    self.say("Color already set to", assoc,
                                             col, ".Skipping")
                                    continue
                                ColorBy(display, [assoc, col])
                                self.say("Color", n, "in view", viewNr, "with",
                                         (assoc, col))
                                # display.ColorArrayName=[assoc,col]
                                changedSources.add(n[0])
                                color = GetColorTransferFunction(col)
                                # display.ColorArrayName=filterColors[n[0]]
                                # display.LookupTable=color
                                #                            UpdatePipeline(proxy=sources[n])

                                if n[0] not in self.opts.noColorbar and (
                                        len(self.opts.colorbarView) == 0
                                        or viewNr in self.opts.colorbarView):
                                    self.say("Adding a colorbar")
                                    scalar = GetScalarBar(color, view)
                                    scalar.Visibility = 1
                                    if scalar.Title == "Name":
                                        scalar.Title = col
                                    if scalar.ComponentTitle == "Component":
                                        scalar.ComponentTitle = ""
                            elif sources[n].__class__.__name__=="Histogram" \
                                   and view.__class__.__name__=="BarChartView":
                                self.say(n, "is a Histogram")
                                # dp=GetDisplayProperties(sources[n],view)
                                assoc, oldCol = sources[n].SelectInputArray
                                col = filterColors[n[0]]
                                self.say("Setting color from", oldCol, "to",
                                         col)
                                sources[n].SelectInputArray = [assoc, col]
                            else:
                                # self.say(n,"is unsuppored Source:",sources[n],
                                #         "View:",view)
                                pass
                    HideUnusedScalarBars(view)

                if self.opts.colorPrefix:
                    for s in changedSources:
                        if isinstance(filterColors[s], (tuple, )):
                            colorPrefix += s + "=" + filterColors[s][1] + "_"
                        if isinstance(filterColors[s], (dict, )):
                            spc = filterColors[s]
                            colorPrefix += s + "=" + ":".join(
                                ["%d:%s" % (v, spc[v]) for v in spc]) + "_"
                        else:
                            colorPrefix += s + "=" + filterColors[s] + "_"

            for c in self.opts.rescaleToSource:
                found = False
                from paraview.simple import GetSources
                sources = GetSources()
                for n in sources:
                    if n[0] == c:
                        src = sources[n]
                        found = True
                        for view in views:
                            display = sm.GetRepresentation(sources[n], view)
                            if display == None:
                                continue
                            if display.Visibility == 0:
                                continue
                            col = display.ColorArrayName[1]
                            src.UpdatePipeline(time=float(t))
                            if col in percentileRanges:
                                low, hig = percentileRanges[col]
                                if low is None:
                                    low = 0
                                if hig is None:
                                    hig = 100
                                else:
                                    hig = 100 - hig
                                rng = self.getDataRangePercentile(src,
                                                                  col,
                                                                  low=low,
                                                                  high=hig)
                            else:
                                rng = self.getDataRange(src, col)

                            if not rng is None:
                                self.say("Resetting color function", col,
                                         "to range", rng,
                                         "because of data set", c)
                                if col in colorRanges:
                                    low, hig = colorRanges[col]
                                    if low is not None:
                                        rng = low, rng[1]
                                    if hig is not None:
                                        rng = rng[0], hig
                                    self.say("Extremes overruled to", rng,
                                             "for resetting")
                                self.setColorTransferFunction(col, rng)
                            else:
                                self.warning("No field", col, "found on", c)
                        break

                if not found:
                    self.warning("Source", c, "not found")

            for j, view in enumerate(views):
                self.say("Preparing views")
                view.ViewTime = float(t)

            for j, view in enumerate(views):
                if len(views) > 0:
                    print_("View %d" % j, end=" ")
                    sys.stdout.flush()
                    self.say()

                if doPic:
                    print_(self.opts.picType, end=" ")
                    sys.stdout.flush()

                    fn = (timeString % {
                        'nr': i,
                        't': t,
                        'view': j
                    }) + "." + self.opts.picType
                    if PVVersion() < (3, 6):
                        self.say("Very old Paraview writing")
                        view.WriteImage(fn,
                                        self.picTypeTable[self.opts.picType],
                                        self.opts.magnification)
                    elif PVVersion() < (4, 2):
                        self.say("Old Paraview writing")
                        from paraview.simple import SetActiveView, Render, WriteImage
                        self.say("Setting view")
                        SetActiveView(view)
                        self.say("Rendering")
                        Render()
                        self.say("Writing image", fn, "type",
                                 self.picTypeTable[self.opts.picType])
                        # This may produce a segmentation fault with offscreen rendering
                        WriteImage(
                            fn,
                            view,
                            #                               Writer=self.picTypeTable[self.opts.picType],
                            Magnification=self.opts.magnification)
                        self.say("Finished writing")
                    elif PVVersion() < (5, 4):
                        doRender = True
                        usedView = view
                        self.say("New Paraview writing")
                        from paraview.simple import SetActiveView, SaveScreenshot, GetLayout, GetSources

                        layout = GetLayout(view)
                        if self.opts.doLayouts:
                            usedView = None
                            if layout in layouts:
                                doRender = False
                            else:
                                layouts.append(layout)
                        else:
                            layout = None
                        if doRender:
                            self.say("Writing image", colorPrefix + fn, "type",
                                     self.picTypeTable[self.opts.picType])
                            # This may produce a segmentation fault with offscreen rendering
                            SaveScreenshot(
                                colorPrefix + fn,
                                view=usedView,
                                layout=layout,
                                quality=100 - self.opts.quality,
                                magnification=self.opts.magnification)
                        else:
                            self.say("Skipping image", colorPrefix + fn)
                        self.say("Finished writing")
                    else:
                        doRender = True
                        usedView = view
                        self.say("Paraview >5.4 writing")
                        from paraview.simple import SetActiveView, SaveScreenshot, GetLayout, GetSources

                        layout = GetLayout(view)
                        if self.opts.doLayouts:
                            usedView = None
                            if layout in layouts:
                                doRender = False
                            else:
                                layouts.append(layout)
                            exts = [0] * 4
                            layout.GetLayoutExtent(exts)
                            size = [
                                exts[1] - exts[0] + 1, exts[3] - exts[2] + 1
                            ]
                        else:
                            layout = None
                            size = usedView.ViewSize

                        if doRender:
                            self.say("Writing image", colorPrefix + fn, "type",
                                     self.picTypeTable[self.opts.picType])
                            # This may produce a segmentation fault with offscreen rendering
                            if self.opts.xRes:
                                if self.opts.yRes:
                                    size = self.opts.xRes, self.opts.yRes
                                else:
                                    size = self.opts.xRes, int(self.opts.xRes *
                                                               size[1] /
                                                               float(size[0]))
                            elif self.opts.yRes:
                                size = int(self.opts.yRes * size[0] /
                                           float(size[1])), self.opts.yRes
                            else:
                                size = size[0] * self.opts.magnification, size[
                                    1] * self.opts.magnification
                            SaveScreenshot(
                                colorPrefix + fn,
                                viewOrLayout=usedView or layout,
                                SeparatorWidth=self.opts.separatorWidth,
                                ImageResolution=size,
                                TransparentBackground=self.opts.
                                transparentBackground,
                                ImageQuality=100 - self.opts.quality)
                        else:
                            self.say("Skipping image", colorPrefix + fn)
                        self.say("Finished writing")
                if doGeom:
                    from paraview.simple import Show, Hide, GetSources

                    print_(self.opts.geomType, end=" ")
                    sys.stdout.flush()
                    for select in self.opts.sources:
                        fn = (timeString % {'nr': i, 't': t, 'view': j})
                        if select != "":
                            print_("*" + select + "*", end=" ")
                            sys.stdout.flush()
                            fn += "_" + select
                            sources = GetSources()
                            for n, s in sources.iteritems():
                                if n[0].find(select) >= 0:
                                    Show(s, view)
                                else:
                                    Hide(s, view)
                        fn += "." + self.opts.geomType
                        self.say("Creating exporter for file", fn)
                        ex = exporterType(FileName=fn)
                        ex.SetView(view)
                        ex.Write()
                if doSources:
                    if self.opts.viewList:
                        print_(
                            "View Nr %s: Position %s Size: %s" %
                            (viewReorder[j], view.GetProperty("ViewPosition"),
                             view.GetProperty("ViewSize")))
                    if self.opts.sourcesList:
                        from paraview.simple import GetSources
                        srcNames = []
                        sources = GetSources()
                        for n in sources:
                            srcNames.append(n[0])
                        if allSources == None:
                            allSources = set(srcNames)
                            alwaysSources = set(srcNames)
                        else:
                            allSources |= set(srcNames)
                            alwaysSources &= set(srcNames)
            print_()

        if doSources:
            print_()
            print_(
                "List of found sources (* means that it is present in all timesteps)"
            )
            for n in allSources:
                if n in alwaysSources:
                    flag = "*"
                else:
                    flag = " "
                print_("  %s  %s" % (flag, n))

        if createdDataFile:
            self.warning("Removing pseudo-data-file", dataFile)
            unlink(dataFile)

        del sm
Example #11
0
    def __init__(self,
                 sol,
                 correctors,
                 tolerance,
                 relTol,
                 pRefValue=None,
                 pRefCell=None,
                 removeLibs=False,
                 removeFunctions=False):
        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 and foamVersion()[0] < 2:
                self.solution["SIMPLE"] = ParsedParameterFile(
                    path.join(pot.systemDir(),
                              "fvSolution"), backup=False)["SIMPLE"]

            if foamVersion()[0] < 2:
                solutionBlock = self.solution["SIMPLE"]
            else:
                self.solution["potentialFlow"] = {}
                solutionBlock = self.solution["potentialFlow"]

            if "nNonOrthogonalCorrectors" not in solutionBlock and correctors == None:
                correctors = 3
                warning("Setting number of correctors to default value",
                        correctors)
            if correctors != None:
                solutionBlock["nNonOrthogonalCorrectors"] = correctors

            if pRefCell != None:
                solutionBlock["pRefCell"] = pRefCell
            if pRefValue != None:
                solutionBlock["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
            for k in ["functions", "libs"]:
                if k in self.control:
                    print_("Remove", k, "from controlDict")
                    del self.control[k]

            if "functions" in self.controlOrig and not removeFunctions:
                print_("Copying functions over")
                self.control["functions"] = self.controlOrig["functions"]
            if "libs" in self.controlOrig and not removeLibs:
                print_("Copying libs over")
                self.control["libs"] = self.controlOrig["libs"]

            self.solution.writeFile()
            self.schemes.writeFile()
            self.control.writeFile()
        except Exception:
            e = sys.exc_info()[
                1]  # Needed because python 2.5 does not support 'as e'
            warning("Restoring defaults")
            self.solution.restore()
            self.schemes.restore()
            self.control.restore()
            raise e
    def __init__(self,requiredReader="PV3FoamReader"):
        """Sets up the Servermanager in such a way that it is usable
        with OpenFOAM-data.
        :param requiredReader: Reader that is needed. If not found, try to load plugins"""

        try:
            self.con=self.module().Connect()
        except RuntimeError:
            # 3.98 doesn't seem to need this naymore
            self.con=None

        dyExt="so"
        if uname()[0]=="Darwin":
            dyExt="dylib"
        elif uname()[0]=="Windows":
            dyExt="DLL"

        if requiredReader in dir(simple) and not "OpenFOAMReader":
            warning("Reader",requiredReader,"already present. No plugins loaded")
            return

        if requiredReader=="PV3FoamReader":
            if uname()[0]=="Darwin":
                import ctypes
                # lib=ctypes.CDLL("/Users/bgschaid/OpenFOAM/ThirdParty-1.6/paraview-3.6.2/platforms/darwinIntel64/lib/paraview-3.6/libpqComponents.dylib",mode=ctypes.RTLD_GLOBAL)
                lib=ctypes.CDLL(path.join(environ["FOAM_LIBBIN"],"libOpenFOAM.dylib"),mode=ctypes.RTLD_GLOBAL)
                # lib=ctypes.CDLL(path.join(environ["FOAM_LIBBIN"],"paraview","libPV3FoamReader.dylib"),mode=ctypes.RTLD_GLOBAL)
                print lib
            elif uname()[0]=="Linux":
                try:
                    import ctypes
                    dirs=[environ["FOAM_LIBBIN"]]+environ["PV_PLUGIN_PATH"].split(":")
                    lib=None
                    for d in dirs:
                        try:
                            lib=ctypes.CDLL(path.join(d,"libPV3FoamReader.so"),mode=ctypes.RTLD_GLOBAL)
                            break
                        except OSError:
                            pass
                    if not lib:
                        warning("Could not find libPV3FoamReader.so in",dirs)
                except ImportError:
                    error("The Workaround for Linux-Systems won't work because there is no ctypes library")

            plug1="libPV3FoamReader."+dyExt
            if foamVersion()>=(1,7):
                plug1=None

            plug2="libPV3FoamReader_SM."+dyExt

            loaded=False
            for p in environ["PV_PLUGIN_PATH"].split(":"):
                if path.exists(path.join(p,plug2)):
                    if version()>=(3,6):
                        LoadPlugin(path.join(p,plug2),ns=globals())
                        try:
                            if plug1:
                                LoadPlugin(path.join(p,plug1),ns=globals())
                            pass
                        except NameError:
                            print dir(self.module())
                            pass
                    else:
                        if plug1:
                            servermanager.LoadPlugin(path.join(p,plug1))
                        servermanager.LoadPlugin(path.join(p,plug2))
                    loaded=True
                    break

            if not loaded:
                error("The plugin",plug2,"was not found in the PV_PLUGIN_PATH",environ["PV_PLUGIN_PATH"])
            if not "PV3FoamReader" in dir(servermanager.sources):
                error("The plugin was not properly loaded. PV3FoamReader not found in the list of sources")
        elif requiredReader=="OpenFOAMReader":
            if "ParaView_DIR" in environ:
                hasPlug=False
                for d in ["plugins","Plugins"]:
                    plug=path.join(environ["ParaView_DIR"],"bin",d,"libPOpenFOAMReaderPlugin."+dyExt)
                    if path.exists(plug):
                        LoadPlugin(plug)
                        hasPlug=True
                        break
                if not hasPlug:
                    warning("Can't find expected plugin 'libPOpenFOAMReaderPlugin' assuming that correct reader is compiled in. Wish me luck")
            else:
                warning("Can't plugin without ParaView_DIR-variable. Continuing without")
        else:
            warning("Loading of plugins for reader",requiredReader,"not implemented")
Example #13
0
    def prepare(self,
                sol,
                cName=None,
                overrideParameters=None,
                numberOfProcessors=None):
        """Do the actual preparing
        :param numberOfProcessors: If set this overrides the value set in the
        command line"""

        if cName == None:
            cName = sol.name

        if self.opts.onlyVariables:
            self.opts.verbose = True

        vals = {}
        vals, self.metaData = self.getDefaultValues(cName)
        vals.update(
            self.addDictValues(
                "System", "Automatically defined values", {
                    "casePath":
                    '"' + path.abspath(cName) + '"',
                    "caseName":
                    '"' + path.basename(path.abspath(cName)) + '"',
                    "foamVersion":
                    foamVersion(),
                    "foamFork":
                    foamFork(),
                    "numberOfProcessors":
                    numberOfProcessors if numberOfProcessors != None else
                    self.opts.numberOfProcessors
                }))

        if len(self.opts.extensionAddition) > 0:
            vals.update(
                self.addDictValues(
                    "ExtensionAdditions",
                    "Additional extensions to be processed",
                    dict((e, True) for e in self.opts.extensionAddition)))

        valsWithDefaults = set(vals.keys())

        self.info("Looking for template values", cName)
        for f in self.opts.valuesDicts:
            self.info("Reading values from", f)
            vals.update(
                ParsedParameterFile(f, noHeader=True,
                                    doMacroExpansion=True).getValueDict())

        setValues = {}
        for v in self.opts.values:
            self.info("Updating values", v)
            vals.update(eval(v))
            setValues.update(eval(v))

        if overrideParameters:
            vals.update(overrideParameters)

        unknownValues = set(vals.keys()) - valsWithDefaults
        if len(unknownValues) > 0:
            self.warning("Values for which no default was specified: " +
                         ", ".join(unknownValues))

        if self.opts.verbose and len(vals) > 0:
            print_("\nUsed values\n")
            nameLen = max(len("Name"), max(*[len(k) for k in vals.keys()]))
            format = "%%%ds - %%s" % nameLen
            print_(format % ("Name", "Value"))
            print_("-" * 40)
            for k, v in sorted(iteritems(vals)):
                print_(format % (k, v))
            print_("")
        else:
            self.info("\nNo values specified\n")

        self.checkCorrectOptions(vals)

        derivedScript = path.join(cName, self.opts.derivedParametersScript)
        derivedAdded = None
        derivedChanged = None
        if path.exists(derivedScript):
            self.info("Deriving variables in script", derivedScript)
            scriptText = open(derivedScript).read()
            glob = {}
            oldVals = vals.copy()
            exec_(scriptText, glob, vals)
            derivedAdded = []
            derivedChanged = []
            for k, v in iteritems(vals):
                if k not in oldVals:
                    derivedAdded.append(k)
                elif vals[k] != oldVals[k]:
                    derivedChanged.append(k)
            if len(derivedChanged) > 0 and (
                    not self.opts.allowDerivedChanges
                    and not configuration().getboolean("PrepareCase",
                                                       "AllowDerivedChanges")):
                self.error(
                    self.opts.derivedParametersScript, "changed values of",
                    " ".join(derivedChanged),
                    "\nTo allow this set --allow-derived-changes or the configuration item 'AllowDerivedChanges'"
                )
            if len(derivedAdded) > 0:
                self.info("Added values:", " ".join(derivedAdded))
            if len(derivedChanged) > 0:
                self.info("Changed values:", " ".join(derivedChanged))
            if len(derivedAdded) == 0 and len(derivedChanged) == 0:
                self.info("Nothing added or changed")
        else:
            self.info("No script", derivedScript, "for derived values")

        if self.opts.onlyVariables:
            return

        self.__writeToStateFile(sol, "Starting")

        if self.opts.doClear:
            self.info("Clearing", cName)
            self.__writeToStateFile(sol, "Clearing")
            sol.clear(processor=True,
                      pyfoam=True,
                      vtk=True,
                      removeAnalyzed=True,
                      keepParallel=False,
                      clearHistory=False,
                      clearParameters=True,
                      additional=["postProcessing"])
            self.__writeToStateFile(sol, "Done clearing")

        if self.opts.writeParameters:
            fName = path.join(cName, self.parameterOutFile)
            self.info("Writing parameters to", fName)
            with WriteParameterFile(fName, noHeader=True) as w:
                w.content.update(vals, toString=True)
                w["foamVersion"] = vals["foamVersion"]
                w.writeFile()

        if self.opts.writeReport:
            fName = path.join(cName, self.parameterOutFile + ".rst")
            self.info("Writing report to", fName)
            with open(fName, "w") as w:
                helper = RestructuredTextHelper(defaultHeading=1)
                w.write(".. title:: " + self.__strip(vals["caseName"]) + "\n")
                w.write(".. sectnum::\n")
                w.write(".. header:: " + self.__strip(vals["caseName"]) + "\n")
                w.write(".. header:: " + time.asctime() + "\n")
                w.write(".. footer:: ###Page### / ###Total###\n\n")

                w.write("Parameters set in case directory " +
                        helper.literal(self.__strip(vals["casePath"])) +
                        " at " + helper.emphasis(time.asctime()) + "\n\n")
                w.write(".. contents::\n\n")
                if len(self.opts.valuesDicts):
                    w.write(helper.heading("Parameter files"))
                    w.write("Parameters read from files\n\n")
                    w.write(
                        helper.enumerateList([
                            helper.literal(f) for f in self.opts.valuesDicts
                        ]))
                    w.write("\n")
                if len(setValues) > 0:
                    w.write(helper.heading("Overwritten parameters"))
                    w.write(
                        "These parameters were set from the command line\n\n")
                    w.write(helper.definitionList(setValues))
                    w.write("\n")
                w.write(helper.heading("Parameters with defaults"))
                w.write(self.makeReport(vals))
                if len(unknownValues) > 0:
                    w.write(helper.heading("Unspecified parameters"))
                    w.write(
                        "If these parameters are actually used then specify them in "
                        + helper.literal(self.defaultParameterFile) + "\n\n")
                    tab = helper.table(True)
                    for u in unknownValues:
                        tab.addRow(u)
                        tab.addItem("Value", vals[u])
                    w.write(str(tab))
                if not derivedAdded is None:
                    w.write(helper.heading("Derived Variables"))
                    w.write("Script with derived Parameters" +
                            helper.literal(derivedScript) + "\n\n")
                    if len(derivedAdded) > 0:
                        w.write("These values were added:\n")
                        tab = helper.table(True)
                        for a in derivedAdded:
                            tab.addRow(a)
                            tab.addItem("Value", str(vals[a]))
                        w.write(str(tab))
                    if len(derivedChanged) > 0:
                        w.write("These values were changed:\n")
                        tab = helper.table(True)
                        for a in derivedChanged:
                            tab.addRow(a)
                            tab.addItem("Value", str(vals[a]))
                            tab.addItem("Old", str(oldVals[a]))
                        w.write(str(tab))
                    w.write("The code of the script:\n")
                    w.write(helper.code(scriptText))

        self.addToCaseLog(cName)

        for over in self.opts.overloadDirs:
            self.info("Overloading files from", over)
            self.__writeToStateFile(sol, "Overloading")
            self.overloadDir(sol.name, over)

        self.__writeToStateFile(sol, "Initial")

        zeroOrig = path.join(sol.name, "0.org")

        hasOrig = path.exists(zeroOrig)
        cleanZero = True

        if not hasOrig:
            self.info("Not going to clean '0'")
            self.opts.cleanDirectories.remove("0")
            cleanZero = False

        if self.opts.doCopy:
            if hasOrig:
                self.info("Found 0.org. Clearing 0")
                zeroDir = path.join(sol.name, "0")
                if path.exists(zeroDir):
                    rmtree(zeroDir)
                else:
                    self.info("No 0-directory")

            self.info("")
        else:
            cleanZero = False

        if self.opts.doTemplates:
            self.__writeToStateFile(sol, "Templates")
            self.searchAndReplaceTemplates(
                sol.name,
                vals,
                self.opts.templateExt,
                ignoreDirectories=self.opts.ignoreDirectories)

            self.info("")

        backupZeroDir = None

        if self.opts.doMeshCreate:
            self.__writeToStateFile(sol, "Meshing")
            if self.opts.meshCreateScript:
                scriptName = path.join(sol.name, self.opts.meshCreateScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultMeshCreate)):
                scriptName = path.join(sol.name, self.defaultMeshCreate)
            else:
                scriptName = None

            if scriptName:
                self.info("Executing", scriptName, "for mesh creation")
                if self.opts.verbose:
                    echo = "Mesh: "
                else:
                    echo = None
                self.executeScript(scriptName, workdir=sol.name, echo=echo)
            else:
                self.info(
                    "No script for mesh creation found. Looking for 'blockMeshDict'"
                )
                if sol.blockMesh() != "":
                    self.info(sol.blockMesh(), "found. Executing 'blockMesh'")
                    bm = BasicRunner(argv=["blockMesh", "-case", sol.name])
                    bm.start()
                    if not bm.runOK():
                        self.error("Problem with blockMesh")
                for r in sol.regions():
                    self.info("Checking region", r)
                    s = SolutionDirectory(sol.name,
                                          region=r,
                                          archive=None,
                                          paraviewLink=False)
                    if s.blockMesh() != "":
                        self.info(s.blockMesh(),
                                  "found. Executing 'blockMesh'")
                        bm = BasicRunner(argv=[
                            "blockMesh", "-case", sol.name, "-region", r
                        ])
                        bm.start()
                        if not bm.runOK():
                            self.error("Problem with blockMesh")

            self.info("")

            if cleanZero and path.exists(zeroDir):
                self.warning("Mesh creation recreated 0-directory")
                if self.opts.keepZeroDirectoryFromMesh:
                    backupZeroDir = zeroDir + ".bakByPyFoam"
                    self.info("Backing up", zeroDir, "to", backupZeroDir)
                    move(zeroDir, backupZeroDir)
                else:
                    self.info("Data in", zeroDir, "will be removed")
            self.__writeToStateFile(sol, "Done Meshing")

        if self.opts.doCopy:
            self.__writeToStateFile(sol, "Copying")
            self.copyOriginals(sol.name)

            self.info("")

            if backupZeroDir:
                self.info("Copying backups from", backupZeroDir, "to", zeroDir)
                self.overloadDir(zeroDir, backupZeroDir)
                self.info("Removing backup", backupZeroDir)
                rmtree(backupZeroDir)

        if self.opts.doPostTemplates:
            self.__writeToStateFile(sol, "Post-templates")
            self.searchAndReplaceTemplates(
                sol.name,
                vals,
                self.opts.postTemplateExt,
                ignoreDirectories=self.opts.ignoreDirectories)

            self.info("")

        if self.opts.doCaseSetup:
            self.__writeToStateFile(sol, "Case setup")
            if self.opts.caseSetupScript:
                scriptName = path.join(sol.name, self.opts.caseSetupScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultCaseSetup)):
                scriptName = path.join(sol.name, self.defaultCaseSetup)
            else:
                scriptName = None

            if scriptName:
                self.info("Executing", scriptName, "for case setup")
                if self.opts.verbose:
                    echo = "Case:"
                else:
                    echo = None
                self.executeScript(scriptName, workdir=sol.name, echo=echo)
            elif path.exists(path.join(sol.name, "system", "setFieldsDict")):
                self.info(
                    "So setup script found. But 'setFieldsDict'. Executing setFields"
                )
                sf = BasicRunner(argv=["setFields", "-case", sol.name])
                sf.start()
                if not sf.runOK():
                    self.error("Problem with setFields")
            else:
                self.info("No script for case-setup found. Nothing done")
            self.info("")
            self.__writeToStateFile(sol, "Done case setup")

        if self.opts.doFinalTemplates:
            self.__writeToStateFile(sol, "Final templates")
            self.searchAndReplaceTemplates(
                sol.name,
                vals,
                self.opts.finalTemplateExt,
                ignoreDirectories=self.opts.ignoreDirectories)

        if self.opts.doTemplateClean:
            self.info("Clearing templates")
            for d in self.opts.cleanDirectories:
                for e in [
                        self.opts.templateExt, self.opts.postTemplateExt,
                        self.opts.finalTemplateExt
                ]:
                    self.cleanExtension(path.join(sol.name, d), e)
            self.info("")

        self.info("Case setup finished")
        self.__writeToStateFile(sol, "Finished OK")
Example #14
0
    def prepare(self, sol, cName=None, overrideParameters=None):
        if cName == None:
            cName = sol.name

        if self.opts.onlyVariables:
            self.opts.verbose = True

        vals = {}
        vals["casePath"] = '"' + path.abspath(cName) + '"'
        vals["caseName"] = '"' + path.basename(path.abspath(cName)) + '"'
        vals["foamVersion"] = foamVersion()
        vals["foamFork"] = foamFork()

        if self.opts.verbose:
            print_("Looking for template values", cName)
        for f in self.opts.valuesDicts:
            if self.opts.verbose:
                print_("Reading values from", f)
            vals.update(
                ParsedParameterFile(f, noHeader=True,
                                    doMacroExpansion=True).getValueDict())
        for v in self.opts.values:
            if self.opts.verbose:
                print_("Updating values", v)
            vals.update(eval(v))

        if overrideParameters:
            vals.update(overrideParameters)

        if self.opts.verbose and len(vals) > 0:
            print_("\nUsed values\n")
            nameLen = max(len("Name"), max(*[len(k) for k in vals.keys()]))
            format = "%%%ds - %%s" % nameLen
            print_(format % ("Name", "Value"))
            print_("-" * 40)
            for k, v in sorted(iteritems(vals)):
                print_(format % (k, v))
            print_("")
        elif self.opts.verbose:
            print_("\nNo values specified\n")

        if self.opts.onlyVariables:
            return

        if self.opts.doClear:
            if self.opts.verbose:
                print_("Clearing", cName)
            sol.clear(processor=True,
                      pyfoam=True,
                      vtk=True,
                      removeAnalyzed=True,
                      keepParallel=False,
                      clearHistory=False,
                      clearParameters=True,
                      additional=["postProcessing"])

        if self.opts.writeParameters:
            fName = path.join(cName, self.parameterOutFile)
            if self.opts.verbose:
                print_("Writing parameters to", fName)
            with WriteParameterFile(fName, noHeader=True) as w:
                w.content.update(vals, toString=True)
                w["foamVersion"] = vals["foamVersion"]
                w.writeFile()

        self.addToCaseLog(cName)

        for over in self.opts.overloadDirs:
            if self.opts.verbose:
                print_("Overloading files from", over)
                self.overloadDir(sol.name, over)

        zeroOrig = path.join(sol.name, "0.org")

        hasOrig = path.exists(zeroOrig)
        if not hasOrig:
            if self.opts.verbose:
                print_("Not going to clean '0'")
            self.opts.cleanDirectories.remove("0")

        if self.opts.doCopy:
            if hasOrig:
                if self.opts.verbose:
                    print_("Found 0.org. Clearing 0")
                zeroDir = path.join(sol.name, "0")
                if path.exists(zeroDir):
                    rmtree(zeroDir)
                elif self.opts.verbose:
                    print_("No 0-directory")

            if self.opts.verbose:
                print_("")

        if self.opts.doTemplates:
            self.searchAndReplaceTemplates(sol.name, vals,
                                           self.opts.templateExt)

            if self.opts.verbose:
                print_("")

        if self.opts.doMeshCreate:
            if self.opts.meshCreateScript:
                scriptName = path.join(sol.name, self.opts.meshCreateScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultMeshCreate)):
                scriptName = path.join(sol.name, self.defaultMeshCreate)
            else:
                scriptName = None

            if scriptName:
                if self.opts.verbose:
                    print_("Executing", scriptName, "for mesh creation")
                if self.opts.verbose:
                    echo = "Mesh: "
                else:
                    echo = None
                result = "".join(
                    execute([scriptName], workdir=sol.name, echo=echo))
                open(scriptName + ".log", "w").write(result)
            else:
                if self.opts.verbose:
                    print_(
                        "No script for mesh creation found. Looking for 'blockMeshDict'"
                    )
                if sol.blockMesh() != "":
                    if self.opts.verbose:
                        print_(sol.blockMesh(), "found. Executing 'blockMesh'")
                    bm = BasicRunner(argv=["blockMesh", "-case", sol.name])
                    bm.start()
                    if not bm.runOK():
                        self.error("Problem with blockMesh")
            if self.opts.verbose:
                print_("")

        if self.opts.doCopy:
            self.copyOriginals(sol.name)

            if self.opts.verbose:
                print_("")

        if self.opts.doPostTemplates:
            self.searchAndReplaceTemplates(sol.name, vals,
                                           self.opts.postTemplateExt)

            if self.opts.verbose:
                print_("")

        if self.opts.doCaseSetup:
            if self.opts.caseSetupScript:
                scriptName = path.join(sol.name, self.opts.caseSetupScript)
                if not path.exists(scriptName):
                    self.error("Script", scriptName, "does not exist")
            elif path.exists(path.join(sol.name, self.defaultCaseSetup)):
                scriptName = path.join(sol.name, self.defaultCaseSetup)
            else:
                scriptName = None

            if scriptName:
                if self.opts.verbose:
                    print_("Executing", scriptName, "for case setup")
                if self.opts.verbose:
                    echo = "Case:"
                else:
                    echo = None
                result = "".join(
                    execute([scriptName], workdir=sol.name, echo=echo))
                open(scriptName + ".log", "w").write(result)
            else:
                if self.opts.verbose:
                    print_("No script for case-setup found. Nothing done")
            if self.opts.verbose:
                print_("")

        if self.opts.doTemplateClean:
            if self.opts.verbose:
                print_("Clearing templates")
            for d in self.opts.cleanDirectories:
                for e in [self.opts.templateExt, self.opts.postTemplateExt]:
                    self.cleanExtension(path.join(sol.name, d), e)
            if self.opts.verbose:
                print_("")

        if self.opts.verbose:
            print_("Case setup finished")
Example #15
0
    def addOptions(self):
        if foamVersion()>=(1,6):
            self.defaultMethod="scotch"
            self.decomposeChoices+=[self.defaultMethod]
            self.decomposeChoices+=["parMetis"]

        spec=OptionGroup(self.parser,
                         "Decomposition Specification",
                         "How the case should be decomposed")
        spec.add_option("--method",
                        type="choice",
                        default=self.defaultMethod,
                        dest="method",
                        action="store",
                        choices=self.decomposeChoices,
                        help="The method used for decomposing (Choices: "+string.join(self.decomposeChoices,", ")+") Default: %default")

        spec.add_option("--n",
                        dest="n",
                        action="store",
                        default=None,
                        help="Number of subdivisions in coordinate directions. A python list or tuple (for simple and hierarchical)")

        spec.add_option("--delta",
                        dest="delta",
                        action="store",
                        type="float",
                        default=None,
                        help="Cell skew factor (for simple and hierarchical)")

        spec.add_option("--order",
                        dest="order",
                        action="store",
                        default=None,
                        help="Order of decomposition (for hierarchical)")

        spec.add_option("--processorWeights",
                        dest="processorWeights",
                        action="store",
                        default=None,
                        help="The weights of the processors. A python list. Used for metis, scotch and parMetis")

        spec.add_option("--globalFaceZones",
                        dest="globalFaceZones",
                        action="store",
                        default=None,
                        help="""Global face zones. A string with a python list or an OpenFOAM-list of words. Used for the GGI interface. Ex: '["GGI_Z1","GGI_Z2"]' or '(GGI_Z1 GGI_Z2)'""")

        spec.add_option("--dataFile",
                        dest="dataFile",
                        action="store",
                        default=None,
                        help="File with the allocations. (for manual)")
        self.parser.add_option_group(spec)

        behave=OptionGroup(self.parser,
                           "Decomposition behaviour",
                           "How the program should behave during decomposition")
        behave.add_option("--test",
                          dest="test",
                          action="store_true",
                          default=False,
                          help="Just print the resulting dictionary")

        behave.add_option("--clear",
                          dest="clear",
                          action="store_true",
                          default=False,
                          help="Clear the case of previous processor directories")

        behave.add_option("--no-decompose",
                          dest="doDecompose",
                          action="store_false",
                          default=True,
                          help="Don't run the decomposer (only writes the dictionary")

        behave.add_option("--do-function-objects",
                          dest="doFunctionObjects",
                          action="store_true",
                          default=False,
                          help="Allow the execution of function objects (default behaviour is switching them off)")

        behave.add_option("--decomposer",
                               dest="decomposer",
                               action="store",
                               default="decomposePar",
                               help="The decompose Utility that should be used")
        self.parser.add_option_group(behave)

        work=OptionGroup(self.parser,
                           "Additional work",
                           "What else should be done in addition to decomposing")
        work.add_option("--constant-link",
                        dest="doConstantLinks",
                        action="store_true",
                        default=False,
                        help="Add links to the contents of the constant directory to the constant directories of the processor-directories")
        self.parser.add_option_group(work)

        CommonMultiRegion.addOptions(self)
        CommonStandardOutput.addOptions(self)
        CommonServer.addOptions(self,False)
        CommonVCSCommit.addOptions(self)
Example #16
0
    def run(self):
        doPic = True
        doGeom = False
        doSources = False
        if self.opts.geomType:
            if PVVersion() < (3, 9):
                self.error(
                    "This paraview version does not support geometry writing")
            doGeom = True
            doPic = self.opts.pictureWithGeometry
            if len(self.opts.sources) == 0:
                self.opts.sources = [""]  # add empty string as token
        if self.opts.sourcesList:
            doPic = False
            doGeom = False
            doSources = True

        self.say("Paraview version", PVVersion(), "FoamVersion", foamVersion())
        if PVVersion() >= (3, 6):
            self.warning(
                "This is experimental because the API in Paraview>=3.6 has changed. But we'll try"
            )

        case = path.abspath(self.parser.getArgs()[0])
        short = path.basename(case)

        if self.opts.state == None:
            self.opts.state = path.join(case, "default.pvsm")

        if not path.exists(self.opts.state):
            self.error("The state file", self.opts.state, "does not exist")

        timeString = ""

        if self.opts.casename:
            timeString += "_" + short
        timeString += "_%(nr)05d"
        if self.opts.timename:
            timeString += "_t=%(t)s"

        sol = SolutionDirectory(case, paraviewLink=False, archive=None)

        times = self.processTimestepOptions(sol)
        if len(times) < 1:
            self.warning("Can't continue without time-steps")
            return

        dataFile = path.join(case, short + ".OpenFOAM")
        createdDataFile = False
        if not path.exists(dataFile):
            self.say("Creating", dataFile)
            createdDataFile = True
            f = open(dataFile, "w")
            f.close()

        self.say("Opening state file", self.opts.state)
        sf = StateFile(self.opts.state)
        self.say("Setting data to", dataFile)
        sf.setCase(dataFile)

        values = eval(self.opts.replacements)
        values[self.opts.casenameKey] = short
        sf.rewriteTexts(values)
        newState = sf.writeTemp()

        self.say("Setting session manager with reader type", sf.readerType())
        sm = SM(requiredReader=sf.readerType())
        exporterType = None
        if doGeom:
            self.say("Getting geometry exporter",
                     self.geomTypeTable[self.opts.geomType])
            exporters = sm.createModule("exporters")
            exporterType = getattr(exporters,
                                   self.geomTypeTable[self.opts.geomType])

        # make sure that the first snapshot is rendered correctly
        import paraview.simple
        paraview.simple._DisableFirstRenderCameraReset()

        if not self.opts.progress:
            self.say("Toggling progress")
            sm.ToggleProgressPrinting()

        self.say("Loading state")
        sm.LoadState(newState)
        self.say("Getting Views")
        views = sm.GetRenderViews()

        if len(views) > 1:
            self.warning(
                "More than 1 view in state-file. Generating multiple series")
            timeString = "_View%(view)02d" + timeString
        timeString = self.opts.prefix + timeString

        self.say("Setting Offscreen rendering")
        offWarn = True
        for view in views:
            if self.opts.offscreenRender:
                view.UseOffscreenRenderingForScreenshots = True
                if offWarn:
                    self.warning(
                        "Trying offscreen rendering. If writing the file fails with a segmentation fault try --no-offscreen-rendering"
                    )
            elif offWarn:
                self.warning(
                    "No offscreen rendering. Camera perspective will probably be wrong"
                )
            offWarn = False

        allSources = None
        alwaysSources = None

        self.say("Starting times", times)
        for i, t in enumerate(times):
            self.say("Nr", i, "time", t)
            print "Snapshot ", i, " for t=", t,
            sys.stdout.flush()
            self.say()
            for j, view in enumerate(views):
                if len(views) > 0:
                    print "View %d" % j,
                    sys.stdout.flush()
                    self.say()
                view.ViewTime = float(t)
                if doPic:
                    print self.opts.picType,
                    sys.stdout.flush()

                    fn = (timeString % {
                        'nr': i,
                        't': t,
                        'view': j
                    }) + "." + self.opts.picType
                    if PVVersion() < (3, 6):
                        self.say("Old Paraview writing")
                        view.WriteImage(fn,
                                        self.picTypeTable[self.opts.picType],
                                        self.opts.magnification)
                    else:
                        self.say("New Paraview writing")
                        from paraview.simple import SetActiveView, Render, WriteImage
                        self.say("Setting view")
                        SetActiveView(view)
                        self.say("Rendering")
                        Render()
                        self.say("Writing image", fn, "type",
                                 self.picTypeTable[self.opts.picType])
                        # This may produce a segmentation fault with offscreen rendering
                        WriteImage(
                            fn,
                            view,
                            #                               Writer=self.picTypeTable[self.opts.picType],
                            Magnification=self.opts.magnification)
                        self.say("Finished writing")
                if doGeom:
                    from paraview.simple import Show, Hide, GetSources

                    print self.opts.geomType,
                    sys.stdout.flush()
                    for select in self.opts.sources:
                        fn = (timeString % {'nr': i, 't': t, 'view': j})
                        if select != "":
                            print "*" + select + "*",
                            sys.stdout.flush()
                            fn += "_" + select
                            sources = GetSources()
                            for n, s in sources.iteritems():
                                if n[0].find(select) >= 0:
                                    Show(s, view)
                                else:
                                    Hide(s, view)
                        fn += "." + self.opts.geomType
                        self.say("Creating exporter for file", fn)
                        ex = exporterType(FileName=fn)
                        ex.SetView(view)
                        ex.Write()
                if doSources:
                    from paraview.simple import GetSources
                    srcNames = []
                    sources = GetSources()
                    for n in sources:
                        srcNames.append(n[0])
                    if allSources == None:
                        allSources = set(srcNames)
                        alwaysSources = set(srcNames)
                    else:
                        allSources |= set(srcNames)
                        alwaysSources &= set(srcNames)
            print

        if doSources:
            print
            print "List of found sources (* means that it is present in all timesteps)"
            for n in allSources:
                if n in alwaysSources:
                    flag = "*"
                else:
                    flag = " "
                print "  %s  %s" % (flag, n)

        if createdDataFile:
            self.warning("Removing pseudo-data-file", dataFile)
            unlink(dataFile)

        del sm
Example #17
0
    def run(self):
        doPic=True
        doGeom=False
        doSources=False
        if self.opts.geomType:
             if PVVersion()<(3,9):
                  self.error("This paraview version does not support geometry writing")
             doGeom=True
             doPic=self.opts.pictureWithGeometry
             if len(self.opts.sources)==0:
                 self.opts.sources=[""] # add empty string as token
        if self.opts.sourcesList:
             doPic=False
             doGeom=False
             doSources=True

        self.say("Paraview version",PVVersion(),"FoamVersion",foamVersion())
        if PVVersion()>=(3,6):
            self.warning("This is experimental because the API in Paraview>=3.6 has changed. But we'll try")

        case=path.abspath(self.parser.getArgs()[0])
        short=path.basename(case)

        if self.opts.state==None:
            self.opts.state=path.join(case,"default.pvsm")

        if not path.exists(self.opts.state):
            self.error("The state file",self.opts.state,"does not exist")

        timeString=""

        if self.opts.casename:
            timeString+="_"+short
        timeString+="_%(nr)05d"
        if self.opts.timename:
            timeString+="_t=%(t)s"

        sol=SolutionDirectory(case,
                              paraviewLink=False,
                              archive=None)

        times=self.processTimestepOptions(sol)
        if len(times)<1:
            self.warning("Can't continue without time-steps")
            return

        dataFile=path.join(case,short+".OpenFOAM")
        createdDataFile=False
        if not path.exists(dataFile):
            self.say("Creating",dataFile)
            createdDataFile=True
            f=open(dataFile,"w")
            f.close()

        self.say("Opening state file",self.opts.state)
        sf=StateFile(self.opts.state)
        self.say("Setting data to",dataFile)
        sf.setCase(dataFile)

        values=eval(self.opts.replacements)
        values[self.opts.casenameKey]=short
        sf.rewriteTexts(values)
        newState=sf.writeTemp()

        self.say("Setting session manager with reader type",sf.readerType())
        sm=SM(requiredReader=sf.readerType())
        exporterType=None
        if doGeom:
             self.say("Getting geometry exporter",self.geomTypeTable[self.opts.geomType])
             exporters=sm.createModule("exporters")
             exporterType=getattr(exporters,self.geomTypeTable[self.opts.geomType])

        # make sure that the first snapshot is rendered correctly
        import paraview.simple
        paraview.simple._DisableFirstRenderCameraReset()

        if not self.opts.progress:
            self.say("Toggling progress")
            sm.ToggleProgressPrinting()

        self.say("Loading state")
        sm.LoadState(newState)
        self.say("Getting Views")
        views=sm.GetRenderViews()

        if len(views)>1:
            self.warning("More than 1 view in state-file. Generating multiple series")
            timeString="_View%(view)02d"+timeString
        timeString=self.opts.prefix+timeString

        self.say("Setting Offscreen rendering")
        offWarn=True
        for view in views:
            if self.opts.offscreenRender:
                view.UseOffscreenRenderingForScreenshots=True
                if offWarn:
                    self.warning("Trying offscreen rendering. If writing the file fails with a segmentation fault try --no-offscreen-rendering")
            elif offWarn:
                self.warning("No offscreen rendering. Camera perspective will probably be wrong")
            offWarn=False

        allSources=None
        alwaysSources=None

        self.say("Starting times",times)
        for i,t in enumerate(times):
            self.say("Nr",i,"time",t)
            print "Snapshot ",i," for t=",t,
            sys.stdout.flush()
            self.say()
            for j,view in enumerate(views):
                if len(views)>0:
                    print "View %d" % j,
                    sys.stdout.flush()
                    self.say()
                view.ViewTime=float(t)
                if doPic:
                     print self.opts.picType,
                     sys.stdout.flush()

                     fn = (timeString % {'nr':i,'t':t,'view':j})+"."+self.opts.picType
                     if PVVersion()<(3,6):
                         self.say("Old Paraview writing")
                         view.WriteImage(fn,
                                         self.picTypeTable[self.opts.picType],
                                         self.opts.magnification)
                     else:
                         self.say("New Paraview writing")
                         from paraview.simple import SetActiveView,Render,WriteImage
                         self.say("Setting view")
                         SetActiveView(view)
                         self.say("Rendering")
                         Render()
                         self.say("Writing image",fn,"type",self.picTypeTable[self.opts.picType])
                         # This may produce a segmentation fault with offscreen rendering
                         WriteImage(fn,
                                    view,
     #                               Writer=self.picTypeTable[self.opts.picType],
                                    Magnification=self.opts.magnification)
                         self.say("Finished writing")
                if doGeom:
                     from paraview.simple import Show,Hide,GetSources

                     print self.opts.geomType,
                     sys.stdout.flush()
                     for select in self.opts.sources:
                         fn = (timeString % {'nr':i,'t':t,'view':j})
                         if select!="":
                             print "*"+select+"*",
                             sys.stdout.flush()
                             fn+="_"+select
                             sources=GetSources()
                             for n,s in sources.iteritems():
                                 if n[0].find(select)>=0:
                                     Show(s,view)
                                 else:
                                     Hide(s,view)
                         fn += "."+self.opts.geomType
                         self.say("Creating exporter for file",fn)
                         ex=exporterType(FileName=fn)
                         ex.SetView(view)
                         ex.Write()
                if doSources:
                    from paraview.simple import GetSources
                    srcNames=[]
                    sources=GetSources()
                    for n in sources:
                         srcNames.append(n[0])
                    if allSources==None:
                         allSources=set(srcNames)
                         alwaysSources=set(srcNames)
                    else:
                         allSources|=set(srcNames)
                         alwaysSources&=set(srcNames)
            print

        if doSources:
             print
             print "List of found sources (* means that it is present in all timesteps)"
             for n in allSources:
                  if n in alwaysSources:
                       flag="*"
                  else:
                       flag=" "
                  print "  %s  %s" % (flag,n)

        if createdDataFile:
            self.warning("Removing pseudo-data-file",dataFile)
            unlink(dataFile)

        del sm
    def prepare(self,sol,
                cName=None,
                overrideParameters=None,
                numberOfProcessors=None):
        """Do the actual preparing
        @param numberOfProcessors: If set this overrides the value set in the
        command line"""

        if cName==None:
            cName=sol.name

        if self.opts.onlyVariables:
            self.opts.verbose=True

        vals={}
        vals,self.metaData=self.getDefaultValues(cName)
        vals.update(self.addDictValues("System",
                                       "Automatically defined values",
                                       {
                                           "casePath" : '"'+path.abspath(cName)+'"',
                                           "caseName" : '"'+path.basename(path.abspath(cName))+'"',
                                           "foamVersion" : foamVersion(),
                                           "foamFork" : foamFork(),
                                           "numberOfProcessors" : numberOfProcessors if numberOfProcessors!=None else self.opts.numberOfProcessors
                                       }))

        if len(self.opts.extensionAddition)>0:
            vals.update(self.addDictValues("ExtensionAdditions",
                                           "Additional extensions to be processed",
                                           dict((e,True) for e in self.opts.extensionAddition)))

        valsWithDefaults=set(vals.keys())

        self.info("Looking for template values",cName)
        for f in self.opts.valuesDicts:
            self.info("Reading values from",f)
            vals.update(ParsedParameterFile(f,
                                            noHeader=True,
                                            doMacroExpansion=True).getValueDict())

        setValues={}
        for v in self.opts.values:
            self.info("Updating values",v)
            vals.update(eval(v))
            setValues.update(eval(v))

        if overrideParameters:
            vals.update(overrideParameters)

        unknownValues=set(vals.keys())-valsWithDefaults
        if len(unknownValues)>0:
            self.warning("Values for which no default was specified: "+
                         ", ".join(unknownValues))

        if self.opts.verbose and len(vals)>0:
            print_("\nUsed values\n")
            nameLen=max(len("Name"),
                        max(*[len(k) for k in vals.keys()]))
            format="%%%ds - %%s" % nameLen
            print_(format % ("Name","Value"))
            print_("-"*40)
            for k,v in sorted(iteritems(vals)):
                print_(format % (k,v))
            print_("")
        else:
            self.info("\nNo values specified\n")

        self.checkCorrectOptions(vals)

        derivedScript=path.join(cName,self.opts.derivedParametersScript)
        if path.exists(derivedScript):
            self.info("Deriving variables in script",derivedScript)
            scriptText=open(derivedScript).read()
            glob={}
            oldVals=vals.copy()
            exec_(scriptText,glob,vals)
            added=[]
            changed=[]
            for k,v in iteritems(vals):
                if k not in oldVals:
                    added.append(k)
                elif vals[k]!=oldVals[k]:
                    changed.append(k)
            if len(changed)>0 and (not self.opts.allowDerivedChanges and not configuration().getboolean("PrepareCase","AllowDerivedChanges")):
                self.error(self.opts.derivedParametersScript,
                           "changed values of"," ".join(changed),
                           "\nTo allow this set --allow-derived-changes or the configuration item 'AllowDerivedChanges'")
            if len(added)>0:
                self.info("Added values:"," ".join(added))
            if len(changed)>0:
                self.info("Changed values:"," ".join(changed))
            if len(added)==0 and len(changed)==0:
                self.info("Nothing added or changed")
        else:
            self.info("No script",derivedScript,"for derived values")

        if self.opts.onlyVariables:
            return

        if self.opts.doClear:
            self.info("Clearing",cName)
            sol.clear(processor=True,
                      pyfoam=True,
                      vtk=True,
                      removeAnalyzed=True,
                      keepParallel=False,
                      clearHistory=False,
                      clearParameters=True,
                      additional=["postProcessing"])

        if self.opts.writeParameters:
            fName=path.join(cName,self.parameterOutFile)
            self.info("Writing parameters to",fName)
            with WriteParameterFile(fName,noHeader=True) as w:
                w.content.update(vals,toString=True)
                w["foamVersion"]=vals["foamVersion"]
                w.writeFile()

        if self.opts.writeReport:
            fName=path.join(cName,self.parameterOutFile+".rst")
            self.info("Writing report to",fName)
            with open(fName,"w") as w:
                helper=RestructuredTextHelper(defaultHeading=1)
                w.write(".. title:: "+self.__strip(vals["caseName"])+"\n")
                w.write(".. sectnum::\n")
                w.write(".. header:: "+self.__strip(vals["caseName"])+"\n")
                w.write(".. header:: "+time.asctime()+"\n")
                w.write(".. footer:: ###Page### / ###Total###\n\n")

                w.write("Parameters set in case directory "+
                        helper.literal(self.__strip(vals["casePath"]))+" at "+
                        helper.emphasis(time.asctime())+"\n\n")
                w.write(".. contents::\n\n")
                if len(self.opts.valuesDicts):
                    w.write(helper.heading("Parameter files"))
                    w.write("Parameters read from files\n\n")
                    w.write(helper.enumerateList([helper.literal(f) for f in self.opts.valuesDicts]))
                    w.write("\n")
                if len(setValues)>0:
                    w.write(helper.heading("Overwritten parameters"))
                    w.write("These parameters were set from the command line\n\n")
                    w.write(helper.definitionList(setValues))
                    w.write("\n")
                w.write(helper.heading("Parameters with defaults"))
                w.write(self.makeReport(vals))
                if len(unknownValues)>0:
                    w.write(helper.heading("Unspecified parameters"))
                    w.write("If these parameters are actually used then specify them in "+
                            helper.literal(self.defaultParameterFile)+"\n\n")
                    tab=helper.table(True)
                    for u in unknownValues:
                        tab.addRow(u)
                        tab.addItem("Value",vals[u])
                    w.write(str(tab))

        self.addToCaseLog(cName)

        for over in self.opts.overloadDirs:
            self.info("Overloading files from",over)
            self.overloadDir(sol.name,over)

        zeroOrig=path.join(sol.name,"0.org")

        hasOrig=path.exists(zeroOrig)
        cleanZero=True

        if not hasOrig:
            self.info("Not going to clean '0'")
            self.opts.cleanDirectories.remove("0")
            cleanZero=False

        if self.opts.doCopy:
            if hasOrig:
                self.info("Found 0.org. Clearing 0")
                zeroDir=path.join(sol.name,"0")
                if path.exists(zeroDir):
                    rmtree(zeroDir)
                else:
                    self.info("No 0-directory")

            self.info("")
        else:
            cleanZero=False

        if self.opts.doTemplates:
            self.searchAndReplaceTemplates(sol.name,
                                           vals,
                                           self.opts.templateExt)

            self.info("")

        backupZeroDir=None

        if self.opts.doMeshCreate:
            if self.opts.meshCreateScript:
                scriptName=path.join(sol.name,self.opts.meshCreateScript)
                if not path.exists(scriptName):
                    self.error("Script",scriptName,"does not exist")
            elif path.exists(path.join(sol.name,self.defaultMeshCreate)):
                scriptName=path.join(sol.name,self.defaultMeshCreate)
            else:
                scriptName=None

            if scriptName:
                self.info("Executing",scriptName,"for mesh creation")
                if self.opts.verbose:
                    echo="Mesh: "
                else:
                    echo=None
                result="".join(execute([scriptName],workdir=sol.name,echo=echo))
                open(scriptName+".log","w").write(result)
            else:
                self.info("No script for mesh creation found. Looking for 'blockMeshDict'")
                if sol.blockMesh()!="":
                    self.info(sol.blockMesh(),"found. Executing 'blockMesh'")
                    bm=BasicRunner(argv=["blockMesh","-case",sol.name])
                    bm.start()
                    if not bm.runOK():
                        self.error("Problem with blockMesh")
                for r in sol.regions():
                    self.info("Checking region",r)
                    s=SolutionDirectory(sol.name,region=r,
                                        archive=None,paraviewLink=False)
                    if s.blockMesh()!="":
                        self.info(s.blockMesh(),"found. Executing 'blockMesh'")
                        bm=BasicRunner(argv=["blockMesh","-case",sol.name,
                                             "-region",r])
                        bm.start()
                        if not bm.runOK():
                            self.error("Problem with blockMesh")

            self.info("")

            if cleanZero and path.exists(zeroDir):
                self.warning("Mesh creation recreated 0-directory")
                if self.opts.keepZeroDirectoryFromMesh:
                    backupZeroDir=zeroDir+".bakByPyFoam"
                    self.info("Backing up",zeroDir,"to",backupZeroDir)
                    move(zeroDir,backupZeroDir)
                else:
                    self.info("Data in",zeroDir,"will be removed")

        if self.opts.doCopy:
            self.copyOriginals(sol.name)

            self.info("")

            if backupZeroDir:
                self.info("Copying backups from",backupZeroDir,"to",zeroDir)
                self.overloadDir(zeroDir,backupZeroDir)
                self.info("Removing backup",backupZeroDir)
                rmtree(backupZeroDir)

        if self.opts.doPostTemplates:
            self.searchAndReplaceTemplates(sol.name,
                                           vals,
                                           self.opts.postTemplateExt)

            self.info("")

        if self.opts.doCaseSetup:
            if self.opts.caseSetupScript:
                scriptName=path.join(sol.name,self.opts.caseSetupScript)
                if not path.exists(scriptName):
                    self.error("Script",scriptName,"does not exist")
            elif path.exists(path.join(sol.name,self.defaultCaseSetup)):
                scriptName=path.join(sol.name,self.defaultCaseSetup)
            else:
                scriptName=None

            if scriptName:
                self.info("Executing",scriptName,"for case setup")
                if self.opts.verbose:
                    echo="Case:"
                else:
                    echo=None
                result="".join(execute([scriptName],workdir=sol.name,echo=echo))
                open(scriptName+".log","w").write(result)
            else:
                self.info("No script for case-setup found. Nothing done")
            self.info("")

        if self.opts.doFinalTemplates:
            self.searchAndReplaceTemplates(sol.name,
                                           vals,
                                           self.opts.finalTemplateExt)

        if self.opts.doTemplateClean:
            self.info("Clearing templates")
            for d in self.opts.cleanDirectories:
                for e in [self.opts.templateExt,
                          self.opts.postTemplateExt,
                          self.opts.finalTemplateExt]:
                    self.cleanExtension(path.join(sol.name,d),e)
            self.info("")

        self.info("Case setup finished")