def RequestData():
    # R.0.2018.080
    import sys
    import numpy as np
    import os
    import paraview.simple as simple
    sys.path.insert(0, r'EMC_SRC_PATH')
    import IrisEMC_Paraview_Lib as lib

    views = simple.GetViews(viewtype="SpreadSheetView")
    if len(views) > 0:
        simple.Delete(views[0])
    else:
        view = simple.GetActiveView()
        layout = simple.GetLayout(view)

    pdo = self.GetOutput()  # vtkTable

    if Coordinate_Type == 0:
        lon = X_or_Longitude
        lat = Y_or_Latitude
        depth = Z_or_Depth
        x, y, z = lib.llz2xyz(lat, lon, depth)
    else:
        x = X_or_Longitude
        y = Y_or_Latitude
        z = Z_or_Depth
        lat, lon, depth = lib.xyz2llz(x, y, z)

    # store metadata
    fieldData = pdo.GetFieldData()
    fieldData.AllocateArrays(3)  # number of fields

    fieldData = pdo.GetFieldData()
    data = vtk.vtkFloatArray()
    data.SetName('Longitude, Latitude, Depth')
    data.InsertNextValue(lon)
    data.InsertNextValue(lat)
    data.InsertNextValue(depth)
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('X, Y, Z')
    data.InsertNextValue(x)
    data.InsertNextValue(y)
    data.InsertNextValue(z)
    fieldData.AddArray(data)

    pdo.SetFieldData(fieldData)
Ejemplo n.º 2
0
def get_state(options=None, source_set=[], filter=None, raw=False):
    """Returns the state string"""
    if options:
        options = sm._getPyProxy(options)
        propertiesToTraceOnCreate = options.PropertiesToTraceOnCreate
        skipHiddenRepresentations = options.SkipHiddenDisplayProperties
        skipRenderingComponents = options.SkipRenderingComponents
    else:
        propertiesToTraceOnCreate = RECORD_MODIFIED_PROPERTIES
        skipHiddenRepresentations = True
        skipRenderingComponents = False

    # essential to ensure any obsolete accessors don't linger - can cause havoc
    # when saving state following a Python trace session
    # (paraview/paraview#18994)
    import gc
    gc.collect()

    if sm.vtkSMTrace.GetActiveTracer():
        raise RuntimeError ("Cannot generate Python state when tracing is active.")

    if filter is None:
        filter = visible_representations() if skipHiddenRepresentations else supported_proxies()

    # build a set of proxies of interest
    if source_set:
        start_set = source_set
    else:
        # if nothing is specified, we save all views and sources.
        start_set = [x for x in simple.GetSources().values()] + simple.GetViews()
    start_set = [x for x in start_set if filter(x)]

    # now, locate dependencies for the start_set, pruning irrelevant branches
    consumers = set(start_set)
    for proxy in start_set:
        get_consumers(proxy, filter, consumers)

    producers = set()
    for proxy in consumers:
        get_producers(proxy, filter, producers)

    # proxies_of_interest is set of all proxies that we should trace.
    proxies_of_interest = producers.union(consumers)
    #print ("proxies_of_interest", proxies_of_interest)

    trace_config = smtrace.start_trace(preamble="")
    # this ensures that lookup tables/scalar bars etc. are fully traced.
    trace_config.SetFullyTraceSupplementalProxies(True)
    trace_config.SetSkipRenderingComponents(skipRenderingComponents)

    trace = smtrace.TraceOutput()
    trace.append("# state file generated using %s" % simple.GetParaViewSourceVersion())
    trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))

    #--------------------------------------------------------------------------
    # We trace the views and layouts, if any.
    if skipRenderingComponents:
        views = []
    else:
        views = [x for x in proxies_of_interest if smtrace.Trace.get_registered_name(x, "views")]

    if views:
        # sort views by their names, so the state has some structure to it.
        views = sorted(views, key=lambda x:\
                smtrace.Trace.get_registered_name(x, "views"))
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup views used in the visualization",
            "# ----------------------------------------------------------------"])
        for view in views:
            # FIXME: save view camera positions and size.
            traceitem = smtrace.RegisterViewProxy(view)
            traceitem.finalize()
            del traceitem
        trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))
        trace.append_separated(["SetActiveView(None)"])

    # from views,  build the list of layouts of interest.
    layouts = set()
    for aview in views:
        l = simple.GetLayout(aview)
        if l:
            layouts.add(simple.GetLayout(aview))

    # trace create of layouts
    if layouts:
        layouts = sorted(layouts, key=lambda x:\
                  smtrace.Trace.get_registered_name(x, "layouts"))
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup view layouts",
            "# ----------------------------------------------------------------"])
        for layout in layouts:
            traceitem = smtrace.RegisterLayoutProxy(layout)
            traceitem.finalize(filter=lambda x: x in views)
            del traceitem
        trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))

    if views:
        # restore the active view after the layouts have been created.
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# restore active view",
            "SetActiveView(%s)" % smtrace.Trace.get_accessor(simple.GetActiveView()),
            "# ----------------------------------------------------------------"])

    #--------------------------------------------------------------------------
    # Next, trace data processing pipelines.
    sorted_proxies_of_interest = __toposort(proxies_of_interest)
    sorted_sources = [x for x in sorted_proxies_of_interest \
        if smtrace.Trace.get_registered_name(x, "sources")]
    if sorted_sources:
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup the data processing pipelines",
            "# ----------------------------------------------------------------"])
        for source in sorted_sources:
            traceitem = smtrace.RegisterPipelineProxy(source)
            traceitem.finalize()
            del traceitem
        trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))

    #--------------------------------------------------------------------------
    # Can't decide if the representations should be saved with the pipeline
    # objects or afterwards, opting for afterwards for now since the topological
    # sort doesn't guarantee that the representations will follow their sources
    # anyways.
    sorted_representations = [x for x in sorted_proxies_of_interest \
        if smtrace.Trace.get_registered_name(x, "representations")]
    scalarbar_representations = [x for x in sorted_proxies_of_interest\
        if smtrace.Trace.get_registered_name(x, "scalar_bars")]
    # print ("sorted_representations", sorted_representations)
    # print ("scalarbar_representations", scalarbar_representations)
    if not skipRenderingComponents and (sorted_representations or scalarbar_representations):
        for view in views:
            view_representations = [x for x in view.Representations if x in sorted_representations]
            view_scalarbars = [x for x in view.Representations if x in scalarbar_representations]
            if view_representations or view_scalarbars:
                trace.append_separated([\
                    "# ----------------------------------------------------------------",
                    "# setup the visualization in view '%s'" % smtrace.Trace.get_accessor(view),
                    "# ----------------------------------------------------------------"])
            for rep in view_representations:
                try:
                    producer = rep.Input
                    port = rep.Input.Port
                    traceitem = smtrace.Show(producer, port, view, rep,
                        comment="show data from %s" % smtrace.Trace.get_accessor(producer))
                    traceitem.finalize()
                    del traceitem
                    trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))

                    if rep.UseSeparateColorMap:
                        trace.append_separated([\
                            "# set separate color map",
                            "%s.UseSeparateColorMap = True" % (\
                                smtrace.Trace.get_accessor(rep))])

                except AttributeError: pass
            # save the scalar bar properties themselves.
            if view_scalarbars:
                trace.append_separated("# setup the color legend parameters for each legend in this view")
                for rep in view_scalarbars:
                    smtrace.Trace.get_accessor(rep)
                    trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))
                    trace.append_separated([\
                      "# set color bar visibility", "%s.Visibility = %s" % (\
                    smtrace.Trace.get_accessor(rep), rep.Visibility)])


            for rep in view_representations:
                try:
                    producer = rep.Input
                    port = rep.Input.Port

                    if rep.IsScalarBarVisible(view):
                        # FIXME: this will save this multiple times, right now,
                        # if two representations use the same LUT.
                        trace.append_separated([\
                            "# show color legend",
                            "%s.SetScalarBarVisibility(%s, True)" % (\
                                smtrace.Trace.get_accessor(rep),
                                smtrace.Trace.get_accessor(view))])

                    if not rep.Visibility:
                      traceitem = smtrace.Hide(producer, port, view)
                      traceitem.finalize()
                      del traceitem
                      trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))

                except AttributeError: pass

    #--------------------------------------------------------------------------
    # Now, trace the transfer functions (color maps and opacity maps) used.
    ctfs = set([x for x in proxies_of_interest \
        if smtrace.Trace.get_registered_name(x, "lookup_tables")])
    if not skipRenderingComponents and ctfs:
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup color maps and opacity mapes used in the visualization",
            "# note: the Get..() functions create a new object, if needed",
            "# ----------------------------------------------------------------"])
        for ctf in ctfs:
            smtrace.Trace.get_accessor(ctf)
            if ctf.ScalarOpacityFunction in proxies_of_interest:
                smtrace.Trace.get_accessor(ctf.ScalarOpacityFunction)
        trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))

    # Trace extract generators.
    exgens = set([x for x in proxies_of_interest \
            if smtrace.Trace.get_registered_name(x, "extract_generators")])
    if exgens:
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup extract generators",
            "# ----------------------------------------------------------------"])
        for exgen in exgens:
            # FIXME: this currently doesn't handle multiple output ports
            # correctly.
            traceitem = smtrace.CreateExtractGenerator(\
                    xmlname=exgen.Writer.GetXMLName(),
                    producer=exgen.Producer,
                    generator=exgen,
                    registrationName=smtrace.Trace.get_registered_name(exgen, "extract_generators"))
            traceitem.finalize()
            del traceitem
        trace.append_separated(smtrace.get_current_trace_output_and_reset(raw=True))

    # restore the active source since the order in which the pipeline is created
    # in the state file can end up changing the active source to be different
    # than what it was when the state is being saved.
    trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# restore active source",
            "SetActiveSource(%s)" % smtrace.Trace.get_accessor(simple.GetActiveSource()),
            "# ----------------------------------------------------------------"])

    if options:
        # add coda about extracts generation.
        trace.append_separated(["",
            "if __name__ == '__main__':",
            "    # generate extracts",
            "    SaveExtracts(ExtractsOutputDirectory='%s')" % options.ExtractsOutputDirectory])
    del trace_config
    smtrace.stop_trace()
    #print (trace)
    return str(trace) if not raw else trace.raw_data()
Ejemplo n.º 3
0
def get_state(
        propertiesToTraceOnCreate=1,  # sm.vtkSMTrace.RECORD_MODIFIED_PROPERTIES,
        skipHiddenRepresentations=True,
        source_set=[],
        filter=None,
        raw=False):
    """Returns the state string"""
    if sm.vtkSMTrace.GetActiveTracer():
        raise RuntimeError(
            "Cannot generate Python state when tracing is active.")

    if filter is None:
        filter = visible_representations(
        ) if skipHiddenRepresentations else supported_proxies()

    # build a set of proxies of interest
    if source_set:
        start_set = source_set
    else:
        # if nothing is specified, we save all views and sources.
        start_set = [x for x in simple.GetSources().values()
                     ] + simple.GetViews()
    start_set = [x for x in start_set if filter(x)]

    # now, locate dependencies for the start_set, pruning irrelevant branches
    consumers = set(start_set)
    for proxy in start_set:
        get_consumers(proxy, filter, consumers)

    producers = set()
    for proxy in consumers:
        get_producers(proxy, filter, producers)

    # proxies_of_interest is set of all proxies that we should trace.
    proxies_of_interest = producers.union(consumers)
    #print ("proxies_of_interest", proxies_of_interest)

    trace_config = smtrace.start_trace()
    # this ensures that lookup tables/scalar bars etc. are fully traced.
    trace_config.SetFullyTraceSupplementalProxies(True)

    trace = smtrace.TraceOutput()
    trace.append("# state file generated using %s" %
                 simple.GetParaViewSourceVersion())

    #--------------------------------------------------------------------------
    # First, we trace the views and layouts, if any.
    # TODO: add support for layouts.
    views = [
        x for x in proxies_of_interest
        if smtrace.Trace.get_registered_name(x, "views")
    ]
    if views:
        # sort views by their names, so the state has some structure to it.
        views = sorted(views, key=lambda x:\
                smtrace.Trace.get_registered_name(x, "views"))
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup views used in the visualization",
            "# ----------------------------------------------------------------"])
        for view in views:
            # FIXME: save view camera positions and size.
            traceitem = smtrace.RegisterViewProxy(view)
            traceitem.finalize()
            del traceitem
        trace.append_separated(
            smtrace.get_current_trace_output_and_reset(raw=True))
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# restore active view",
            "SetActiveView(%s)" % smtrace.Trace.get_accessor(simple.GetActiveView()),
            "# ----------------------------------------------------------------"])

    #--------------------------------------------------------------------------
    # Next, trace data processing pipelines.
    sorted_proxies_of_interest = __toposort(proxies_of_interest)
    sorted_sources = [x for x in sorted_proxies_of_interest \
        if smtrace.Trace.get_registered_name(x, "sources")]
    if sorted_sources:
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup the data processing pipelines",
            "# ----------------------------------------------------------------"])
        for source in sorted_sources:
            traceitem = smtrace.RegisterPipelineProxy(source)
            traceitem.finalize()
            del traceitem
        trace.append_separated(
            smtrace.get_current_trace_output_and_reset(raw=True))

    #--------------------------------------------------------------------------
    # Can't decide if the representations should be saved with the pipeline
    # objects or afterwords, opting for afterwords for now since the topological
    # sort doesn't guarantee that the representations will follow their sources
    # anyways.
    sorted_representations = [x for x in sorted_proxies_of_interest \
        if smtrace.Trace.get_registered_name(x, "representations")]
    scalarbar_representations = [x for x in sorted_proxies_of_interest\
        if smtrace.Trace.get_registered_name(x, "scalar_bars")]
    # print ("sorted_representations", sorted_representations)
    # print ("scalarbar_representations", scalarbar_representations)
    if sorted_representations or scalarbar_representations:
        for view in views:
            view_representations = [
                x for x in view.Representations if x in sorted_representations
            ]
            view_scalarbars = [
                x for x in view.Representations
                if x in scalarbar_representations
            ]
            if view_representations or view_scalarbars:
                trace.append_separated([\
                    "# ----------------------------------------------------------------",
                    "# setup the visualization in view '%s'" % smtrace.Trace.get_accessor(view),
                    "# ----------------------------------------------------------------"])
            for rep in view_representations:
                try:
                    producer = rep.Input
                    port = rep.Input.Port
                    traceitem = smtrace.Show(
                        producer,
                        port,
                        view,
                        rep,
                        comment="show data from %s" %
                        smtrace.Trace.get_accessor(producer))
                    traceitem.finalize()
                    del traceitem
                    trace.append_separated(
                        smtrace.get_current_trace_output_and_reset(raw=True))

                    if rep.UseSeparateColorMap:
                        trace.append_separated([\
                            "# set separate color map",
                            "%s.UseSeparateColorMap = True" % (\
                                smtrace.Trace.get_accessor(rep))])

                except AttributeError:
                    pass
            # save the scalar bar properties themselves.
            if view_scalarbars:
                trace.append_separated(
                    "# setup the color legend parameters for each legend in this view"
                )
                for rep in view_scalarbars:
                    smtrace.Trace.get_accessor(rep)
                    trace.append_separated(
                        smtrace.get_current_trace_output_and_reset(raw=True))
                    trace.append_separated([\
                      "# set color bar visibility", "%s.Visibility = %s" % (\
                    smtrace.Trace.get_accessor(rep), rep.Visibility)])

            for rep in view_representations:
                try:
                    producer = rep.Input
                    port = rep.Input.Port

                    if rep.IsScalarBarVisible(view):
                        # FIXME: this will save this multiple times, right now,
                        # if two representations use the same LUT.
                        trace.append_separated([\
                            "# show color legend",
                            "%s.SetScalarBarVisibility(%s, True)" % (\
                                smtrace.Trace.get_accessor(rep),
                                smtrace.Trace.get_accessor(view))])

                    if not rep.Visibility:
                        traceitem = smtrace.Hide(producer, port, view)
                        traceitem.finalize()
                        del traceitem
                        trace.append_separated(
                            smtrace.get_current_trace_output_and_reset(
                                raw=True))

                except AttributeError:
                    pass

    #--------------------------------------------------------------------------
    # Now, trace the transfer functions (color maps and opacity maps) used.
    ctfs = set([x for x in proxies_of_interest \
        if smtrace.Trace.get_registered_name(x, "lookup_tables")])
    if ctfs:
        trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# setup color maps and opacity mapes used in the visualization",
            "# note: the Get..() functions create a new object, if needed",
            "# ----------------------------------------------------------------"])
        for ctf in ctfs:
            smtrace.Trace.get_accessor(ctf)
            if ctf.ScalarOpacityFunction in proxies_of_interest:
                smtrace.Trace.get_accessor(ctf.ScalarOpacityFunction)
        trace.append_separated(
            smtrace.get_current_trace_output_and_reset(raw=True))

    # restore the active source since the order in which the pipeline is created
    # in the state file can end up changing the active source to be different
    # than what it was when the state is being saved.
    trace.append_separated([\
            "# ----------------------------------------------------------------",
            "# finally, restore active source",
            "SetActiveSource(%s)" % smtrace.Trace.get_accessor(simple.GetActiveSource()),
            "# ----------------------------------------------------------------"])
    del trace_config
    smtrace.stop_trace()
    #print (trace)
    return str(trace) if not raw else trace.raw_data()
Ejemplo n.º 4
0
def gen_screenshot(state, dest=OUTPUT_DIR):
    for i, view in enumerate(simple.GetViews()):
        simple.SaveScreenshot(f"{dest}/{state.stem}_{i}.png", view)
        print(f"{state}: view #{i} saved")
    simple.ResetSession()
Ejemplo n.º 5
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
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
def RequestData():
    # R.0.2018.080
    import sys
    sys.path.insert(0, "EMC_SRC_PATH")
    from datetime import datetime
    import numpy as np
    from vtk.numpy_interface import dataset_adapter as dsa
    from vtk.util import numpy_support
    import IrisEMC_Paraview_Lib as lib
    import paraview.simple as simple

    views = simple.GetViews(viewtype="SpreadSheetView")
    if len(views) > 0:
       simple.Delete(views[0])
    else:
       view = simple.GetActiveView()
       layout = simple.GetLayout(view)
       locationId = layout.SplitViewVertical(view=view ,fraction=0.7)

    myId    = simple.GetActiveSource().Input.GetGlobalIDAsString()
    proxies = simple.GetSources()
    proxyList = []
    for key in proxies:
       listElt = {}
       listElt['name'] = key[0]
       listElt['id'] = key[1]
       proxy = proxies[key]
       parentId = '0'
       if hasattr(proxy, 'Input'):
           parentId = proxy.Input.GetGlobalIDAsString()
       listElt['parent'] = parentId
       proxyList.append(listElt)


    pdi = self.GetInput() # VTK PolyData Type
    np = pdi.GetNumberOfPoints()
    depthMin = 9999999999999.0
    depthMax = -9999999999999.0
    latitude  = {}
    longitude = {}

    pdo = self.GetOutput() # VTK Table Type
    polyData  = vtk.vtkPolyData()
    dataPoints = vtk.vtkPoints()

    if len(Label.strip()) <= 0:
         pid = simple.GetActiveSource().Input.GetGlobalIDAsString()
         proxies = simple.GetSources()
         for key in proxies:
             if key[1] == pid:
                 Label = " ".join(["Coordinates View:",key[0]])
                 break
    for i in range(np):
        point = pdi.GetPoints().GetPoint(i)
        (lat,lon,depth) = lib.xyz2llz(point[0],point[1],point[2])
        dataPoints.InsertNextPoint((lat,lon,depth))
        key = "%0.1f"%(depth)
        if depthMin >= float(key):
           depthMin = float(key)
           depthMinKey = key
        if depthMax <= float(key):
           depthMax = float(key)
           depthMaxKey = key
        if key not in latitude.keys():
            latitude[key] =[]
            longitude[key] = []
        latitude[key].append(float("%0.1f"%(lat)))
        longitude[key].append(float("%0.1f"%(lon)))

    # store boundary metadata

    fieldData = polyData.GetFieldData()
    fieldData.AllocateArrays(3) # number of fields

    depthData = vtk.vtkStringArray()
    depthData.SetName('Depth\n(km)')

    data = vtk.vtkStringArray()
    data.SetName('Corners (lat,lon)\n(degrees)')

    depthKeys = [depthMinKey,depthMaxKey]
    if depthMinKey == depthMaxKey:
        depthKeys = [depthMinKey]
    for i in range(len(depthKeys)):
       depthKey = depthKeys[i]
       borderLat = []
       borderLon = []
       oldMin = 999999999.0
       oldMax = -99999999.0
       lonList = list(set(sorted(longitude[depthKey])))
       for j in range(len(lonList)):
          lon = lonList[j]
          minVal = 999999999.0
          maxVal = -99999999.0
          for i in range(len(longitude[depthKey])):
             if longitude[depthKey][i] == lon:
                if latitude[depthKey][i] > maxVal:
                  maxVal = latitude[depthKey][i]
                if latitude[depthKey][i] < minVal:
                  minVal = latitude[depthKey][i]
          if oldMin != minVal or j==len(lonList)-1:
             if abs(oldMin) < 9999.0:
                borderLat.append(oldMin)
                borderLon.append(lon)
             borderLat.append(minVal)
             borderLon.append(lon)
             oldMin = minVal
          if oldMax != maxVal or j==len(lonList)-1:
             if abs(oldMax) < 9999.0:
                borderLat.append(oldMax)
                borderLon.append(lon)
             borderLat.append(maxVal)
             borderLon.append(lon)
             oldMax = maxVal
       borderList = zip(borderLat, borderLon)
       borderList.sort()
       borderList = list(set(borderList))
       min1 = borderList[0][0]
       max1 = borderList[0][0]
       for i in range(len(borderList)):
          if borderList[i][0] < min1:
             min1 = borderList[i][0]
          if borderList[i][0] > max1:
             max1 = borderList[i][0]
       minList = []
       maxList = []
       for i in range(len(borderList)):
          if borderList[i][0] ==  min1:
             minList.append(borderList[i][1])
          if borderList[i][0] ==  max1:
             maxList.append(borderList[i][1])
       depthData.InsertNextValue(depthKey)
       data.InsertNextValue("%0.1f, %0.1f"%(min1,min(minList)))
       if min(minList) != max(minList):
          depthData.InsertNextValue(" ")
          data.InsertNextValue("%0.1f, %0.1f"%(min1,max(minList)))
       depthData.InsertNextValue(" ")
       data.InsertNextValue("%0.1f, %0.1f"%(max1,max(maxList)))
       if min(maxList) != max(maxList):
         depthData.InsertNextValue(" ")
         data.InsertNextValue("%0.1f, %0.1f"%(max1,min(maxList)))
    fieldData.AddArray(data)
    fieldData.AddArray(depthData)

    if len(Label.strip()) > 0:
        simple.RenameSource(Label)

    pdo.SetFieldData(fieldData)
def RequestData():
    # R.0.2018.080
    import sys
    import numpy as np
    import os
    import paraview.simple as simple
    sys.path.insert(0, "EMC_SRC_PATH")
    import IrisEMC_Paraview_Lib as lib

    views = simple.GetViews(viewtype="SpreadSheetView")
    if len(views) > 0:
        simple.Delete(views[0])
    else:
        view = simple.GetActiveView()
        layout = simple.GetLayout(view)
        locationId = layout.SplitViewVertical(view=view, fraction=0.7)

    pdo = self.GetOutput()  # vtkTable

    if Coordinate_Type == 0:
        lon = X_or_Longitude
        lat = Y_or_Latitude
        depth = Z_or_Depth
        x, y, z = lib.llz2xyz(lat, lon, depth)
    else:
        x = X_or_Longitude
        y = Y_or_Latitude
        z = Z_or_Depth
        lat, lon, depth = lib.xyz2llz(x, y, z)

    # VTK arrays for columns
    #name = vtk.vtkStringArray()
    #name.SetNumberOfComponents(1)
    #name.SetNumberOfTuples(6)
    #name.SetName("Component Name")
    #name.InsertNextValue("X")
    #name.InsertNextValue("Y")
    #name.InsertNextValue("Z")
    #name.InsertNextValue("Latitude")
    #name.InsertNextValue("Longitude")
    #name.InsertNextValue("Depth")
    #pdo.Array(name)

    # store metadata
    fieldData = pdo.GetFieldData()
    fieldData.AllocateArrays(3)  # number of fields

    fieldData = pdo.GetFieldData()
    data = vtk.vtkFloatArray()
    data.SetName('Longitude, Latitude, Depth')
    data.InsertNextValue(lon)
    data.InsertNextValue(lat)
    data.InsertNextValue(depth)
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('X, Y, Z')
    data.InsertNextValue(x)
    data.InsertNextValue(y)
    data.InsertNextValue(z)
    fieldData.AddArray(data)

    pdo.SetFieldData(fieldData)
def RequestData():
    # R.1.2018.354
    import sys
    sys.path.insert(0, "EMC_SRC_PATH")
    from operator import itemgetter
    from datetime import datetime
    import numpy as np
    from vtk.numpy_interface import dataset_adapter as dsa
    from vtk.util import numpy_support
    import IrisEMC_Paraview_Lib as lib
    import paraview.simple as simple

    views = simple.GetViews(viewtype="SpreadSheetView")
    if len(views) > 0:
        # set active view
        view = simple.SetActiveView(views[0])
    else:
        view = simple.GetActiveView()
        layout = simple.GetLayout(view)
        location_id = layout.SplitViewVertical(view=view, fraction=0.7)

    myId = simple.GetActiveSource().Input.GetGlobalIDAsString()

    proxies = simple.GetSources()
    proxyList = []
    for key in proxies:
        list_elt = dict()
        list_elt['name'] = key[0]
        list_elt['id'] = key[1]
        proxy = proxies[key]
        parent_id = '0'
        if hasattr(proxy, 'Input'):
            parent_id = proxy.Input.GetGlobalIDAsString()
        list_elt['parent'] = parent_id
        proxyList.append(list_elt)

    pdi = self.GetInput()  # VTK PolyData Type
    try:
        np = pdi.GetNumberOfPoints()
    except Exception:
        raise Exception('Invalid input!')

    na = pdi.GetPointData().GetNumberOfArrays()
    val_arrays = []
    for i in range(na):
        val_arrays.append(pdi.GetPointData().GetArray(i))

    latitude = {}
    longitude = {}
    value = {}
    depth = {}
    pdo = self.GetOutput()  # VTK Table Type
    poly_data = vtk.vtkPolyData()
    data_points = vtk.vtkPoints()

    if len(Label.strip()) <= 0:
        pid = simple.GetActiveSource().Input.GetGlobalIDAsString()
        proxies = simple.GetSources()
        for key in proxies:
            if key[1] == pid:
                Label = " ".join(["Coordinates:", key[0]])
                break
    for i in range(np):
        point = pdi.GetPoints().GetPoint(i)
        (lat, lon, this_depth) = lib.xyz2llz(point[0], point[1], point[2])
        data_points.InsertNextPoint((lat, lon, this_depth))
        key = "%0.2f" % this_depth
        if key not in list(latitude.keys()):
            latitude[key] = []
            longitude[key] = []
            value[key] = []

        # need to control precision to have a reasonable sort order
        # note that these coordinates are recomputed
        if key not in list(depth.keys()):
            depth[key] = float('%0.4f' % this_depth)
        latitude[key].append(float('%0.4f' % lat))
        longitude[key].append(float('%0.4f' % lon))
        value_array = []
        for j in range(na):
            value_array.append(float(val_arrays[j].GetTuple1(i)))
        value[key].append(value_array)

    # store boundary metadata
    field_data = poly_data.GetFieldData()
    field_data.AllocateArrays(5)  # number of fields

    depth_data = vtk.vtkFloatArray()
    depth_data.SetName('depth')

    lat_data = vtk.vtkFloatArray()
    lat_data.SetName('latitude')

    lon_data = vtk.vtkFloatArray()
    lon_data.SetName('longitude')

    val_data = []
    for j in range(na):
        val_data.append(vtk.vtkFloatArray())
        val_data[j].SetName('value(%s)' %
                            pdi.GetPointData().GetArray(j).GetName())

    depth_keys = list(latitude.keys())

    for i in range(len(depth_keys)):
        depth_key = depth_keys[i]
        lon_list = longitude[depth_key]
        lat_list = latitude[depth_key]
        val_list = value[depth_key]
        point_list = list(zip(lat_list, lon_list, val_list))
        point_list.sort(key=itemgetter(0, 1))

        for index, data in enumerate(point_list):
            depth_data.InsertNextValue(float(depth[depth_key]))
            lat_data.InsertNextValue(float(data[0]))
            lon_data.InsertNextValue(float(data[1]))
            for k in range(na):
                point_data = data[2]
                val_data[k].InsertNextValue(point_data[k])

    field_data.AddArray(lat_data)
    field_data.AddArray(lon_data)
    field_data.AddArray(depth_data)
    for j in range(na):
        field_data.AddArray(val_data[j])

    if len(Label.strip()) > 0:
        simple.RenameSource(Label)

    pdo.SetFieldData(field_data)