Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 4
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
    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
Ejemplo n.º 6
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