Beispiel #1
0
def tick(self):
	""" function called at each timestep """
	view = smp.GetActiveView()

	# lidar orientation and position
	R_l = self.orientations[self.i]
	T_l = self.pts[self.i, :]

	# move camera
	for c in self.cameras:
		if c.timestep_inside_range(self.i):
			print c.type
			view.CameraPosition = c.interpolate_position(self.i, R_l, T_l, np.asarray(list(view.CameraPosition)))
			view.CameraFocalPoint = c.interpolate_focal_point(self.i, R_l, T_l)
			view.CameraViewUp = c.interpolate_up_vector(self.i, R_l)
			break

	# move 3d model (vtk Transform rotation are angle axis in degrees)
	if self.model is not None:
		self.model.Transform.Translate = self.pts[self.i, :3]
		o = R_l.as_rotvec()
		angle_rad = np.linalg.norm(o)
		angle_deg = np.rad2deg(angle_rad)
		self.model.Transform.Rotate = o * angle_deg / angle_rad

	smp.Render()

	# save frame
	if len(frames_output_dir) > 0:
		imageName = os.path.join(frames_output_dir, "image_%04d.png" % (self.image_index))
		smp.WriteImage(imageName)

	self.image_index += 1
	self.i += 1
Beispiel #2
0
def getRenameMap():
    renameMap = {}
    names = getAllNames()
    view = simple.GetActiveView()
    renderer = view.GetClientSideObject().GetRenderer()
    viewProps = renderer.GetViewProps()
    volumes = renderer.GetVolumes()
    idx = 1
    for viewProp in viewProps:
        if not viewProp.IsA('vtkActor'):
            continue
        if not viewProp.GetVisibility():
            continue
        bounds = viewProp.GetBounds()
        if bounds[0] > bounds[1]:
            continue
        # The mapping will fail for multiblock that are composed of several blocks
        # Merge block should be used to solve the renaming issue for now
        # as the id is based on the a valid block vs representation.
        strIdx = '%s' % idx
        renameMap[strIdx] = findName(names, viewProp, strIdx)
        idx += 1
    for volume in volumes:
        if not volume.IsA('vtkVolume'):
            continue
        if not volume.GetVisibility():
            continue
        bounds = volume.GetBounds()
        if bounds[0] > bounds[1]:
            continue
        strIdx = '%s' % idx
        renameMap[strIdx] = findName(names, volume, strIdx)
        idx += 1

    return renameMap
Beispiel #3
0
    def init_view(self):
        pasi.SetActiveView(pasi.GetRenderView())
        if paraview_loaded:
            camera = pasi.GetActiveCamera()
            self.camera = camera
            # cm = CameraMover(camera)
            print("Camera loaded")

            if self.view_size is not None:
                pasi.GetActiveView().ViewSize = self.view_size
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)
    def getView(self, vid):
        """
        Returns the view for a given view ID, if vid is None then return the
        current active view.
        :param vid: The view ID
        :type vid: str
        """
        view = self.mapIdToProxy(vid)
        if not view:
            # Use active view is none provided.
            view = simple.GetActiveView()
        if not view:
            raise Exception("no view provided: " + vid)

        return view
Beispiel #6
0
def animate(fn):
    casefoam = pv.OpenFOAMReader(FileName=fn)
    pv.Show(casefoam)
    dp = pv.GetDisplayProperties(casefoam)
    dp.SetPropertyWithName('ColorArrayName', ['POINTS', 'U'])
    view = pv.GetActiveView()
    reader = pv.GetActiveSource()
    tsteps = reader.TimestepValues
    annTime = pv.AnnotateTimeFilter(reader)
    pv.Show(annTime)
    pv.Render()
    while True:
        try:
            for t in tsteps:
                view.ViewTime = t
                pv.Render()
        except KeyboardInterrupt:
            sys.exit(0)
Beispiel #7
0
def getRenameMap():
    renameMap = {}
    names = getAllNames()
    view = simple.GetActiveView()
    renderer = view.GetClientSideObject().GetRenderer()
    viewProps = renderer.GetViewProps()
    volumes = renderer.GetVolumes()
    idx = 1
    for viewProp in viewProps:
        if not viewProp.IsA("vtkActor"):
            continue
        if not viewProp.GetVisibility():
            continue
        # The mapping will fail for multiblock that are composed of several blocks
        # Merge block should be used to solve the renaming issue for now
        # as the id is based on the a valid block vs representation.
        strIdx = "%s" % idx
        # Prop is valid if we can find it in the current sources
        for name, actor in names.items():
            if viewProp == actor:
                renameMap[strIdx] = name
                idx += 1
                break

    for volume in volumes:
        if not volume.IsA("vtkVolume"):
            continue
        if not volume.GetVisibility():
            continue
        strIdx = "%s" % idx
        for name, actor in names.items():
            if viewProp == actor:
                renameMap[strIdx] = name
                idx += 1
                break

    return renameMap
def RequestData():
    # R.0.2018.080
    import sys
    sys.path.insert(0, "EMC_SRC_PATH")
    import paraview.simple as simple
    import numpy as np
    import csv
    import os
    from vtk.util import numpy_support as nps
    import IrisEMC_Paraview_Lib as lib
    import urlparse

    Label = ''

    pts = vtk.vtkPoints()

    # make sure we have input files
    query = lib.volcanoLocationsQuery
    if len(Alternate_FileName) <= 0:
        volcanoFile = lib.query2fileName(query)
        query = '?'.join([lib.volcanoLocationsKeys[Data_Source], query])
        fileFound, address, source = lib.findFile(volcanoFile,
                                                  loc='EMC_VOLCANOES_PATH',
                                                  query=query)
        Label = ' '.join([
            lib.volcanoLocationsValues[Data_Source].strip(), 'from',
            urlparse.urlparse(
                lib.volcanoLocationsKeys[Data_Source]).netloc.strip()
        ])
    else:
        fileFound, address, source = lib.findFile(Alternate_FileName,
                                                  loc='EMC_VOLCANOES_PATH')

    if not fileFound:
        raise Exception(
            'volcano file "' + address +
            '" not found! Please provide the full path or UR for the file. Aborting.'
        )
    (params, lines) = lib.readGcsv(address)

    Latitude_Begin, Latitude_End, Longitude_Begin, Longitude_End = lib.getArea(
        Area, Latitude_Begin, Latitude_End, Longitude_Begin, Longitude_End)
    Label2 = " - %s (lat:%0.1f,%0.1f, lon:%0.1f,%0.1f)" % (
        lib.areaValues[Area], Latitude_Begin, Latitude_End, Longitude_Begin,
        Longitude_End)

    pdo = self.GetOutput()  # vtkPoints
    count = 0
    latIndex = 0
    lonIndex = 1

    column_keys = lib.columnKeys
    for key in lib.columnKeys.keys():
        if key in params.keys():
            column_keys[key] = params[key]

    delimiter = params['delimiter'].strip()

    origin = None
    if 'source' in params:
        origin = params['source']
        if len(Label.strip()) <= 0:
            Label = origin
    header = lines[0].strip()
    fields = header.split(delimiter)
    for i in range(len(fields)):
        if fields[i].strip().lower() == column_keys['longitude_column'].lower(
        ):
            lonIndex = i
        elif fields[i].strip().lower() == column_keys['latitude_column'].lower(
        ):
            latIndex = i
        elif fields[i].strip().lower(
        ) == column_keys['elevation_column'].lower():
            elevIndex = i
    for i in range(1, len(lines)):
        line = lines[i].strip()
        values = line.strip().split(params['delimiter'].strip())
        try:
            lat = float(values[latIndex])
            lon = float(values[lonIndex])
        except:
            continue
        if len(values[elevIndex].strip()) <= 0:
            depth = 0.0
        else:
            try:
                depth = -1 * float(values[elevIndex]) / 1000.0
            except:
                continue
        if lat >= Latitude_Begin and lat <= Latitude_End and lon >= Longitude_Begin and lon <= Longitude_End:
            x, y, z = lib.llz2xyz(lat, lon, depth)
            pts.InsertNextPoint(x, y, z)
    pdo.SetPoints(pts)

    done = False
    simple.RenameSource(' '.join(
        ['Volcano locations:',
         Label.strip(), Label2.strip()]))

    view = simple.GetActiveView()

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

    data = vtk.vtkFloatArray()
    data.SetName('Latitude\nRange (deg)')
    data.InsertNextValue(Latitude_Begin)
    data.InsertNextValue(Latitude_End)
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('Longitude\nRange (deg)')
    data.InsertNextValue(Longitude_Begin)
    data.InsertNextValue(Longitude_End)
    fieldData.AddArray(data)

    data = vtk.vtkStringArray()
    data.SetName('Source')
    if origin is not None:
        data.InsertNextValue(origin)

    data.InsertNextValue(source)
    fieldData.AddArray(data)

    pdo.SetFieldData(fieldData)
Beispiel #9
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()
    else:
        sceneName = args[1]
    # arg 2 shoud be compression prefernece
    doCompressArrays = args[2]




# Generate timestamp and use it to make subdirectory within the top level output dir
timeStamp = time.strftime("%a-%d-%b-%Y-%H-%M-%S")
outputDir = os.path.join(ROOT_OUTPUT_DIRECTORY, timeStamp)
mkdir_p(outputDir)


# Get the active view and render window, use it to iterate over renderers
activeView = simple.GetActiveView()
renderWindow = activeView.GetRenderWindow()
renderers = renderWindow.GetRenderers()

scDirs = []
sceneComponents = []
textureToSave = {}

for rIdx in range(renderers.GetNumberOfItems()):
  renderer = renderers.GetItemAsObject(rIdx)
  renProps = renderer.GetViewProps()
  for rpIdx in range(renProps.GetNumberOfItems()):
    renProp = renProps.GetItemAsObject(rpIdx)
    if not renProp.GetVisibility():
      continue
    if hasattr(renProp, 'GetMapper'):
Beispiel #11
0
def export_scene(baseDirName, viewSelection, trackSelection):
    '''This explores a set of user-defined views and tracks. export_scene is
    called from vtkCinemaExport.  The expected order of parameters is as follows:

    - viewSelection (following the format defined in Wrapping/Python/paraview/cpstate.py):

    Directory  of the form {'ViewName' : [parameters], ...}, with parameters defined in the
    order:  Image filename, freq, fittoscreen, magnification, width, height, cinema).

    - trackSelection:

    Directory of the form {'TrackName' : [v1, v2, v3], ...}

    Note:  baseDirName is used as the parent directory of the database generated for
    each view in viewSelection. 'Image filename' is used as the database directory name.
    '''

    import paraview.simple as pvs

    # save initial state
    initialView = pvs.GetActiveView()
    pvstate = record_visibility()

    atLeastOneViewExported = False
    for viewName, viewParams in viewSelection.iteritems():

        # check if this view was selected to export as spec b
        cinemaParams = viewParams[6]
        if len(cinemaParams) == 0:
            print "Skipping view: Not selected to export as cinema spherical."
            continue

        # get the view and save the initial status
        view = pvs.FindView(viewName)
        pvs.SetActiveView(view)
        view.ViewSize = [viewParams[4], viewParams[5]]
        pvs.Render() # fully renders the scene (if not, some faces might be culled)
        view.LockBounds = 1

        #writeFreq = viewParams[1] # TODO where to get the timestamp in this case?
        #if (writeFreq and timestamp % writeFreq == 0):

        #magnification = viewParams[3] # Not used in cinema (TODO hide in UI)

        fitToScreen = viewParams[2]
        if fitToScreen != 0:
            if view.IsA("vtkSMRenderViewProxy") == True:
                view.ResetCamera()
            elif view.IsA("vtkSMContextViewProxy") == True:
                view.ResetDisplay()
            else:
                print ' do not know what to do with a ', view.GetClassName()

        userDefValues = {}
        if "theta" in cinemaParams:
            userDefValues["theta"] = cinemaParams["theta"]

        if "phi" in cinemaParams:
            userDefValues["phi"] = cinemaParams["phi"]

        userDefValues.update(trackSelection)

        # generate file path
        import os.path
        viewFileName = viewParams[0]
        viewDirName = viewFileName[0:viewFileName.rfind("_")] #strip _num.ext
        filePath = os.path.join(baseDirName, viewDirName, "info.json")

        p = inspect()
        cs = make_cinema_store(p, filePath, forcetime = False,
          _userDefinedValues = userDefValues)

        explore(cs, p)

        view.LockBounds = 0
        cs.save()
        atLeastOneViewExported = True

    if not atLeastOneViewExported:
        print "No view was selected to export as cinema spherical."
        return

    # restore initial state
    pvs.SetActiveView(initialView)
    restore_visibility(pvstate)
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)
Beispiel #13
0
def RequestData():
    # V.2019.014
    import sys
    sys.path.insert(0, r'EMC_SRC_PATH')
    import paraview.simple as simple
    import numpy as np
    import csv
    import os
    from vtk.util import numpy_support as nps
    import IrisEMC_Paraview_Lib as lib
    import urllib.parse

    Label = ''

    pts = vtk.vtkPoints()

    # make sure we have input files
    if len(File_name.strip()) <= 0:
        fileFound = False
        address = ''
    else:
        fileFound, address, source = lib.find_file(File_name.strip(),
                                                   loc=r'EMC_VOLCANOES_PATH')

    if not fileFound:
        raise Exception(
            'volcano file "' + address +
            '" not found! Please provide the full path or UR for the file. Aborting.'
        )
    (params, lines) = lib.read_geocsv(address)

    Latitude_Begin, Latitude_End, Longitude_Begin, Longitude_End = lib.get_area(
        Area, Latitude_Begin, Latitude_End, Longitude_Begin, Longitude_End)
    Label2 = " - %s (lat:%0.1f,%0.1f, lon:%0.1f,%0.1f)" % (
        lib.areaValues[Area], Latitude_Begin, Latitude_End, Longitude_Begin,
        Longitude_End)

    pdo = self.GetOutput()  # vtkPoints
    lat_index = 0
    lon_index = 1

    column_keys = lib.columnKeys
    for key in list(lib.columnKeys.keys()):
        if key in list(params.keys()):
            column_keys[key] = params[key]

    delimiter = params['delimiter'].strip()

    origin = None
    if 'source' in params:
        origin = params['source']
        if len(Label.strip()) <= 0:
            Label = origin

    fields = params['header']
    for i in range(len(fields)):
        if fields[i].strip().lower() == column_keys['longitude_column'].lower(
        ):
            lon_index = i
        elif fields[i].strip().lower() == column_keys['latitude_column'].lower(
        ):
            lat_index = i
        elif fields[i].strip().lower(
        ) == column_keys['elevation_column'].lower():
            elev_index = i

    for i, line in enumerate(lines):
        line = line.strip()
        values = line.split(delimiter)
        try:
            lat = float(values[lat_index])
            lon = float(values[lon_index])
        except:
            continue
        if len(values[elev_index].strip()) <= 0:
            depth = 0.0
        else:
            try:
                depth = -1 * float(values[elev_index]) / 1000.0
            except:
                continue
        if Latitude_Begin <= lat <= Latitude_End and Longitude_Begin <= lon <= Longitude_End:
            x, y, z = lib.llz2xyz(lat, lon, depth)
            pts.InsertNextPoint(x, y, z)
    pdo.SetPoints(pts)

    simple.RenameSource(' '.join(
        ['Volcano locations:',
         Label.strip(), Label2.strip()]))

    view = simple.GetActiveView()

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

    data = vtk.vtkFloatArray()
    data.SetName('Latitude\nRange (deg)')
    data.InsertNextValue(Latitude_Begin)
    data.InsertNextValue(Latitude_End)
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('Longitude\nRange (deg)')
    data.InsertNextValue(Longitude_Begin)
    data.InsertNextValue(Longitude_End)
    fieldData.AddArray(data)

    data = vtk.vtkStringArray()
    data.SetName('Source')
    if origin is not None:
        data.InsertNextValue(origin)

    data.InsertNextValue(source)
    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)
Beispiel #15
0
def Save_PV_data_to_picture_file(inputFileName, field_name,
                             node_or_cell,outputFileName
                             ):
    pvs._DisableFirstRenderCameraReset()

    #pvs.HideAll(view=None)#Not available in paraview 5.1.2
    view = pvs.GetActiveView()
    sources = pvs.GetSources().values()
    for aSource in sources:
        pvs.Hide(aSource, view)

    # create a new 'XML Unstructured Grid Reader'
    reader = pvs.XMLUnstructuredGridReader(FileName=[inputFileName])
    if node_or_cell== 'CELLS':
        reader.CellArrayStatus = [field_name]
    elif node_or_cell== 'NODES':
        reader.PointArrayStatus = [field_name]
    else:
        raise ValueError("unknown type : should be CELLS or NODES")
        
    # get active view
    renderView1 = pvs.GetActiveViewOrCreate('RenderView')
    # uncomment following to set a specific view size
    # renderView1.ViewSize = [1057, 499]

    # show data in view
    display = pvs.Show(reader, renderView1);
    # trace defaults for the display properties.
    display.ColorArrayName = [None, '']
    display.GlyphType = 'Arrow'
    display.ScalarOpacityUnitDistance = 0.02234159571242408

    # reset view to fit data
    renderView1.ResetCamera()

    # set scalar coloring
    if node_or_cell== 'CELLS':
        pvs.ColorBy(display, ('CELLS', field_name))
    elif node_or_cell== 'NODES':
        pvs.ColorBy(display, ('POINTS', field_name))
    else:
        raise ValueError("unknown type : should be CELLS or NODES")

    # rescale color and/or opacity maps used to include current data range
    display.RescaleTransferFunctionToDataRange(True)

    # show color bar/color legend
    display.SetScalarBarVisibility(renderView1, True)

    pvs.SaveScreenshot(outputFileName+".png", magnification=1, quality=100, view=renderView1)
    display.SetScalarBarVisibility(renderView1, False)

    if field_name=='Velocity' :
        #pvs.HideAll(view=None)#Not available in paraview 5.1.2
        view = pvs.GetActiveView()
        sources = pvs.GetSources().values()
        for aSource in sources:
            pvs.Hide(aSource, view)
        # create a new 'Stream Tracer'
        streamTracer1 = pvs.StreamTracer(Input=reader, SeedType='Point Source')
        streamTracer1.Vectors = ['CELLS', 'Velocity']
        
        # init the 'Point Source' selected for 'SeedType'
        streamTracer1.SeedType.Center = [0.5, 0.5, 0.0]
        streamTracer1.SeedType.Radius = 0.0
        
        # Properties modified on streamTracer1
        streamTracer1.SeedType = 'High Resolution Line Source'
        
        # Properties modified on streamTracer1.SeedType
        streamTracer1.SeedType.Point1 = [0.0, 0.0, 0.0]
        streamTracer1.SeedType.Point2 = [1.0, 1.0, 0.0]
        streamTracer1.SeedType.Resolution = 20# Pb : claims attribute Resolution does not exist

        # show data in view
        streamTracer1Display = pvs.Show(streamTracer1, renderView1)
        
        # create a new 'Stream Tracer'
        streamTracer2 = pvs.StreamTracer(Input=reader, SeedType='Point Source')
        streamTracer2.Vectors = ['CELLS', 'Velocity']
        
        # init the 'Point Source' selected for 'SeedType'
        streamTracer2.SeedType.Center = [0.5, 0.5, 0.0]
        streamTracer2.SeedType.Radius = 0.0
        
        # Properties modified on streamTracer2
        streamTracer2.SeedType = 'High Resolution Line Source'
        
        # Properties modified on streamTracer2.SeedType
        streamTracer2.SeedType.Point1 = [0.0, 1.0, 0.0]
        streamTracer2.SeedType.Point2 = [1.0, 0.0, 0.0]
        streamTracer2.SeedType.Resolution = 25# Pb : claims attribute Resolution does not exist
        
        # show data in view
        streamTracer2Display = pvs.Show(streamTracer2, renderView1)

        pvs.SaveScreenshot(outputFileName+"_streamlines.png", magnification=1, quality=100, view=renderView1)
    
    pvs.Delete()
Beispiel #16
0
def start_cue(self):
	""" function called at the beginning of the animation """
	self.image_index = 0	# image index

	# setup view parameters
	view = smp.GetActiveView()
	view.CameraParallelProjection = CameraParallelProjection
	view.Background = Background
	view.Background2 = Background2
	view.UseGradientBackground = UseGradientBackground
	view.CameraViewAngle = CameraViewAngle

	# setup initial opacity
	frames = smp.FindSource(pointclouds_name)
	self.frames_repr = smp.Show(frames)
	self.frames_repr.Opacity = opacity

	# get trajectory positions and orientations
	trajectory = smp.FindSource(trajectory_name)
	traj = trajectory.GetClientSideObject().GetOutput()
	self.pts = numpy_support.vtk_to_numpy(traj.GetPoints().GetData()).copy()

	# convert veloview axis angle to scipy Rotation
	orientations_data = traj.GetPointData().GetArray("Orientation(AxisAngle)")
	orientations = numpy_support.vtk_to_numpy(orientations_data).copy()
	axis = orientations[:, :3]
	angles = orientations[:, 3].reshape((-1, 1))
	axis_angles = axis * angles
	self.orientations = [Rotation.from_rotvec(a) for a in axis_angles]


	# get the 3D model
	self.model = None
	if len(cad_model_name) > 0:
		self.model = smp.FindSource(cad_model_name)


	# get all available timesteps and find the index corresponding to the start time
	time = view.ViewTime
	source_frames = smp.FindSource(temporal_source_name)
	timesteps = list(source_frames.TimestepValues)
	self.i = np.argmin(np.abs(np.asarray(timesteps) - time))
	print "Start timestep: ", self.i



# -----------------------------TO MODIFY--------------------------------------
	# Camera path definition (need to be specified)
	# This is an example, you can define your custom camera path
	c1 = FirstPersonView(self.i, self.i+40, focal_point=[0, 0, 1])

	c2 = FixedPositionView(self.i+40, self.i+100)
	c2.set_transition(c1, 5, "s-shape")		# transition from c1

	c3 = AbsoluteOrbit(self.i+100, self.i+200,
						center=[99.65169060331509, 35.559305816556, 37.233268868598536],
						up_vector=[0, 0, 1.0],
						initial_pos = [85.65169060331509, 35.559305816556, 37.233268868598536],
						focal_point=[99.65169060331509, 35.559305816556, 7.233268868598536])
	c3.set_transition(c2, 20, "s-shape")

	c4 = ThirdPersonView(self.i+200, self.i+280)
	c4.set_transition(c3, 20, "s-shape")

	c5 = RelativeOrbit(self.i+280, self.i+350, up_vector=[0, 0, 1.0], initial_pos = [0.0, -10, 10])
	c5.set_transition(c4, 20, "square")

	self.cameras = [c1, c2, c3, c4, c5]
Beispiel #17
0
def RequestData():
    # R.0.2018.120
    import sys
    sys.path.insert(0, "EMC_SRC_PATH")
    import paraview.simple as simple
    import numpy as np
    import csv
    import os
    from vtk.util import numpy_support as nps
    import IrisEMC_Paraview_Lib as lib
    import urlparse

    Label = ''

    pts = vtk.vtkPoints()
    Latitude_Begin, Latitude_End, Longitude_Begin, Longitude_End = lib.getArea(
        Area, Latitude_Begin, Latitude_End, Longitude_Begin, Longitude_End)
    Label2 = " - %s (lat:%0.1f,%0.1f, lon:%0.1f,%0.1f, depth:%0.1f-%0.1f)" % (
        lib.areaValues[Area], Latitude_Begin, Latitude_End, Longitude_Begin,
        Longitude_End, Depth_Begin, Depth_End)

    # make sure we have input files
    query = lib.earthquakeQuery % (Start_Time, Magnitude_Begin, Magnitude_End,
                                   Depth_Begin, Depth_End, Latitude_Begin,
                                   Latitude_End, Longitude_Begin,
                                   Longitude_End, Max_Count)
    if len(Alternate_FileName) <= 0:
        eqFile = lib.query2fileName(query, url=lib.earthquakeKeys[Data_Source])
        query = '?'.join([lib.earthquakeKeys[Data_Source], query])
        fileFound, address, source = lib.findFile(eqFile,
                                                  loc='EMC_EARTHQUAKES_PATH',
                                                  query=query)
    else:
        fileFound, address, source = lib.findFile(Alternate_FileName,
                                                  loc='EMC_EARTHQUAKES_PATH')
    if not fileFound:
        raise Exception(
            'earthquake catalog file "' + address +
            '" not found! Please provide the full path or UR for the file. Aborting.'
        )
    (params, lines) = lib.readGcsv(address)

    pdo = self.GetOutput()  # vtkPoints
    column_keys = lib.columnKeys
    for key in lib.columnKeys.keys():
        if key in params.keys():
            column_keys[key] = params[key]

    delimiter = params['delimiter'].strip()
    origin = None
    if 'source' in params:
        origin = params['source']
        Label = urlparse.urlparse(origin).netloc
    else:
        try:
            Label = urlparse.urlparse(Alternate_FileName).netloc
        except:
            Label = Alternate_FileName

    header = lines[0].strip()
    fields = header.split(delimiter)
    for i in range(len(fields)):
        if fields[i].strip().lower() == column_keys['longitude_column'].lower(
        ):
            lonIndex = i
        elif fields[i].strip().lower() == column_keys['latitude_column'].lower(
        ):
            latIndex = i
        elif fields[i].strip().lower() == column_keys['depth_column'].lower():
            depthIndex = i
        elif fields[i].strip().lower(
        ) == column_keys['magnitude_column'].lower():
            magIndex = i

    scalars = vtk.vtkFloatArray()
    scalars.SetNumberOfComponents(1)
    scalars.SetName("magnitude")
    lat = []
    lon = []
    depth = []
    mag = []

    for i in range(1, len(lines)):
        line = lines[i].strip()
        values = line.strip().split(params['delimiter'].strip())
        lat.append(float(values[latIndex]))
        lon.append(float(values[lonIndex]))
        depth.append(float(values[depthIndex]))
        mag.append(float(values[magIndex]))
        if lat[-1] >= Latitude_Begin and lat[-1] <= Latitude_End and lon[
                -1] >= Longitude_Begin and lon[-1] <= Longitude_End:
            x, y, z = lib.llz2xyz(lat[-1], lon[-1], depth[-1])
            pts.InsertNextPoint(x, y, z)
            scalars.InsertNextValue(mag[-1])
    pdo.SetPoints(pts)
    pdo.GetPointData().AddArray(scalars)

    if len(Label.strip()) > 0:
        simple.RenameSource(' '.join(
            ['Earthquake locations:', 'from',
             Label.strip(),
             Label2.strip()]))

    view = simple.GetActiveView()

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

    data = vtk.vtkFloatArray()
    data.SetName('Latitude\nRange (deg)')
    data.InsertNextValue(min(lat))
    data.InsertNextValue(max(lat))
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('Longitude\nRange (deg)')
    data.InsertNextValue(min(lon))
    data.InsertNextValue(max(lon))
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('Depth\nRange (km)')
    data.InsertNextValue(min(depth))
    data.InsertNextValue(max(depth))
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('Magnitude\nRange')
    data.InsertNextValue(min(mag))
    data.InsertNextValue(max(mag))
    fieldData.AddArray(data)

    data = vtk.vtkIntArray()
    data.SetName('Max. Event\nCount')
    data.InsertNextValue(len(mag))
    fieldData.AddArray(data)

    data = vtk.vtkStringArray()
    data.SetName('Start Date')
    data.InsertNextValue(Start_Time)
    fieldData.AddArray(data)

    data = vtk.vtkStringArray()
    data.SetName('Source')
    if origin is not None:
        data.InsertNextValue(origin)

    data.InsertNextValue(source)
    fieldData.AddArray(data)

    pdo.SetFieldData(fieldData)
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)
Beispiel #19
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()
Beispiel #20
0
 def _get_active_view():
     view = simple.GetActiveView()
     if not view:
         raise Error(404, "No view provided to WebGL resource")
     return view
Beispiel #21
0
files = glob.glob(args.source_dir + "/*.vtk")
files = natural_sort(files)

jump = args.step

count = 0

files = files[::jump]  #some_list[start:stop:step]

reader = simple.OpenDataFile(files)
simple.Show(reader)
dp = simple.GetDisplayProperties(reader)
dp.Representation = 'Surface'

simple.GetActiveView().GetRenderWindow().SetSize(800, 800)
dp.LookupTable = simple.MakeBlueToRedLT(-86.2, 40.0)
dp.ColorArrayName = 'Scalars_'

camera = simple.GetActiveCamera()
camera.Elevation(args.elevation)
camera.Azimuth(args.azimuth)

simple.Render()

#simple.AnimateReader(reader, filename=video_file)
simple.SaveAnimation(video_file)

if args.images:
    os.system('ffmpeg -i ' + video_file + ' ./images/output_%04d.png')
    if not args.video: