Source code for paraview.simple

# SPDX-FileCopyrightText: Copyright (c) Kitware Inc.
# SPDX-License-Identifier: BSD-3-Clause

r"""simple is a module for using paraview server manager in Python. It
provides a simple convenience layer to functionality provided by the
C++ classes wrapped to Python as well as the servermanager module.

A simple example::

  from paraview.simple import *

  # Create a new sphere proxy on the active connection and register it
  # in the sources group.
  sphere = Sphere(ThetaResolution=16, PhiResolution=32)

  # Apply a shrink filter
  shrink = Shrink(sphere)

  # Turn the visibility of the shrink object on.
  Show(shrink)

  # Render the scene
  Render()

Scripts generated by ParaView's Python Tracing, Python state saving, and
Catalyst saving use functions in this module.
"""

from __future__ import absolute_import, division, print_function

import paraview
from paraview import servermanager
import paraview._backwardscompatibilityhelper
from paraview.modules.vtkRemotingCore import vtkPVSession

# Bring in OutputPort
from paraview.servermanager import OutputPort

# Bring in selection functions
from .selection import *

import sys
import warnings

if sys.version_info >= (3,):
    xrange = range


[docs]def GetParaViewVersion(): """:return: The version of the ParaView build in (major, minor) form. :rtype: 2-element tuple""" return paraview._version(servermanager.vtkSMProxyManager.GetVersionMajor(), servermanager.vtkSMProxyManager.GetVersionMinor())
[docs]def GetParaViewSourceVersion(): """:return: the ParaView source version string, e.g., 'paraview version x.x.x, Date: YYYY-MM-DD'. :rtype: str""" return servermanager.vtkSMProxyManager.GetParaViewSourceVersion()
# ============================================================================== # Client/Server Connection methods # ==============================================================================
[docs]def Disconnect(ns=None, force=True): """Disconnect from the currently connected server and free the active session. Does not shut down the client application where the call is executed. :param ns: Namespace in which ParaView functions were created. Optional, defaults to the namespace returned by `globals()` :type ns: Dict or `None` :param force: Force disconnection in a simultaneous connection. Optional, defaults to forcing disconnection. :type force: bool """ if not ns: ns = globals() supports_simutaneous_connections = \ servermanager.vtkProcessModule.GetProcessModule().GetMultipleSessionsSupport() if not force and supports_simutaneous_connections: # This is an internal Disconnect request that doesn't need to happen in # multi-server setup. Ignore it. return if servermanager.ActiveConnection: _remove_functions(ns) servermanager.Disconnect() import gc gc.collect()
# -----------------------------------------------------------------------------
[docs]def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111, timeout=60): """Creates a connection to a server. :param ds_host: Data server hostname. Needed to set up a client/data server/render server connection. :type ds_host: string :param ds_port: Data server port to listen on. :type ds_port: int :param rs_host: Render server hostname. Needed to set up a client/data server/render server connection. :type rs_host: string :param rs_port: Render server port to listen on. :type rs_port: int :param timeout: Time in seconds at which the connection is abandoned if not made. :type timeout: int Example usage connecting to a host named "amber":: Connect("amber") # Connect to a single server at default port Connect("amber", 12345) # Connect to a single server at port 12345 Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair Connect("amber", timeout=30) # Connect to a single server at default port with a 30s timeout instead of default 60s Connect("amber", timeout=-1) # Connect to a single server at default port with no timeout instead of default 60s Connect("amber", timeout=0) # Connect to a single server at default port without retrying instead of retrying for the default 60s """ Disconnect(globals(), False) connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port, timeout) if not (connection is None): _initializeSession(connection) _add_functions(globals()) return connection
# -----------------------------------------------------------------------------
[docs]def ReverseConnect(port=11111): """Create a reverse connection to a server. First, disconnects from any servers, then listens on port and waits for an incoming connection from the server. :param port: The port to listen on for incoming connections. :type port: int :return: Connection object :rtype: """ Disconnect(globals(), False) connection = servermanager.ReverseConnect(port) _initializeSession(connection) _add_functions(globals()) return connection
# -----------------------------------------------------------------------------
[docs]def ResetSession(): """Reset the session to its initial state. All pipeline readers, sources, filters extractors, and representations are removed.""" connection = servermanager.ResetSession() _initializeSession(connection) _add_functions(globals()) return connection
# ============================================================================== # Multi-servers # ==============================================================================
[docs]def SetActiveConnection(connection=None, ns=None): """Set the active connection. If the process was run without multi-server enabled and this method is called with a non-None argument while an ActiveConnection is present, it will raise a RuntimeError. :param connection: If provided, changes the current connection. :type connection: Connection object. :param ns: Namespace in which functions from the old Connection are removed and functions in the new Connection are added. :raises RuntimeError: If called when ParaView is not running in multi-server mode, a `RuntimeError` will be raised. """ if not ns: ns = globals() if servermanager.ActiveConnection != connection: _remove_functions(ns) servermanager.SetActiveConnection(connection) _add_functions(ns)
# ============================================================================== # Views and Layout methods # ==============================================================================
[docs]def CreateView(view_xml_name, **params): """Creates and returns the specified proxy view based on its name/label. Also set params keywords arguments as view properties. :param view_xml_name: Name of the requested View as it appears in the proxy definition XML. Examples include RenderView, ImageChartView, SpreadSheetView, etc. :param params: Dictionary created from named arguments. If one of these arguments is named 'registrationName', the string value associated with it will be used as the name of the proxy. That name will appear in the Pipeline Browser of the ParaView GUI, and it is the name to be passed to the FindView() function to find this view. Any additional named arguments will be passed as properties to initialize the view. :return: The created view Python object. :rtype: """ view = servermanager._create_view(view_xml_name) if not view: raise RuntimeError("Failed to create requested view", view_xml_name) try: registrationName = params["registrationName"] del params["registrationName"] except KeyError: try: registrationName = params["guiName"] del params["guiName"] except KeyError: registrationName = None controller = servermanager.ParaViewPipelineController() controller.PreInitializeProxy(view) SetProperties(view, **params) controller.PostInitializeProxy(view) controller.RegisterViewProxy(view, registrationName) if paraview.compatibility.GetVersion() <= (5, 6): # older versions automatically assigned view to a # layout. controller.AssignViewToLayout(view) if paraview.compatibility.GetVersion() <= (5, 9): if hasattr(view, "UseColorPaletteForBackground"): view.UseColorPaletteForBackground = 0 # setup an interactor if current process support interaction if an # interactor hasn't already been set. This overcomes the problem where VTK # segfaults if the interactor is created after the window was created. view.MakeRenderWindowInteractor(True) from .catalyst.detail import IsInsitu, RegisterView if IsInsitu(): # tag the view to know which pipeline this came from. RegisterView(view) return view
# -----------------------------------------------------------------------------
[docs]def CreateRenderView(**params): """Create standard 3D render view. See :func:`CreateView` for argument documentation""" return CreateView("RenderView", **params)
# -----------------------------------------------------------------------------
[docs]def CreateXYPlotView(**params): """Create XY plot Chart view. See :func:`CreateView` for argument documentation""" return CreateView("XYChartView", **params)
# -----------------------------------------------------------------------------
[docs]def CreateXYPointPlotView(**params): """Create XY plot point Chart view. See :func:`CreateView` for argument documentation""" return CreateView("XYPointChartView", **params)
# -----------------------------------------------------------------------------
[docs]def CreateBarChartView(**params): """Create Bar Chart view. See :func:`CreateView` for argument documentation""" return CreateView("XYBarChartView", **params)
# -----------------------------------------------------------------------------
[docs]def CreateComparativeRenderView(**params): """Create Comparative view. See :func:`CreateView` for argument documentation""" return CreateView("ComparativeRenderView", **params)
# -----------------------------------------------------------------------------
[docs]def CreateComparativeXYPlotView(**params): """Create comparative XY plot Chart view. See :func:`CreateView` for argument documentation""" return CreateView("ComparativeXYPlotView", **params)
# -----------------------------------------------------------------------------
[docs]def CreateComparativeBarChartView(**params): """Create comparative Bar Chart view. See :func:`CreateView` for argument documentation""" return CreateView("ComparativeBarChartView", **params)
# -----------------------------------------------------------------------------
[docs]def CreateParallelCoordinatesChartView(**params): """Create Parallel Coordinates Chart view. See :func:`CreateView` for argument documentation""" return CreateView("ParallelCoordinatesChartView", **params)
# -----------------------------------------------------------------------------
[docs]def Create2DRenderView(**params): """Create the standard 3D render view with the 2D interaction mode turned on. See :func:`CreateView` for argument documentation""" return CreateView("2DRenderView", **params)
# -----------------------------------------------------------------------------
[docs]def GetRenderView(): """Returns the active view if there is one. Else creates and returns a new view. :return: the active view""" view = active_objects.view if not view: # it's possible that there's no active view, but a render view exists. # If so, locate that and return it (before trying to create a new one). view = servermanager.GetRenderView() if not view: view = CreateRenderView() return view
# -----------------------------------------------------------------------------
[docs]def GetRenderViews(): """Get all render views in a list. :return: all render views in a list.""" return servermanager.GetRenderViews()
# -----------------------------------------------------------------------------
[docs]def GetViews(viewtype=None): """Returns all views in a list. :param viewtype: If provided, only the views of the specified type are returned. Optional, defaults to `None`. :type viewtype: str :return: list of views of the given viewtype, or all views if viewtype is `None`. :rtype: list of view proxies""" val = [] for aProxy in servermanager.ProxyManager().GetProxiesInGroup("views").values(): if aProxy.IsA("vtkSMViewProxy") and \ (viewtype is None or aProxy.GetXMLName() == viewtype): val.append(aProxy) return val
# -----------------------------------------------------------------------------
[docs]def SetViewProperties(view=None, **params): """Sets one or more properties of the given view. If an argument is not provided, the active view is used. Pass in arguments of the form `property_name=value` to this function to set property values. For example:: SetProperties(Background=[1, 0, 0], UseImmediateMode=0) :param view: The view whose properties are to be set. If not provided, the active view is used. :type view: View proxy. :param params: A variadic list of `key=value` pairs giving values of specific named properties in the view. For a list of available properties, call `help(view)`. """ if not view: view = active_objects.view SetProperties(view, **params)
# -----------------------------------------------------------------------------
[docs]def Render(view=None): """Renders the given view if given, otherwise renders the active view. If this is the first render and the view is a RenderView, the camera is reset. :param view: The view to render. Optional, defaults to rendering the active view. :type view: View proxy.""" if not view: view = active_objects.view if not view: raise AttributeError("view cannot be None") # setup an interactor if current process support interaction if an # interactor hasn't already been set. This overcomes the problem where VTK # segfaults if the interactor is created after the window was created. view.MakeRenderWindowInteractor(True) view.StillRender() if _funcs_internals.first_render: # Not all views have a ResetCamera method try: view.ResetCamera() view.StillRender() except AttributeError: pass _funcs_internals.first_render = False return view
# -----------------------------------------------------------------------------
[docs]def RenderAllViews(): """Renders all existing views.""" for view in GetViews(): Render(view)
# -----------------------------------------------------------------------------
[docs]def Interact(view=None): """Call this method to start interacting with a view. This method will block until the interaction is done. If the local process cannot support interactions, this method will simply return without doing anything. :param view: The interaction occurs with this view. Optional, defaults to the active view. :type view: View proxy.""" if not view: view = active_objects.view if not view: raise ValueError("view argument cannot be None") if not view.MakeRenderWindowInteractor(False): raise RuntimeError("Configuration doesn't support interaction.") paraview.print_debug_info("Staring interaction. Use 'q' to quit.") # Views like ComparativeRenderView require that Render() is called before # the Interaction is begun. Hence we call a Render() before start the # interactor loop. This also avoids the case where there are pending updates # and thus the interaction will be begun on stale datasets. Render(view) view.GetInteractor().Start()
# -----------------------------------------------------------------------------
[docs]def ResetCamera(view=None): """Resets camera settings to make the whole scene visible while preserving orientation. :param view: The camera for this view is reset. Optional, defaults to the active view. :type view: View proxy.""" if not view: view = active_objects.view if hasattr(view, "ResetCamera"): view.ResetCamera() if hasattr(view, "ResetDisplay"): view.ResetDisplay() Render(view)
# -----------------------------------------------------------------------------
[docs]def ResetCameraToDirection(position, direction, up=None, view=None): """Resets the settings of the camera to the given position and direction. :param position: Position of the camera. :type position: 3-element tuple or list of floats. :param direction: Direction of the camera. :type direction: 3-element tuple or list of floats. :param up: If provided, will be used as the camera's up direction. :type up: 3-element tuple or list of floats. :param view: If provided, modifies the camera in this view. :type view: View proxy.""" if not view: view = active_objects.view if hasattr(view, "CameraFocalPoint"): view.CameraFocalPoint = position if hasattr(view, "CameraPosition"): for i in range(3): view.CameraPosition[i] = position[i] - direction[i] if hasattr(view, "CameraViewUp") and up: view.CameraViewUp = up ResetCamera(view)
# -----------------------------------------------------------------------------
[docs]def CreateLayout(name=None): """Create a new layout with no active view. :param name: The name of the layout. Optional, defaults to an automatically created name.""" layout = servermanager.misc.ViewLayout(registrationGroup="layouts") if name: RenameLayout(name, layout) return layout
# -----------------------------------------------------------------------------
[docs]def RemoveLayout(proxy=None): """Remove the provided layout. If none is provided, remove the layout containing the active view. If it is the only layout it will create a new one with the same name as the removed one. :param proxy: The layout proxy to remove. Optional, defaults to the layout containing the active view. :type proxy: Layout proxy or `None`.""" pxm = servermanager.ProxyManager() if not proxy: proxy = GetLayout() name = pxm.GetProxyName('layouts', proxy) pxm.UnRegisterProxy('layouts', name, proxy) if len(GetLayouts()) == 0: CreateLayout(name)
# -----------------------------------------------------------------------------
[docs]def GetLayouts(): """Returns all the layout proxies. :return: A list of all the layouts. :rtype: list of layout proxies""" return servermanager.ProxyManager().GetProxiesInGroup("layouts")
# -----------------------------------------------------------------------------
[docs]def GetLayout(view=None): """Return the layout containing the given view, if any. :param view: A view in the layout to be removed. Optional, defaults to the active view. :return: The layout containing the view :rtype: :class:`paraview.servermanager.ViewLayout`""" if not view: view = GetActiveView() if not view: raise RuntimeError("No active view was found.") lproxy = servermanager.vtkSMViewLayoutProxy.FindLayout(view.SMProxy) return servermanager._getPyProxy(lproxy)
[docs]def GetLayoutByName(name): """Return the first layout with the given name, if any. :param name: Name of the layout :type name: str :return: The named layout if it exists :rtype: Layout proxy or `None`""" layouts = GetLayouts() for key in layouts.keys(): if key[0] == name: return layouts.get(key) return None
[docs]def GetViewsInLayout(layout=None): """Returns a list of views in the given layout. :param layout: Layout whose views should be returned. Optional, defaults to the layout for the active view, if possible. :type layout: Layout proxy. :return: List of views in the layout. :rtype: list""" layout = layout if layout else GetLayout() if not layout: raise RuntimeError("Layout couldn't be determined. Please specify a valid layout.") views = GetViews() return [x for x in views if layout.GetViewLocation(x) != -1]
[docs]def AssignViewToLayout(view=None, layout=None, hint=0): """Assigns the view provided to the layout provided. If no layout exists, then a new layout will be created. It is an error to assign the same view to multiple layouts. :param view: The view to assign to the layout. Optional, defaults to the active view. :type view: View proxy. :param layout: If layout is `None`, then either the active layout or an existing layout on the same server will be used. :type layout: Layout proxy. :return: Returns `True` on success. :rtype: bool """ view = view if view else GetActiveView() if not view: raise RuntimeError("No active view was found.") layout = layout if layout else GetLayout() controller = servermanager.ParaViewPipelineController() return controller.AssignViewToLayout(view, layout, hint)
# -----------------------------------------------------------------------------
[docs]def RemoveViewsAndLayouts(): """ Removes all existing views and layouts. """ pxm = servermanager.ProxyManager() layouts = pxm.GetProxiesInGroup("layouts") for view in GetRenderViews(): Delete(view) # Can not use regular delete for layouts for name, id in layouts: proxy = layouts[(name, id)] pxm.UnRegisterProxy('layouts', name, layouts[(name, id)])
[docs]def EqualizeViewsHorizontally(layout=None): """Equalizes horizontal view sizes in the provided layout. :param layout: Layout the layout contain the views to equalize. Optional, defaults to the active layout. :type layout: Layout proxy. """ layout = layout if layout else GetLayout() layout.SMProxy.EqualizeViews(paraview.modules.vtkRemotingViews.vtkSMViewLayoutProxy.HORIZONTAL)
[docs]def EqualizeViewsVertically(layout=None): """Equalizes vertical view sizes in the provided layout. :param layout: Layout the layout contain the views to equalize. Optional, defaults to the active layout. :type layout: Layout proxy. """ layout = layout if layout else GetLayout() layout.SMProxy.EqualizeViews(paraview.modules.vtkRemotingViews.vtkSMViewLayoutProxy.VERTICAL)
[docs]def EqualizeViewsBoth(layout=None): """Equalizes the vertical and horizontal view sizes in the provided layout. :param layout: Layout the layout contain the views to equalize. Optional, defaults to the active layout. :type layout: Layout proxy. """ layout = layout if layout else GetLayout() layout.SMProxy.EqualizeViews()
# ============================================================================== # Extracts and Extractors # ==============================================================================
[docs]def CreateExtractor(name, proxy=None, registrationName=None): """Creates a new extractor and returns it. :param name: The type of the extractor to create. :type name: `str` :param proxy: The proxy to generate the extract from. If not specified the active source is used. :type proxy: :class:`paraview.servermanager.Proxy`, optional :param registrationName: The registration name to use to register the extractor with the ProxyManager. If not specified a unique name will be generated. :type name: `str`, optional :return: The extractor created, on success, else None :rtype: :class:`paraview.servermanager.Proxy` or `None` """ if proxy is None: proxy = GetActiveSource() if not proxy: raise RuntimeError("Could determine input for extractor") if proxy.Port > 0: rawProxy = proxy.SMProxy.GetOutputPort(proxy.Port) else: rawProxy = proxy.SMProxy controller = servermanager.vtkSMExtractsController() # Special case of 'steering' extractors : add it to the steerable extractors list # managed by the in situ helper class, not to the extracts controller, because # they are not associated with a writer. from .catalyst.detail import IsInsitu, RegisterExtractor if name == "steering" and IsInsitu(): rawExtractor = controller.CreateSteeringExtractor(rawProxy, registrationName) extractor = servermanager._getPyProxy(rawExtractor) UpdateSteerableParameters(extractor, registrationName) else: rawExtractor = controller.CreateExtractor(rawProxy, name, registrationName) extractor = servermanager._getPyProxy(rawExtractor) if IsInsitu(): # tag the extractor to know which pipeline this came from. RegisterExtractor(extractor) return extractor
[docs]def GetExtractors(proxy=None): """Returns a list of extractors associated with the proxy. :param proxy: The proxy to return the extractors associated with. If not specified (or is None) then all extractors are returned. :type proxy: :class:`paraview.servermanager.Proxy`, optional :return: List of associated extractors if any. May return an empty list. :rtype: list of :class:`paraview.servermanager.Proxy` """ controller = servermanager.vtkSMExtractsController() pxm = servermanager.ProxyManager() extractors = pxm.GetProxiesInGroup("extractors").values() if proxy is None: return list(extractors) else: return [g for g in extractors if controller.IsExtractor(g.SMProxy, proxy.SMProxy)]
[docs]def FindExtractor(registrationName): """ Returns an extractor with a specific registrationName. :param registrationName: Registration name for the extractor. :type registrationName: `str` :return: The extractor or None :rtype: :class:`paraview.servermanager.Proxy` or `None` """ pxm = servermanager.ProxyManager() return pxm.GetProxy("extractors", registrationName)
[docs]def SaveExtractsUsingCatalystOptions(options): """Generate extracts using a :class:`CatalystOptions` object. This is intended for use when a Catalyst analysis script is being run in batch mode. :param options: Catalyst options proxy :type options: :class:`CatalystOptions` """ # handle the case where options is CatalystOptions return SaveExtracts(ExtractsOutputDirectory=options.ExtractsOutputDirectory, GenerateCinemaSpecification=options.GenerateCinemaSpecification)
[docs]def SaveExtracts(**kwargs): """Generate extracts. Parameters are forwarded for 'SaveAnimationExtracts' Currently, supported keyword parameters are: :param ExtractsOutputDirectory: root directory for extracts. If the directory does not exist, it will be created. :type ExtractsOutputDirectory: `str` :param GenerateCinemaSpecification: If set to `True`, enables generation of a cinema specification. :type GenerateCinemaSpecification: bool :param FrameRate: The frame rate in frames-per-second if the extractor supports it. :type FrameRate: int :param FrameStride: The number of timesteps to skip after a timestep is saved. :type FrameStride: int :param FrameWindow: The range of timesteps to extract. :type FrameWindow: 2-element tuple or list of ints """ # currently, Python state files don't have anything about animation, # however, we rely on animation to generate the extracts, so we ensure # that the animation is updated based on timesteps in data by explicitly # calling UpdateAnimationUsingDataTimeSteps. scene = GetAnimationScene() if not scene: from . import print_warning print_warning("This Edition does not support animations. Cannot save extracts.") return False scene.UpdateAnimationUsingDataTimeSteps() controller = servermanager.ParaViewPipelineController() proxy = servermanager.misc.SaveAnimationExtracts() controller.PreInitializeProxy(proxy) proxy.AnimationScene = scene controller.PostInitializeProxy(proxy) SetProperties(proxy, **kwargs) return proxy.SaveExtracts()
[docs]def CreateSteerableParameters(steerable_proxy_type_name, steerable_proxy_registration_name= "SteeringParameters", result_mesh_name="steerable"): """Creates a steerable proxy for Catalyst use cases. :param steerable_proxy_type_name: Name of the proxy type to create. :type steerable_proxy_type_name: str :param steerable_proxy_registration_name: Registration name of the proxy created by this function. If not provided, defaults to "SteeringParameters". :type steerable_proxy_registration_name: str :param result_mesh_name: The name of the resulting mesh. If not provided, defaults to "steerable". :type result_mesh_name: str :return: Proxy of the specified type. :rtype: Steerable proxy.""" pxm = servermanager.ProxyManager() steerable_proxy = pxm.NewProxy("sources", steerable_proxy_type_name) pxm.RegisterProxy("sources", steerable_proxy_registration_name, steerable_proxy) steerable_proxy_wrapper = servermanager._getPyProxy(steerable_proxy) UpdateSteerableParameters(steerable_proxy_wrapper, result_mesh_name) return steerable_proxy_wrapper
[docs]def UpdateSteerableParameters(steerable_proxy, steerable_source_name): """Updates a steerable proxy of a provided source name. :param steerable_proxy: The steerable proxy to update. :type steerable_proxy: Source proxy. :param steerable_source_name: The name of the steerable source proxy. :type steerable_source_name: str""" helper = paraview.modules.vtkPVInSitu.vtkInSituInitializationHelper helper.UpdateSteerableParameters(steerable_proxy.SMProxy, steerable_source_name)
# ============================================================================== # XML State management # ==============================================================================
[docs]def LoadState(statefile, data_directory=None, restrict_to_data_directory=False, filenames=None, location=vtkPVSession.CLIENT, *args, **kwargs): """ Load PVSM state file. This will load the state specified in the `statefile`. ParaView can update absolute paths for data files used in the state which can be useful to portably load state file across different systems. Alternatively, `filenames` can be used to specify a list of filenames explicitly. This must be list of the following form: .. code-block:: json [ { # either 'name' or 'id' are required. if both are provided, 'id' # is checked first. "name" : "[reader name shown in pipeline browser]", "id" : "[reader id used in the pvsm state file]", # all modified filename-like properties on this reader "FileName" : ... .... }, ... ] Calling this function with other positional or keyword arguments will invoke the legacy signature of this function `_LoadStateLegacy`. :param statefile: Path to the statefile to load :type statefile: str :param data_directory: If not `None`, then ParaView searches for files matching those used in the state under the specified directory and if found, replaces the state to use the found files instead. Optional, defaults to `None`. :type data_directory: str :param restrict_to_data_directory: If set to `True`, if a file is not found under the `data_directory`, it will raise an error, otherwise it is left unchanged. Optional, defaults to `False`. :type restrict_to_data_directory: bool :param filenames: JSON-formatted string to specify a list of filenames. :type filenames: str :param location: Where the statefile is located, e.g., pass `vtkPVSession.CLIENT` if the statefile is located on the client system (default value), pass in `vtkPVSession.SERVERS` if on the server. Optional, defaults to client. :type location: `vtkPVServer.ServerFlags` enum value """ if kwargs: return _LoadStateLegacy(statefile, *args, **kwargs) RemoveViewsAndLayouts() pxm = servermanager.ProxyManager() pyproxy = servermanager._getPyProxy(pxm.NewProxy('options', 'LoadStateOptions')) if pyproxy.PrepareToLoad(statefile, location): pyproxy.LoadStateDataFileOptions = pyproxy.SMProxy.USE_FILES_FROM_STATE if pyproxy.HasDataFiles(): if data_directory is not None: pyproxy.LoadStateDataFileOptions = pyproxy.SMProxy.USE_DATA_DIRECTORY pyproxy.DataDirectory = data_directory if restrict_to_data_directory: pyproxy.OnlyUseFilesInDataDirectory = 1 elif filenames is not None: pyproxy.LoadStateDataFileOptions = pyproxy.SMProxy.CHOOSE_FILES_EXPLICITLY for item in filenames: for pname in item.keys(): if pname == "name" or pname == "id": continue smprop = pyproxy.FindProperty(item.get("name"), int(item.get("id")), pname) if not smprop: raise RuntimeError("Invalid item specified in 'filenames': %s", item) prop = servermanager._wrap_property(pyproxy, smprop) prop.SetData(item[pname]) pyproxy.Load() # Try to set the new view active if len(GetRenderViews()) > 0: SetActiveView(GetRenderViews()[0])
def _LoadStateLegacy(filename, connection=None, **extraArgs): """Python scripts from version < 5.9 used a different signature. This function supports that. :param filename: Name of the statefile to load. :type filename: str :param connection: Unused. :type connection: `None` """ RemoveViewsAndLayouts() pxm = servermanager.ProxyManager() pyproxy = servermanager._getPyProxy(pxm.NewProxy('options', 'LoadStateOptions')) if (pyproxy is not None) and pyproxy.PrepareToLoad(filename): if pyproxy.HasDataFiles() and (extraArgs is not None): for pname, value in extraArgs.items(): smprop = pyproxy.FindLegacyProperty(pname) if smprop: if not smprop: raise RuntimeError("Invalid argument '%s'", pname) prop = servermanager._wrap_property(pyproxy, smprop) prop.SetData(value) else: pyproxy.__setattr__(pname, value) pyproxy.Load() # Try to set the new view active if len(GetRenderViews()) > 0: SetActiveView(GetRenderViews()[0]) # -----------------------------------------------------------------------------
[docs]def SaveState(filename, location=vtkPVSession.CLIENT): """Save a ParaView statefile (.pvsm) to disk on a system provided by the location parameter. :param filename: Path where the state file should be saved. :type filename: str :param location: Where the statefile should be save, e.g., pass `vtkPVSession.CLIENT` if the statefile is located on the client system (default value), pass in `vtkPVSession.SERVERS` if on the server. :type location: `vtkPVServer.ServerFlags` enum value""" servermanager.SaveState(filename, location)
# ============================================================================== # Representation methods # ==============================================================================
[docs]def GetRepresentation(proxy=None, view=None): """Given a pipeline proxy and a view, returns the corresponding representation object. If proxy and view are not specified, active objects are used. :param proxy: Pipeline proxy whose representation in the given view is requested. Optional, defaults to the active view. :type proxy: Source proxy :param view: The view associated with the requested representation. Optional, defaults to returning the representation associated with the active view. :type view: View proxy :return: The representation for the given proxy in the view. :rtype: Representation proxy """ if not view: view = active_objects.view if not view: raise ValueError("view argument cannot be None.") if not proxy: proxy = active_objects.source if not proxy: raise ValueError("proxy argument cannot be None.") rep = servermanager.GetRepresentation(proxy, view) if not rep: controller = servermanager.ParaViewPipelineController() return controller.Show(proxy, proxy.Port, view) return rep
# -----------------------------------------------------------------------------
[docs]def GetDisplayProperties(proxy=None, view=None): """Identical to `GetRepresentation()`""" return GetRepresentation(proxy, view)
# -----------------------------------------------------------------------------
[docs]def Show(proxy=None, view=None, representationType=None, **params): """Turns on the visibility of a given pipeline proxy in the given view. If pipeline proxy and/or view are not specified, active objects are used. :param proxy: The pipeline proxy to show. If not provided, uses the active source. :type proxy: Source proxy. :param view: The view proxy to show the source proxy in. Optional, defaults to the active view. :type view: View proxy. :param representationType: Name of the representation type to use. Optional, defaults to a suitable representation for the source proxy and view. :type representationType: str :return: The representation proxy for the source proxy in the view. :rtype: Representation proxy.:""" if proxy == None: proxy = GetActiveSource() if not hasattr(proxy, "GetNumberOfOutputPorts") or proxy.GetNumberOfOutputPorts() == 0: raise RuntimeError('Cannot show a sink i.e. algorithm with no output.') if proxy == None: raise RuntimeError("Show() needs a proxy argument or that an active source is set.") if not view: # If there's no active view, controller.Show() will create a new preferred view. # if possible. view = active_objects.view controller = servermanager.ParaViewPipelineController() rep = controller.Show(proxy, proxy.Port, view, representationType) if rep == None: raise RuntimeError("Could not create a representation object for proxy %s" % proxy.GetXMLLabel()) for param in params.keys(): setattr(rep, param, params[param]) return rep
# -----------------------------------------------------------------------------
[docs]def ShowAll(view=None): """Show all pipeline sources in the given view. :param view: The view in which to show all pipeline sources. :type view: View proxy. Optional, defaults to the active view.""" if not view: view = active_objects.view controller = servermanager.ParaViewPipelineController() controller.ShowAll(view)
# -----------------------------------------------------------------------------
[docs]def Hide(proxy=None, view=None): """Turns the visibility of a given pipeline source off in the given view. If pipeline object and/or view are not specified, active objects are used. :param proxy: The pipeline source. Optional, defaults to the active source. :type proxy: Pipeline source proxy to hide. :param view: The view in which the pipeline source should be hidden. Optional, defaults to the active view. :type view: View proxy. """ if not proxy: proxy = active_objects.source if not view: view = active_objects.view if not proxy: raise ValueError("proxy argument cannot be None when no active source is present.") controller = servermanager.ParaViewPipelineController() controller.Hide(proxy, proxy.Port, view)
# -----------------------------------------------------------------------------
[docs]def HideAll(view=None): """Hide all pipeline sources in the given view. :param view: The view in which to hide all pipeline sources. Optional, defaults to the active view. :type view: View proxy. """ if not view: view = active_objects.view controller = servermanager.ParaViewPipelineController() controller.HideAll(view)
# -----------------------------------------------------------------------------
[docs]def SetDisplayProperties(proxy=None, view=None, **params): """Sets one or more display properties of the given pipeline source. Pass a list of `property_name=value` pairs to this function to set property values. For example:: SetProperties(Color=[1, 0, 0], LineWidth=2) :param proxy: Pipeline source whose display properties should be set. Optional, defaults to the active source. :type proxy: Source proxy :param view: The view in which to make the display property changes. Optional, defaults to the active view. :type view: View proxy """ rep = GetDisplayProperties(proxy, view) SetProperties(rep, **params)
# -----------------------------------------------------------------------------
[docs]def ColorBy(rep=None, value=None, separate=False): """Set data array to color a representation by. This will automatically set up the color maps and others necessary state for the representations. :param rep: Must be a representation proxy i.e. the value returned by the :func:`GetRepresentation`. Optional, defaults to the display properties for the active source, if possible. :type rep: Representation proxy :param value: Name of the array to color by. :type value: str :param separate: Set to `True` to create a color map unique to this representation. Optional, defaults to the global color map ParaView uses for any object colored by an array of the same name. :type separate: bool""" rep = rep if rep else GetDisplayProperties() if not rep: raise ValueError("No display properties can be determined.") rep.UseSeparateColorMap = separate association = rep.ColorArrayName.GetAssociation() arrayname = rep.ColorArrayName.GetArrayName() component = None if value == None: rep.SetScalarColoring(None, servermanager.GetAssociationFromString(association)) return if not isinstance(value, tuple) and not isinstance(value, list): value = (value,) if len(value) == 1: arrayname = value[0] elif len(value) >= 2: association = value[0] arrayname = value[1] if len(value) == 3: # component name provided componentName = value[2] if componentName == "Magnitude": component = -1 else: if association == "POINTS": array = rep.Input.PointData.GetArray(arrayname) if association == "CELLS": array = rep.Input.CellData.GetArray(arrayname) if array: # looking for corresponding component name for i in range(0, array.GetNumberOfComponents()): if componentName == array.GetComponentName(i): component = i break # none have been found, try to use the name as an int if i == array.GetNumberOfComponents() - 1: try: component = int(componentName) except ValueError: pass if component is None: rep.SetScalarColoring(arrayname, servermanager.GetAssociationFromString(association)) else: rep.SetScalarColoring(arrayname, servermanager.GetAssociationFromString(association), component) rep.RescaleTransferFunctionToDataRange()
# -----------------------------------------------------------------------------
[docs]def ColorBlocksBy(rep=None, selectors=None, value=None, separate=False): """Like :func:`ColorBy`, set data array by which to color selected blocks within a representation, but color only selected blocks with the specified properties. This will automatically set up the color maps and others necessary state for the representations. :param rep: Must be a representation proxy i.e. the value returned by the :func:`GetRepresentation`. Optional, defaults to the display properties for the active source, if possible. :type rep: Representation proxy :param selectors: List of block selectors that choose which blocks to modify with this call. :type selectors: list of str :param value: Name of the array to color by. :type value: str :param separate: Set to `True` to create a color map unique to this representation. Optional, default is that the color map used will be the global color map ParaView uses for any object colored by an array of the same name. :type separate: bool""" rep = rep if rep else GetDisplayProperties() if not rep: raise ValueError("No display properties can be determined.") if selectors is None or len(selectors) == 0: raise ValueError("No selector can be determined.") rep.SetBlocksUseSeparateColorMap(selectors, separate) firstSelector = selectors[0] associationInt = rep.GetBlockColorArrayAssociation(firstSelector) association = servermanager.GetAssociationAsString(associationInt) if associationInt != -1 else None arrayname = rep.GetBlockColorArrayName(firstSelector) component = None if value is None: if association is not None: rep.SetBlocksScalarColoring(selectors, None, servermanager.GetAssociationFromString(association)) else: rep.SetBlocksScalarColoring(selectors, None, 0) return if not isinstance(value, tuple) and not isinstance(value, list): value = (value,) if len(value) == 1: arrayname = value[0] elif len(value) >= 2: association = value[0] arrayname = value[1] if len(value) == 3: # component name provided componentName = value[2] if componentName == "Magnitude": component = -1 else: if association == "POINTS": array = rep.Input.PointData.GetArray(arrayname) if association == "CELLS": array = rep.Input.CellData.GetArray(arrayname) if array: # looking for corresponding component name for i in range(0, array.GetNumberOfComponents()): if componentName == array.GetComponentName(i): component = i break # none have been found, try to use the name as an int if i == array.GetNumberOfComponents() - 1: try: component = int(componentName) except ValueError: pass if component is None: rep.SetBlocksScalarColoring(selectors, arrayname, servermanager.GetAssociationFromString(association)) else: rep.SetBlocksScalarColoring(selectors, arrayname, servermanager.GetAssociationFromString(association), component) rep.RescaleBlocksTransferFunctionToDataRange(selectors)
# ----------------------------------------------------------------------------- def _DisableFirstRenderCameraReset(): """Normally a ResetCamera is called automatically when Render is called for the first time after importing the `paraview.simple` module. Calling this function disables this first render camera reset.""" _funcs_internals.first_render = False # ============================================================================== # Proxy handling methods # ==============================================================================
[docs]def SetProperties(proxy=None, **params): """Sets one or more properties of the given pipeline source. If an argument is not provided, the active source is used. Pass in arguments of the form `property_name=value` to this function to set property values. For example:: SetProperties(Center=[1, 2, 3], Radius=3.5) :param proxy: The pipeline source whose properties should be set. Optional, defaultst to the active source. :type proxy: Source proxy :param params: A variadic list of `key=value` pairs giving values of specific named properties in the pipeline source. For a list of available properties, call `help(proxy)`.""" if not proxy: proxy = active_objects.source properties = proxy.ListProperties() for param in params.keys(): pyproxy = servermanager._getPyProxy(proxy) pyproxy.__setattr__(param, params[param])
# -----------------------------------------------------------------------------
[docs]def GetProperty(*arguments, **keywords): """Get one property of the given pipeline object. If keywords are used, you can set the proxy and the name of the property that you want to get as shown in the following example:: GetProperty({proxy=sphere, name="Radius"}) If arguments are used, then you have two cases: - if only one argument is used that argument will be the property name. - if two arguments are used then the first one will be the proxy and the second one the property name. Several example are given below:: GetProperty({name="Radius"}) GetProperty({proxy=sphereProxy, name="Radius"}) GetProperty( sphereProxy, "Radius" ) GetProperty( "Radius" ) """ name = None proxy = None for key in keywords: if key == "name": name = keywords[key] if key == "proxy": proxy = keywords[key] if len(arguments) == 1: name = arguments[0] if len(arguments) == 2: proxy = arguments[0] name = arguments[1] if not name: raise RuntimeError( "Expecting at least a property name as input. Otherwise keyword could be used to set 'proxy' and property 'name'") if not proxy: proxy = active_objects.source return proxy.GetProperty(name)
# -----------------------------------------------------------------------------
[docs]def GetDisplayProperty(*arguments, **keywords): """Same as :func:`GetProperty()`, except that if no `proxy` parameter is passed, it will use the active representation, rather than the active source.""" proxy = None name = None for key in keywords: if key == "name": name = keywords[key] if key == "proxy": proxy = keywords[key] if len(arguments) == 1: name = arguments[0] if len(arguments) == 2: proxy = arguments[0] name = arguments[1] if not proxy: proxy = GetDisplayProperties() return GetProperty(proxy, name)
# -----------------------------------------------------------------------------
[docs]def GetViewProperty(*arguments, **keywords): """Same as :func:`GetProperty()`, except that if no 'proxy' parameter is passed, it will use the active view properties, rather than the active source.""" proxy = None name = None for key in keywords: if key == "name": name = keywords[key] if key == "proxy": proxy = keywords[key] if len(arguments) == 1: name = arguments[0] if len(arguments) == 2: proxy = arguments[0] name = arguments[1] if not proxy: proxy = GetViewProperties() return GetProperty(proxy, name)
# -----------------------------------------------------------------------------
[docs]def GetViewProperties(view=None): """Same as :func:`GetActiveView()`. this API is provided just for consistency with :func:`GetDisplayProperties()`.""" return GetActiveView()
# -----------------------------------------------------------------------------
[docs]def LoadPalette(paletteName): """Load a color palette to override the default foreground and background colors used by ParaView views. The current global palette's colors are set to the colors in the loaded palette. :param paletteName: Name of the palette to load from this list: 'WarmGrayBackground', 'DarkGrayBackground', 'NeutralGrayBackground', 'LightGrayBackground', 'WhiteBackground', 'BlackBackground', 'GradientBackground'. :type paletteName: str""" name = paletteName # Handling backward compatibility if paraview.compatibility.GetVersion() <= (5, 10): if paletteName == "DefaultBackground" or paletteName == "GrayBackground": name = "BlueGrayBackground" elif paletteName == "PrintBackground": name = "WhiteBackground" if paraview.compatibility.GetVersion() <= (5, 11): if paletteName == "WarmGrayBackground": name = "DarkGrayBackground" if paraview.compatibility.GetVersion() <= (5, 12): if paletteName == "DefaultBackground": name = "BlueGrayBackground" pxm = servermanager.ProxyManager() palette = pxm.GetProxy("settings", "ColorPalette") prototype = pxm.GetPrototypeProxy("palettes", name) if palette is None or prototype is None: return palette.Copy(prototype) palette.UpdateVTKObjects()
# ============================================================================== # ServerManager methods # ==============================================================================
[docs]def RenameProxy(proxy, group, newName): """Renames the given proxy. This is the name used by :func:`FindSource` and is displayed in the Pipeline Browser. :param proxy: The proxy to be renamed :type proxy: Proxy object :param group: The group in which the proxy lives. Can be retrieved with `proxy.GetXMLGroup()` :type group: str :param newName: The new name of the proxy. :type newName: str""" pxm = servermanager.ProxyManager() oldName = pxm.GetProxyName(group, proxy) if oldName and newName != oldName: pxm.RegisterProxy(group, newName, proxy) pxm.UnRegisterProxy(group, oldName, proxy)
[docs]def RenameSource(newName, proxy=None): """Renames the given source proxy. If the given proxy is not registered in the 'sources' group this function will have no effect. :param newName: The new name of the source proxy :type newName: str :param proxy: The source proxy to rename. It must be a member of the 'sources' group. Optional, defaults to renaming the active source. :type proxy: Source proxy""" if not proxy: proxy = GetActiveSource() RenameProxy(proxy, "sources", newName)
[docs]def RenameView(newName, proxy=None): """Renames the given view. If the given proxy is not registered in the 'views' group this method will have no effect. :param newName: The new name of the view proxy :type newName: str :param proxy: The view proxy to rename. It must be a member of the 'views' group. Optional, defaults to renaming the active view. :type proxy: View proxy""" if not proxy: proxy = GetActiveView() RenameProxy(proxy, "views", newName)
[docs]def RenameLayout(newName, proxy=None): """Renames the given layout. If the given proxy is not registered in the 'layouts' group this method will have no effect. :param newName: The new name of the layout proxy :type newName: str :param layout: The layout proxy to rename. It must be a member of the 'layouts' groupd. Optional, defaults to renaming the active layout.""" if not proxy: proxy = GetLayout() RenameProxy(proxy, "layouts", newName)
# -----------------------------------------------------------------------------
[docs]def FindSource(name): """ Return a pipeline source based on the name that was used to register it with ParaView. Example usage:: Cone(guiName='MySuperCone') Show() Render() myCone = FindSource('MySuperCone') :param name: The name that the pipeline source was registered with during creation or after renaming. :type name: str :return: The pipeline source if found. :rtype: Pipeline source proxy.""" return servermanager.ProxyManager().GetProxy("sources", name)
[docs]def FindView(name): """Return a view proxy based on the name that was used to register it with ParaView. Example usage:: CreateRenderView(guiName='RenderView1') myView = FindSource('RenderView1') :param name: The name that the view was registered with during creation or after renaming. :type name: str :return: The view if found. :rtype: View proxy.""" return servermanager.ProxyManager().GetProxy("views", name)
[docs]def GetActiveViewOrCreate(viewtype): """ Returns the active view if the active view is of the given type, otherwise creates a new view of the requested type. Note, if a new view is created, it will be assigned to a layout by calling :func:`AssignViewToLayout`. :param viewtype: The type of view to access if it is the active view or create if it doesn't exist. :type viewtype: str :return: The active view if it is of type `viewtype`. :rtype: View proxy. """ view = GetActiveView() if view is None or view.GetXMLName() != viewtype: view = CreateView(viewtype) if view: # if a new view is created, we assign it to a layout. # Since this method gets used when tracing existing views, it makes # sense to assign it to a layout during playback. AssignViewToLayout(view) if not view: raise RuntimeError("Failed to create/locate the specified view") return view
[docs]def FindViewOrCreate(name, viewtype): """Returns the view if a view with the given name exists and is of the the given `viewtype`, otherwise creates a new view of the requested type. Note, if a new view is created, it will be assigned to a layout by calling `AssignViewToLayout`. :param name: Name of the view to find. :type name: str :param viewtype: Type of the view to create. :type viewtype: str""" view = FindView(name) if view is None or view.GetXMLName() != viewtype: view = CreateView(viewtype) if view: # if a new view is created, we assign it to a layout. # Since this method gets used when tracing existing views, it makes # sense to assign it to a layout during playback. AssignViewToLayout(view) if not view: raise RuntimeError("Failed to create/locate the specified view") return view
[docs]def LocateView(displayProperties=None): """Returns the view associated with the given `displayProperties`/representation object if it exists. :param displayProperties: a representation proxy returned by :func:`GetRepresentation()`, :func:`GetDisplayProperties()`, or :func:`Show()` functions. Optional, defaults to the active representation. :type displayProperties: representation proxy :return: The view associated with the representation if it exists, otherwise `None` :rtype: View proxy or `None`""" if displayProperties is None: displayProperties = GetDisplayProperties() if displayProperties is None: raise ValueError("'displayProperties' must be set") for view in GetViews(): try: if displayProperties in view.Representations: return view except AttributeError: pass return None
[docs]def GetSettingsProxy(type): """Given a string giving the type of settings to access, returns the proxy for those settings. :param type: The type of settings to access. Valid types may be found by calling :func:`GetAllSettings()`. :type type: str""" pxm = servermanager.ProxyManager() proxy = pxm.GetProxy("settings", type) return proxy
[docs]def GetAllSettings(): """Get a list of strings that return valid settings proxy types for the :func:GetSettingsProxy() function. :return: List of valid settings proxy names :rtype: list of str""" settingsList = [] pxm = servermanager.ProxyManager() pdm = pxm.GetProxyDefinitionManager() iter = pdm.NewSingleGroupIterator("settings") iter.GoToFirstItem() while not iter.IsDoneWithTraversal(): settingsList.append(iter.GetProxyName()) iter.GoToNextItem() return settingsList
# -----------------------------------------------------------------------------
[docs]def GetSources(): """Get all available pipeline sources. :return: dictionary of pipeline sources. Keys are tuples consisting of the registration name and integer ID of the proxy, and values are the pipeline sources themselves. :rtype: dictionary """ return servermanager.ProxyManager().GetProxiesInGroup("sources")
# -----------------------------------------------------------------------------
[docs]def GetRepresentations(): """Returns all available representation proxies (display properties) in all views. :return: dictionary of representations. Keys are tuples consisting of the registration name and integer ID of the representation proxy, and values are the representation proxies themselves. :rtype: dict """ return servermanager.ProxyManager().GetProxiesInGroup("representations")
# -----------------------------------------------------------------------------
[docs]def UpdatePipeline(time=None, proxy=None): """Updates (executes) the given pipeline object for the given time as necessary (i.e., if it did not already execute). :param time: The time at which to update the pipeline. Optional, defaults to updating the currently loaded timestep. :type time: float :param proxy: Source proxy to update. Optional, defaults to updating the active source. :type proxy: Source proxy.""" if not proxy: proxy = active_objects.source if time: proxy.UpdatePipeline(time) else: proxy.UpdatePipeline()
# -----------------------------------------------------------------------------
[docs]def Delete(proxy=None): """Deletes the given pipeline source or the active source if no argument is specified. :param proxy: the proxy to remove :type proxy: Source proxy. Optional, defaults to deleting the active source.""" if not proxy: proxy = active_objects.source if not proxy: raise RuntimeError("Could not locate proxy to 'Delete'") controller = servermanager.ParaViewPipelineController() controller.UnRegisterProxy(proxy)
# ============================================================================== # Active Source / View / Camera / AnimationScene # ==============================================================================
[docs]def GetActiveView(): """Returns the active view. :return: Active view. :rtype: View proxy.""" return active_objects.view
# -----------------------------------------------------------------------------
[docs]def SetActiveView(view): """Sets the active view. :param view: The view to make active. :type view: View proxy.""" active_objects.view = view
# -----------------------------------------------------------------------------
[docs]def GetActiveSource(): """Returns the active source. :return: Active pipeline source. :rtype: Source proxy""" return active_objects.source
# -----------------------------------------------------------------------------
[docs]def SetActiveSource(source): """Sets the active source. :param source: The source :type source: Source proxy""" active_objects.source = source
# -----------------------------------------------------------------------------
[docs]def GetActiveCamera(): """Returns the active camera for the active view. :return: The active camera :rtype: `vtkCamera`""" return GetActiveView().GetActiveCamera()
# ============================================================================== # I/O methods # ==============================================================================
[docs]def OpenDataFile(filename, **extraArgs): """Creates a reader to read the give file, if possible. This uses extension matching to determine the best reader possible. :return: Returns a suitable reader if found. If a reader cannot be identified, then this returns `None`. :rtype: Reader proxy, or `None` """ session = servermanager.ActiveConnection.Session reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory() if reader_factor.GetNumberOfRegisteredPrototypes() == 0: reader_factor.UpdateAvailableReaders() first_file = filename if type(filename) == list: first_file = filename[0] if not reader_factor.TestFileReadability(first_file, session): msg = "File not readable: %s " % first_file raise RuntimeError(msg) if not reader_factor.CanReadFile(first_file, session): msg = "File not readable. No reader found for '%s' " % first_file raise RuntimeError(msg) prototype = servermanager.ProxyManager().GetPrototypeProxy( reader_factor.GetReaderGroup(), reader_factor.GetReaderName()) xml_name = paraview.make_name_valid(prototype.GetXMLLabel()) reader_func = _create_func(xml_name, servermanager.sources) pname = servermanager.vtkSMCoreUtilities.GetFileNameProperty(prototype) if pname: extraArgs[pname] = filename reader = reader_func(**extraArgs) return reader
# -----------------------------------------------------------------------------
[docs]def ReloadFiles(proxy=None): """Forces a reader proxy to reload the data files. :param proxy: Reader proxy whose files should be reloaded. Optional, defaults to reloading files in the active source. :type proxy: Reader proxy :return: Returns `True` if files reloaded successfully, `False` otherwise :rtype: bool""" if not proxy: proxy = GetActiveSource() helper = servermanager.vtkSMReaderReloadHelper() return helper.ReloadFiles(proxy.SMProxy)
[docs]def ExtendFileSeries(proxy=None): """For a reader proxy that supports reading files series, detect any new files added to the series and update the reader's filename property. :param proxy: Reader proxy that should check for a extended file series. Optional, defaults to extending file series in the active source. :return: `True` if the operation succeeded, `False` otherwise :rtype: bool""" if not proxy: proxy = GetActiveSource() helper = servermanager.vtkSMReaderReloadHelper() return helper.ExtendFileSeries(proxy.SMProxy)
# -----------------------------------------------------------------------------
[docs]def ReplaceReaderFileName(readerProxy, files, propName): """Replaces the readerProxy by a new one given a list of files. :param readerProxy: Reader proxy whose filename should be updated. :type readerProxy: Reader proxy. :param files: List of file names to be read by the reader. :type files: list of str :param propName: should be "FileNames" or "FileName" depending on the property name in the reader. :type propName: str""" servermanager.vtkSMCoreUtilities.ReplaceReaderFileName(readerProxy.SMProxy, files, propName)
# -----------------------------------------------------------------------------
[docs]def CreateWriter(filename, proxy=None, **extraArgs): """Creates a writer that can write the data produced by the source proxy in the given file format (identified by the extension). This function doesn't actually write the data, it simply creates the writer and returns it :param filename: The name of the output data file. :type filename: str :param proxy: Source proxy whose output should be written. Optional, defaults to the creating a writer for the active source. :type proxy: Source proxy. :param extraArgs: Additional arguments that should be passed to the writer proxy. :type extraArgs: A variadic list of `key=value` pairs giving values of specific named properties in the writer.""" if not filename: raise RuntimeError("filename must be specified") session = servermanager.ActiveConnection.Session writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory() if writer_factory.GetNumberOfRegisteredPrototypes() == 0: writer_factory.UpdateAvailableWriters() if not proxy: proxy = GetActiveSource() if not proxy: raise RuntimeError("Could not locate source to write") writer_proxy = writer_factory.CreateWriter(filename, proxy.SMProxy, proxy.Port) writer_proxy.UnRegister(None) pyproxy = servermanager._getPyProxy(writer_proxy) if pyproxy and extraArgs: SetProperties(pyproxy, **extraArgs) return pyproxy
[docs]def SaveData(filename, proxy=None, **extraArgs): """Save data produced by the `proxy` parameter into a file. Properties to configure the writer can be passed in as keyword arguments. Example usage:: SaveData("sample.pvtp", source0) SaveData("sample.csv", FieldAssociation="Points") :param filenam: Path where output file should be saved. :type filename: str :param proxy: Proxy to save. Optional, defaults to saving the active source. :type proxy: Source proxy. :param extraArgs: A variadic list of `key=value` pairs giving values of specific named properties in the writer.""" writer = CreateWriter(filename, proxy, **extraArgs) if not writer: raise RuntimeError("Could not create writer for specified file or data type") writer.UpdateVTKObjects() writer.UpdatePipeline() del writer
# ----------------------------------------------------------------------------- def _SaveScreenshotLegacy(filename, view=None, layout=None, magnification=None, quality=None, **params): """Legacy funcion for saving a screenshot. :param filename: Path where output screenshot should be saved. :type filename: str :param view: View proxy. Optional, defaults to using the active view. :type view: View proxy :param layout: Layout proxy containing the view. Optional, defaults to using the active layout. :type layout: Layout proxy. :param magnification: Integer magnification factor for the screenshot. Optional, defaults to no magnification. :type magnification: int :param quality: Integer quality level for the saved file. Optional, defaults to 100, or highest quality. :type quality: int :param params: A variadic list of `key=value` pairs giving values of named properties in the screenshot writer proxy. :return: `True` if writing was successful, `False` otherwise. :rtype: bool""" if view is not None and layout is not None: raise ValueError("both view and layout cannot be specified") viewOrLayout = view if view else layout viewOrLayout = viewOrLayout if viewOrLayout else GetActiveView() if not viewOrLayout: raise ValueError("view or layout needs to be specified") try: magnification = int(magnification) if int(magnification) > 0 else 1 except TypeError: magnification = 1 try: quality = max(0, min(100, int(quality))) except TypeError: quality = 100 # convert magnification to image resolution. if viewOrLayout.IsA("vtkSMViewProxy"): size = viewOrLayout.ViewSize else: assert (viewOrLayout.IsA("vtkSMViewLayoutProxy")) exts = [0] * 4 viewOrLayout.GetLayoutExtent(exts) size = [exts[1] - exts[0] + 1, exts[3] - exts[2] + 1] imageResolution = (size[0] * magnification, size[1] * magnification) import os.path _, extension = os.path.splitext(filename) if (extension == '.jpg'): return SaveScreenshot(filename, viewOrLayout, ImageResolution=imageResolution, Quality=quality) elif (extension == '.png'): compression = int(((quality * 0.01) - 1.0) * -9.0) return SaveScreenshot(filename, viewOrLayout, ImageResolution=imageResolution, CompressionLevel=compression) else: return SaveScreenshot(filename, viewOrLayout, ImageResolution=imageResolution)
[docs]def SaveScreenshot(filename, viewOrLayout=None, saveInBackground=False, location=vtkPVSession.CLIENT, **params): """Save screenshot for a view or layout (collection of views) to an image. `SaveScreenshot` is used to save the rendering results to an image. :param filename: Name of the image file to save to. The filename extension is used to determine the type of image file generated. Supported extensions are `png`, `jpg`, `tif`, `bmp`, and `ppm`. :type filename: str :param viewOrLayout: The view or layout to save image from, defaults to `None`. If `None`, then the active view is used, if available. To save image from a single view, this must be set to a view, to save an image from all views in a layout, pass the layout. :type viewOrLayout: View or layout proxy. Optional. :param saveInBackground: If set to `True`, the screenshot will be saved by a different thread and run in the background. In such circumstances, one can wait until the file is written by calling :func:`WaitForScreenshot(filename)`. :type saveInBackground: bool :param location: Location where the screenshot should be saved. This can be one of the following values: `vtkPVSession.CLIENT`, `vtkPVSession.DATA_SERVER`. Optional, defaults to `vtkPVSession.CLIENT`. :type location: `vtkPVSession.ServerFlags` enum **Keyword Parameters (optional)** ImageResolution (tuple(int, int)) A 2-tuple to specify the output image resolution in pixels as `(width, height)`. If not specified, the view (or layout) size is used. FontScaling (str) Specify whether to scale fonts proportionally (`"Scale fonts proportionally"`) or not (`"Do not scale fonts"`). Defaults to `"Scale fonts proportionally"`. SeparatorWidth (int) When saving multiple views in a layout, specify the width (in approximate pixels) for a separator between views in the generated image. SeparatorColor (tuple(float, float, float)) Specify the color for separator between views, if applicable. OverrideColorPalette (:obj:str, optional) Name of the color palette to use, if any. If none specified, current color palette remains unchanged. StereoMode (str) Stereo mode to use, if any. Available values are `"No stereo"`, `"Red-Blue"`, `"Interlaced"`, `"Left Eye Only"`, `"Right Eye Only"`, `"Dresden"`, `"Anaglyph"`, `"Checkerboard"`, `"Side-by-Side Horizontal"`, and the default `"No change"`. TransparentBackground (int) Set to 1 (or True) to save an image with background set to alpha=0, if supported by the output image format. In addition, several format-specific keyword parameters can be specified. The format is chosen based on the file extension. For JPEG (`*.jpg`), the following parameters are available (optional) Quality (int) [0, 100] Specify the JPEG compression quality. `O` is low quality (maximum compression) and `100` is high quality (least compression). Progressive (int): Set to 1 (or True) to save progressive JPEG. For PNG (`*.png`), the following parameters are available (optional) CompressionLevel (int) [0, 9] Specify the *zlib* compression level. `0` is no compression, while `9` is maximum compression. **Legacy Parameters** Prior to ParaView version 5.4, the following parameters were available and are still supported. However, they cannot be used together with other keyword parameters documented earlier. view (proxy) Single view to save image from. layout (proxy) Layout to save image from. magnification (int) Magnification factor to use to save the output image. The current view (or layout) size is scaled by the magnification factor provided. quality (int) Output image quality, a number in the range [0, 100]. """ # Let's handle backwards compatibility. # Previous API for this method took the following arguments: # SaveScreenshot(filename, view=None, layout=None, magnification=None, quality=None) # If we notice any of the old arguments, call legacy method. if "magnification" in params or "quality" in params: if viewOrLayout is not None and not "view" in params: # since in previous variant, view could have been passed as a # positional argument, we handle it. params["view"] = viewOrLayout return _SaveScreenshotLegacy(filename, **params) # sometimes users love to pass 'view' or 'layout' as keyword arguments # even though the signature for this function doesn't support it. let's # handle that, it's easy enough. if viewOrLayout is None: if "view" in params: viewOrLayout = params["view"] del params["view"] elif "layout" in params: viewOrLayout = params["layout"] del params["layout"] # use active view if no view or layout is specified. viewOrLayout = viewOrLayout if viewOrLayout else GetActiveView() if not viewOrLayout: raise ValueError("A view or layout must be specified.") controller = servermanager.ParaViewPipelineController() options = servermanager.misc.SaveScreenshot() controller.PreInitializeProxy(options) options.SaveInBackground = saveInBackground options.Layout = viewOrLayout if viewOrLayout.IsA("vtkSMViewLayoutProxy") else None options.View = viewOrLayout if viewOrLayout.IsA("vtkSMViewProxy") else None options.SaveAllViews = True if viewOrLayout.IsA("vtkSMViewLayoutProxy") else False # this will choose the correct format. options.UpdateDefaultsAndVisibilities(filename) controller.PostInitializeProxy(options) # explicitly process format properties. formatProxy = options.Format formatProperties = formatProxy.ListProperties() for prop in formatProperties: if prop in params: formatProxy.SetPropertyWithName(prop, params[prop]) del params[prop] SetProperties(options, **params) return options.WriteImage(filename, location)
# -----------------------------------------------------------------------------
[docs]def SetNumberOfCallbackThreads(n): """Sets the number of threads used by the threaded callback queue that can be used for saving screenshots. :parameter n: Number of callback threads. :type n: int""" paraview.modules.vtkRemotingSetting.GetInstance().SetNumberOfCallbackThreads(n)
# -----------------------------------------------------------------------------
[docs]def GetNumberOfCallbackThreads(n): """Gets the number of threads used by the threaded callback queue that can be used for saving screenshots. :parameter n: Not used :type n: int""" paraview.modules.vtkRemotingSetting.GetInstance().GetNumberOfCallbackThreads()
# -----------------------------------------------------------------------------
[docs]def SetNumberOfSMPThreads(n): """Sets the number of threads used by vtkSMPTools. It is used in various filters. """ paraview.modules.vtkRemotingSetting.GetInstance().SetNumberOfSMPThreads(n) # ----------------------------------------------------------------------------- """Gets the number of threads used by vtkSMPTools. It is used in various filters. """
[docs]def GetNumberOfSMPThreads(n): paraview.modules.vtkRemotingSetting.GetInstance().GetNumberOfSMPThreads()
# -----------------------------------------------------------------------------
[docs]def WaitForScreenshot(filename=None): """Pause this thread until saving a screenshot has terminated. :param filename: Path where screenshot should be saved. If no filename is provided, then this thread pauses until all screenshots have been saved. :type filename: str """ if not filename: paraview.servermanager.vtkRemoteWriterHelper.Wait() else: paraview.servermanager.vtkRemoteWriterHelper.Wait(filename)
# -----------------------------------------------------------------------------
[docs]def SaveAnimation(filename, viewOrLayout=None, scene=None, location=vtkPVSession.CLIENT, **params): """Save animation as a movie file or series of images. `SaveAnimation` is used to save an animation as a movie file (avi, mp4, or ogv) or a series of images. :param filename: Name of the output file. The extension is used to determine the type of the output. Supported extensions are `png`, `jpg`, `tif`, `bmp`, and `ppm`. Based on platform (and build) configuration, `avi`, `mp4`, and `ogv` may be supported as well. :type filename: str :param viewOrLayout: The view or layout to save image from, defaults to `None`. If `None`, then the active view is used, if available. To save an image from a single view, this must be set to a view, to save an image from all views in a layout, pass the layout. :type viewOrLayout: View or layout proxy. :param scene: Animation scene to save. If not provided, then the active scene returned by `GetAnimationScene` is used. :type scene: Animation scene proxy :param location: Location where the screenshot should be saved. This can be one of the following values: `vtkPVSession.CLIENT`, `vtkPVSession.DATA_SERVER`. The default is `vtkPVSession.CLIENT`. :type location: `vtkPVSession.ServerFlags` enum **Keyword Parameters (optional)** `SaveAnimation` supports all keyword parameters supported by `SaveScreenshot`. In addition, the following parameters are supported: FrameRate (int): Frame rate in frames per second for the output. This only affects the output when generated movies (`avi` or `ogv`), and not when saving the animation out as a series of images. FrameWindow (tuple(int,int)) To save a part of the animation, provide the range in frames or timesteps index. In addition, several format-specific keyword parameters can be specified. The format is chosen based on the file extension. For Image-based file-formats that save series of images e.g. PNG, JPEG, following parameters are available. SuffixFormat (string): Format string used to convert the frame number to file name suffix. FFMPEG avi file format supports following parameters. Compression (int) Set to 1 or True to enable compression. Quality: When compression is 1 (or True), this specifies the compression quality. `0` is worst quality (smallest file size) and `2` is best quality (largest file size). VideoForWindows (VFW) avi file format supports following parameters. Quality: This specifies the compression quality. `0` is worst quality (smallest file size) and `2` is best quality (largest file size). OGG/Theora file format supports following parameters. Quality: This specifies the compression quality. `0` is worst quality (smallest file size) and `2` is best quality (largest file size). UseSubsampling: When set to 1 (or True), the video will be encoded using 4:2:0 subsampling for the color channels. """ # use active view if no view or layout is specified. viewOrLayout = viewOrLayout if viewOrLayout else GetActiveView() if not viewOrLayout: raise ValueError("A view or layout must be specified.") scene = scene if scene else GetAnimationScene() if not scene: raise RuntimeError("Missing animation scene.") controller = servermanager.ParaViewPipelineController() options = servermanager.misc.SaveAnimation() controller.PreInitializeProxy(options) options.AnimationScene = scene options.Layout = viewOrLayout if viewOrLayout.IsA("vtkSMViewLayoutProxy") else None options.View = viewOrLayout if viewOrLayout.IsA("vtkSMViewProxy") else None options.SaveAllViews = True if viewOrLayout.IsA("vtkSMViewLayoutProxy") else False # this will choose the correct format. options.UpdateDefaultsAndVisibilities(filename) controller.PostInitializeProxy(options) # explicitly process format properties. formatProxy = options.Format formatProperties = formatProxy.ListProperties() for prop in formatProperties: if prop in params: # see comment at vtkSMSaveAnimationProxy.cxx:327 # certain 'prop' (such as FrameRate) are present # in both SaveAnimation and formatProxy (FFMPEG with # panel_visibility="never"). In this case save it only # in SaveAnimation if formatProxy.GetProperty(prop).GetPanelVisibility() != "never": formatProxy.SetPropertyWithName(prop, params[prop]) del params[prop] SetProperties(options, **params) return options.WriteAnimation(filename, location)
[docs]def WriteAnimationGeometry(filename, view=None): """Save the animation geometry from a specific view to a file specified. The animation geometry is written out as a PVD file. :param filename: The file path of the PVD file to write. :type filename: str :param view: The view holding the geometry that should be saved. Optional, defaults to the active view if possible. :type view: View proxy""" view = view if view else GetActiveView() if not view: raise ValueError("Please specify the view to use") scene = GetAnimationScene() writer = servermanager.vtkSMAnimationSceneGeometryWriter() writer.SetFileName(filename) writer.SetAnimationScene(scene.SMProxy) writer.SetViewModule(view.SMProxy) writer.Save()
[docs]def FetchData(proxy=None, **kwargs): """Fetches data from the specified data producer for processing locally. Use this function with caution since this can cause large amounts of data to be gathered and delivered to the client. If no producer is specified, the active source is used. **Basic Usage** #to fetch data from port 0 dataMap = FetchData(producer) # to fetch data from a specific port dataMap = FetchData(OutputPort(producer, 1)) `FetchData()` does not explicitly update the pipeline. It is expected that the pipeline is already updated. This will simply deliver the current data. Returns a map where the key is an integer representing a rank and value is the dataset fetched from that rank. **Keyword Parameters** The following keyword parameters can be used to customize the fetchs. GatherOnAllRanks (bool/int, optional): This is used only in symmetric batch (or ParaView-Catalyst) mode. If True, then FetchData() will gather the data on all ranks. Default is to only gather the data on the root node. SourceRanks (list(int), optional): List of ints to specity explicitly the ranks from which to fetch data. By default, data from all ranks is fetched. """ if proxy is None: proxy = GetActiveSource() if not proxy: raise RuntimeError("Cannot fetch data from invalid proxy") dataMover = servermanager.misc.DataMover() dataMover.Producer = proxy dataMover.PortNumber = proxy.Port # set properties on dataMover SetProperties(dataMover, **kwargs) dataMover.SMProxy.InvokeCommand("Execute") vtkObj = dataMover.GetClientSideObject() result = {} for i in range(vtkObj.GetNumberOfDataSets()): result[vtkObj.GetDataSetRank(i)] = vtkObj.GetDataSetAtIndex(i) del dataMover return result
# ============================================================================== # Lookup Table / Scalarbar methods # ============================================================================== # -----------------------------------------------------------------------------
[docs]def HideUnusedScalarBars(view=None): """Hides all unused scalar bars from the view. A scalar bar is used if some data is shown in that view that is coloring using the transfer function shown by the scalar bar. :param view: View in which unused scalar bars should be hidden. Optional, defaults to the active view. :type view: View proxy""" if not view: view = active_objects.view if not view: raise ValueError("'view' argument cannot be None with no active is present.") tfmgr = servermanager.vtkSMTransferFunctionManager() return tfmgr.UpdateScalarBars(view.SMProxy, tfmgr.HIDE_UNUSED_SCALAR_BARS)
[docs]def HideScalarBarIfNotNeeded(lut, view=None): """Hides the given scalar bar if it is not used by any of the displayed data. :param lut: The lookup table (lut) or scalar bar proxy :type lut: Scalar bar proxy :param view: The view in which the scalar bar should be hidden. Optional, defaults to hiding scalar bars in the active view.""" if not view: view = active_objects.view if not view: raise ValueError("'view' argument cannot be None with no active present.") tfmgr = servermanager.vtkSMTransferFunctionManager() return tfmgr.HideScalarBarIfNotNeeded(lut.SMProxy, view.SMProxy)
[docs]def UpdateScalarBars(view=None): """Hides all unused scalar bars and shows used scalar bars. A scalar bar is used if some data is shown in that view that is coloring using the transfer function shown by the scalar bar. :param view: The view in which scalar bar visibility should be changed. Optional, defaults to using the active view. :type view: View proxy""" if not view: view = active_objects.view if not view: raise ValueError("'view' argument cannot be None with no active is present.") tfmgr = servermanager.vtkSMTransferFunctionManager() return tfmgr.UpdateScalarBars(view.SMProxy, tfmgr.HIDE_UNUSED_SCALAR_BARS | tfmgr.SHOW_USED_SCALAR_BARS)
[docs]def UpdateScalarBarsComponentTitle(ctf, representation=None): """Update the component portion of the title in all scalar bars using the provided lookup table. The representation is used to recover the array from which the component title was obtained. :param ctf: The lookup table that the scalar bar represents. Optional, defaults to the representation of the active source in the active view. :type ctf: Transfer function proxy. :param representation: If provided, it is the representation to use to recover the array that provides the component title portion. Optional, defaults to the active representation. :type representation: Representation proxy :return: `True` if operation succeeded, `False` otherwise. :rtype: bool""" if not representation: view = active_objects.view proxy = active_objects.source if not view: raise ValueError("'representation' argument cannot be None with no active view.") if not proxy: raise ValueError("'representation' argument cannot be None with no active source.") representation = GetRepresentation(view, proxy) tfmgr = servermanager.vtkSMTransferFunctionManager() return tfmgr.UpdateScalarBarsComponentTitle(ctf.SMProxy, representation.SMProxy)
[docs]def GetScalarBar(ctf, view=None): """Returns the scalar bar for the given color transfer function in the given view. :param ctf: The color transfer function proxy whose scalar bar representation should be returned. :type ctf: Color transfer function proxy. :param view: View from which the scalar bar proxy should be retrieved. Optional, defaults to the active view, if possible. :type view: View proxy. :return: The scalar bar proxy for the color transfer function if found. his will either return an existing scalar bar or create a new one. :rtype: Scalar bar proxy""" view = view if view else active_objects.view if not view: raise ValueError("'view' argument cannot be None when no active view is present") tfmgr = servermanager.vtkSMTransferFunctionManager() sb = servermanager._getPyProxy( \ tfmgr.GetScalarBarRepresentation(ctf.SMProxy, view.SMProxy)) return sb
# -----------------------------------------------------------------------------
[docs]def GetColorTransferFunction(arrayname, representation=None, separate=False, **params): """Get the color transfer function used to map a data array with the given name to colors. :param arrayname: Name of the array whose color transfer function is requested. :type arrayname: str :param representation: Used to modify the array name when using a separate color transfer function. Optional, defaults to the active proxy. :type representation: Representation proxy. :param separate: If `True`, used to recover the separate color transfer function even if it is not used currently by the representation. Optional, defaults to `False`. :type separate: bool :return: This may create a new color transfer function if none exists, or return an existing one if found. :rtype: Color transfer function proxy""" if representation: if separate or representation.UseSeparateColorMap: arrayname = ("%s_%s_%s" % ("Separate", representation.SMProxy.GetGlobalIDAsString(), arrayname)) if not servermanager.ActiveConnection: raise RuntimeError("Missing active session") session = servermanager.ActiveConnection.Session tfmgr = servermanager.vtkSMTransferFunctionManager() lut = servermanager._getPyProxy( \ tfmgr.GetColorTransferFunction(arrayname, session.GetSessionProxyManager())) SetProperties(lut, **params) return lut
[docs]def GetBlockColorTransferFunction(selector, arrayname, representation=None, separate=False, **params): """Get the color transfer function used to map a data array with the given name to colors in the blocks referred to by a selector expresson. :param selector: Selector expression used to select blocks from whom the color transfer should be retrieved. :type selector: str :param arrayname: Name of the array whose color transfer function is requested. :type arrayname: str :param representation: Used to modify the array name when using a separate color transfer function. Optional, defaults to the active proxy. :type representation: Representation proxy. :param separate: If `True`, used to recover the separate color transfer function even if it is not used currently by the representation. Optional, defaults to `False`. :type separate: bool :return: This may create a new color transfer function if none exists, or return an existing one if found. :rtype: Color transfer function proxy""" if representation: if representation.GetBlockUseSeparateColorMap(selector): arrayname = \ ("%s_%s_%s_%s" % ("Separate_", representation.SMProxy.GetGlobalIDAsString(), selector, arrayname)) elif separate or representation.UseSeparateColorMap: arrayname = ("%s_%s_%s" % ("Separate", representation.SMProxy.GetGlobalIDAsString(), arrayname)) if not servermanager.ActiveConnection: raise RuntimeError("Missing active session") session = servermanager.ActiveConnection.Session tfmgr = servermanager.vtkSMTransferFunctionManager() lut = servermanager._getPyProxy( \ tfmgr.GetColorTransferFunction(arrayname, session.GetSessionProxyManager())) SetProperties(lut, **params) return lut
# -----------------------------------------------------------------------------
[docs]def GetOpacityTransferFunction(arrayname, representation=None, separate=False, **params): """Get the opacity transfer function used to map a data array with the given name to opacities in the blocks referred to by a selector expresson. :param arrayname: Name of the array whose opacity transfer function is requested. :type arrayname: str :param representation: Used to modify the array name when using a separate opacity transfer function. Optional, defaults to the active representation. :type representation: Representation proxy. :param separate: If `True`, used to recover the separate opacity transfer function even if it is not used currently by the representation. Optional, defaults to `False`. :type separate: bool :return: This may create a new opacity transfer function if none exists, or return an existing one if found. :rtype: Opacity transfer function proxy""" if representation: if separate or representation.UseSeparateColorMap: arrayname = ("%s%s_%s" % ("Separate_", representation.SMProxy.GetGlobalIDAsString(), arrayname)) if not servermanager.ActiveConnection: raise RuntimeError("Missing active session") session = servermanager.ActiveConnection.Session tfmgr = servermanager.vtkSMTransferFunctionManager() otf = servermanager._getPyProxy( \ tfmgr.GetOpacityTransferFunction(arrayname, session.GetSessionProxyManager())) SetProperties(otf, **params) return otf
[docs]def GetTransferFunction2D(arrayname, array2name=None, representation=None, separate=False, **params): """Get the 2D color transfer function used to map a data array with the given name to colors. :param arrayname: Name of the first array whose color transfer function is requested. :type arrayname: str :param array2name: Name of the second array whose color transfer function is requested. :type array2name: str :param representation: Used to modify the array name when using a separate color transfer function. Optional, defaults to the active representation. :type representation: Representation proxy. :param separate: If `True`, used to recover the separate color transfer function even if it is not used currently by the representation. Optional, defaults to `False`. :type separate: bool :return: This may create a new 2D color transfer function if none exists, or return an existing one if found. :rtype: 2D color transfer function proxy""" array2name = "" if array2name is None else ("_%s" % array2name) if representation: if separate or representation.UseSeparateColorMap: arrayname = ("%s%s_%s%s" % ("Separate_", representation.SMProxy.GetGlobalIDAsString(), arrayname, array2name)) if not servermanager.ActiveConnection: raise RuntimeError("Missing active session") session = servermanager.ActiveConnection.Session tfmgr = servermanager.vtkSMTransferFunctionManager() tf2d = servermanager._getPyProxy( \ tfmgr.GetTransferFunction2D(arrayname, session.GetSessionProxyManager())) SetProperties(tf2d, **params) return tf2d
# -----------------------------------------------------------------------------
[docs]def ImportPresets(filename, location=vtkPVSession.CLIENT): """Import presets from a file. The file can be in the legacy color map XML format or in the new JSON format. :param filename: Path of the file containing the presets. :type filename: str :param location: Where the statefile should be save, e.g., pass `vtkPVSession.CLIENT` if the statefile is located on the client system (default value), pass in `vtkPVSession.SERVERS` if on the server. Optional, defaults to `vtkPVSession.CLIENT`. :type location: `vtkPVServer.ServerFlags` enum value :return: `True` on success, `False` otherwise.""" presets = servermanager.vtkSMTransferFunctionPresets.GetInstance() return presets.ImportPresets(filename, location)
# -----------------------------------------------------------------------------
[docs]def ExportTransferFunction(colortransferfunction, opacitytransferfunction, tfname, filename, location=vtkPVSession.CLIENT): """Export transfer function to a file. The file will be saved in the new JSON format. :param colortransferfunction: The color transfer function to export. :type colortransferfunction: Color transfer function proxy. :param opacitytransferfunction: The opacity transfer functon to export, if provided. can be None. :type opacitytransferfunction: Opacity transfer function proxy. :param tfname: The name that will be given to the transfer function preset if imported back into ParaView. :type tfname: str :param filename: Path to file where exported transfer function should be saved. :type filename: str :param location: Where the statefile should be saved, e.g., pass `vtkPVSession.CLIENT` if the statefile is located on the client system (default value), pass in `vtkPVSession.SERVERS` if on the server. Optional, defaults to `vtkPVSession.CLIENT`. :type location: `vtkPVServer.ServerFlags` enum value :return: `True` on success, `False` otherwise.""" return servermanager.vtkSMTransferFunctionProxy.ExportTransferFunction( \ colortransferfunction.SMProxy, opacitytransferfunction.SMProxy, tfname, filename, location)
# -----------------------------------------------------------------------------
[docs]def CreateLookupTable(**params): """Create and return a lookup table. :param params: A variadic list of `key=value` pairs giving values of specific named properties of the lookup table. :return: Lookup table :rtype: Lookup table proxy""" lt = servermanager.rendering.PVLookupTable() controller = servermanager.ParaViewPipelineController() controller.InitializeProxy(lt) SetProperties(lt, **params) controller.RegisterColorTransferFunctionProxy(lt) return lt
# -----------------------------------------------------------------------------
[docs]def CreatePiecewiseFunction(**params): """Create and return a piecewise function. :param params: A variadic list of `key=value` pairs giving values of specific named properties of the opacity function. :return: Piecewise opacity function :rtype: Opacity functon proxy""" pfunc = servermanager.piecewise_functions.PiecewiseFunction() controller = servermanager.ParaViewPipelineController() controller.InitializeProxy(pfunc) SetProperties(pfunc, **params) controller.RegisterOpacityTransferFunction(pfunc) return pfunc
# -----------------------------------------------------------------------------
[docs]def AssignLookupTable(arrayInfo, lutName, rangeOveride=[]): """Assign a lookup table to an array by lookup table name. Example usage:: track = GetAnimationTrack("Center", 0, sphere) or arrayInfo = source.PointData["Temperature"] AssignLookupTable(arrayInfo, "Cool to Warm") :param arrayInfo: The information object for the array. The array name and its range is determined using the info object provided. :type arrayInfo: `paraview.modules.vtkRemotingCore.vtkPVArrayInformation` :param lutName: The name for the transfer function preset. :type lutName: str :param rangeOveride: The range to use instead of the range of the array determined using the `arrayInfo` parameter. Defaults to `[]`, meaning the array info range will be used. :type rangeOveride: 2-element tuple or list of floats :return: `True` on success, `False` otherwise. :rtype: bool""" # If the named LUT is not in the presets, see if it was one that was removed and # substitute it with the backwards compatibility helper presets = servermanager.vtkSMTransferFunctionPresets.GetInstance() reverse = False if not presets.HasPreset(lutName): (lutName, reverse) = paraview._backwardscompatibilityhelper.lookupTableUpdate(lutName) # If no alternate LUT exists, raise an exception if not presets.HasPreset(lutName): raise RuntimeError("no preset with name `%s` present", lutName) # Preset found. Apply it. lut = GetColorTransferFunction(arrayInfo.Name) if not lut.ApplyPreset(lutName): return False if rangeOveride: lut.RescaleTransferFunction(rangeOveride) # Reverse if necessary for backwards compatibility if reverse: lut.InvertTransferFunction() return True
# -----------------------------------------------------------------------------
[docs]def GetLookupTableNames(): """Returns a list containing the currently available transfer function preset names. :return: List of currently availabe transfer function preset names. :rtype: List of str""" presets = servermanager.vtkSMTransferFunctionPresets.GetInstance() return [presets.GetPresetName(index) for index in range(presets.GetNumberOfPresets())]
# -----------------------------------------------------------------------------
[docs]def LoadLookupTable(fileName): """Load transfer function preset from a file. Both JSON (new) and XML (legacy) preset formats are supported. :param fileName: If the filename ends with a .xml, it's assumed to be a legacy color map XML and will be converted to the new format before processing. :type fileName: str :return: `True` if successful, `False` otherwise. :rtype: bool """ presets = servermanager.vtkSMTransferFunctionPresets.GetInstance() return presets.ImportPresets(fileName)
# ----------------------------------------------------------------------------- # TODO: Change this to take the array name and number of components. Register # the lt under the name ncomp.array_name
[docs]def MakeBlueToRedLT(min, max): """ Create a LookupTable that go from blue to red using the scalar range provided by the min and max arguments. :param min: Minimum range value. :type min: float :param max: Maximum range value. :type max: float :return: the blue-to-red lookup table :rtype: Lookup table proxy. """ # Define RGB points. These are tuples of 4 values. First one is # the scalar values, the other 3 the RGB values. rgbPoints = [min, 0, 0, 1, max, 1, 0, 0] return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
# ============================================================================== # General puprpose links methods # ============================================================================== # ============================================================================== # ViewLink methods # ============================================================================== # ============================================================================== # CameraLink methods # ============================================================================== # ----------------------------------------------------------------------------- # ============================================================================== # SelectionLink methods # ============================================================================== # ----------------------------------------------------------------------------- # ============================================================================== # Animation methods # ==============================================================================
[docs]def GetTimeKeeper(): """Returns the timekeeper proxy for the active session. Timekeeper is often used to manage time step information known to the ParaView application. :return: timekeeper :rtype: :class:`paraview.servermanager.TimeKeeper`""" if not servermanager.ActiveConnection: raise RuntimeError("Missing active session") session = servermanager.ActiveConnection.Session controller = servermanager.ParaViewPipelineController() return controller.FindTimeKeeper(session)
[docs]def GetAnimationScene(): """Returns the application-wide animation scene. ParaView has only one global animation scene. This method provides access to that. You are free to create additional animation scenes directly, but those scenes won't be shown in the ParaView GUI. :return: The animation scene :rtype: :class:`paraview.servermanager.AnimationScene`""" if not servermanager.ActiveConnection: raise RuntimeError("Missing active session") session = servermanager.ActiveConnection.Session controller = servermanager.ParaViewPipelineController() return controller.GetAnimationScene(session)
# -----------------------------------------------------------------------------
[docs]def AnimateReader(reader=None, view=None): """This is a utility function that, given a reader and a view animates over all time steps of the reader. :param reader: The reader source to iterate over. Optional, defaults to the active source. :type reader: reader proxy :param view: The view to animate. Optional, defaults to the active view. :type view: view proxy :return: A new animation scene used to play the animation. :rtype: :class:`paraview.simple.AnimationSceneProxy`""" if not reader: reader = active_objects.source if not view: view = active_objects.view return servermanager.AnimateReader(reader, view)
# -----------------------------------------------------------------------------
[docs]def GetRepresentationAnimationHelper(sourceproxy): """Method that returns the representation animation helper for a source proxy. It creates a new one if none exists.""" # ascertain that proxy is a source proxy if not sourceproxy in GetSources().values(): return None for proxy in servermanager.ProxyManager(): if proxy.GetXMLName() == "RepresentationAnimationHelper" and \ proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy): return proxy # helper must have been created during RegisterPipelineProxy(). return None
# -----------------------------------------------------------------------------
[docs]def GetAnimationTrack(propertyname_or_property, index=None, proxy=None): """Returns an animation cue for the property. If one doesn't exist then a new one will be created. Typical usage:: track = GetAnimationTrack("Center", 0, sphere) or track = GetAnimationTrack(sphere.GetProperty("Radius")) or # this returns the track to animate visibility of the active source in # all views. track = GetAnimationTrack("Visibility") For animating properties on implicit planes etc., use the following signatures:: track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or track = GetAnimationTrack("Origin", 0, slice.SliceType) """ if not proxy: proxy = GetActiveSource() if not isinstance(proxy, servermanager.Proxy): raise TypeError("proxy must be a servermanager.Proxy instance") if isinstance(propertyname_or_property, str): propertyname = propertyname_or_property elif isinstance(propertyname_or_property, servermanager.Property): prop = propertyname_or_property propertyname = prop.Name proxy = prop.Proxy else: raise TypeError("propertyname_or_property must be a string or servermanager.Property") # To handle the case where the property is actually a "display" property, in # which case we are actually animating the "RepresentationAnimationHelper" # associated with the source. if propertyname in ["Visibility", "Opacity"] and proxy.GetXMLName() != "RepresentationAnimationHelper": proxy = GetRepresentationAnimationHelper(proxy) if not proxy or not proxy.GetProperty(propertyname): raise AttributeError("Failed to locate property %s" % propertyname) scene = GetAnimationScene() for cue in scene.Cues: try: if cue.AnimatedProxy == proxy and \ cue.AnimatedPropertyName == propertyname: if index == None or index == cue.AnimatedElement: return cue except AttributeError: pass # matching animation track wasn't found, create a new one. cue = KeyFrameAnimationCue() cue.AnimatedProxy = proxy cue.AnimatedPropertyName = propertyname if index != None: cue.AnimatedElement = index scene.Cues.append(cue) return cue
# -----------------------------------------------------------------------------
[docs]def GetCameraTrack(view=None): """Returns the camera animation track for the given view. :param view: The view whose camera animation track should be retrieved. If no view is specified, the active view will be used. If no existing camera animation track is found, a new one will be created. :type view: View proxy :return: Camera animation cue :rtype: :class:`paraview.servermanager.CameraAnimationCue` """ if not view: view = GetActiveView() if not view: raise ValueError("No view specified") scene = GetAnimationScene() for cue in scene.Cues: if cue.AnimatedProxy == view and \ cue.GetXMLName() == "CameraAnimationCue": return cue # no cue was found, create a new one. cue = CameraAnimationCue() cue.AnimatedProxy = view scene.Cues.append(cue) return cue
# -----------------------------------------------------------------------------
[docs]def GetTimeTrack(): """Returns the animation track used to control the time requested from all sources during playback :return: The time animation track. :rtype: :class:`paraview.servermanager.TimeAnimationCue`""" scene = GetAnimationScene() if not scene: raise RuntimeError("Missing animation scene") controller = servermanager.ParaViewPipelineController() return controller.GetTimeAnimationTrack(scene)
# ============================================================================== # Plugin Management # ==============================================================================
[docs]def LoadXML(xmlstring, ns=None): """Given a server manager XML as a string, parse and process it. If you loaded the simple module with ``from paraview.simple import *``, make sure to pass ``globals()`` as the second arguments:: LoadXML(xmlstring, globals()) Otherwise, the new functions will not appear in the global namespace. :param xmlstring: XML string containing server manager definitions. :type xmlstring: str :param ns: Namespace in which new functions will be defined. Optional, defaults to `None`. :type ns: dict """ if not ns: ns = globals() servermanager.LoadXML(xmlstring) _add_functions(ns)
# -----------------------------------------------------------------------------
[docs]def LoadPlugin(filename, remote=True, ns=None): """Loads a ParaView plugin and updates this module with new constructors if any. The remote argument (default to ``True``) is to specify whether the plugin will be loaded on the client (``remote=False``) or on the server (``remote=True``). If you loaded the simple module with ``from paraview.simple import *``, make sure to pass ``globals()`` as an argument:: LoadPlugin("myplugin", False, globals()) # to load on client LoadPlugin("myplugin", True, globals()) # to load on server LoadPlugin("myplugin", ns=globals()) # to load on server Otherwise, the new functions will not appear in the global namespace. :param filename: Path to the plugin to load. :type filename: str :param remote: If `True`, loads the plugin on the server unless the connection is not remote. If `False`, loads the plugin on the client. Optional, defaults to `True`. :type remote: bool :param ns: Namespace in which new functions will be loaded. Optional, defaults to `None`. :type ns: dict :return: None """ return LoadPlugins(filename, remote=remote, ns=ns)
# -----------------------------------------------------------------------------
[docs]def LoadPlugins(*args, **kwargs): """Loads ParaView plugins and updates this module with new constructors if any. The remote keyword argument (default to ``True``) is to specify whether the plugin will be loaded on client (``remote=False``) or on server (``remote=True``). Proxy definition updates are deferred until all plugins have been read, which can be more computationally efficient when multiple plugins are loaded in sequence. If you loaded the simple module with ``from paraview.simple import *``, make sure to pass ``globals()`` as a keyword argument:: LoadPlugins("myplugin1", "myplugin2", remote=False, ns=globals()) # to load on client LoadPlugins("myplugin", "myplugin2", remote=True, ns=globals()) # to load on server LoadPlugins("myplugin", "myplugin2", ns=globals()) # to load on server Otherwise, the new functions will not appear in the global namespace. Note, `remote=True` has no effect when the connection is not remote. """ remote = True if 'remote' in kwargs: remote = kwargs['remote'] ns = globals() if 'ns' in kwargs and kwargs['ns']: ns = kwargs['ns'] servermanager.vtkSMProxyManager.GetProxyManager().SetBlockProxyDefinitionUpdates(True) for arg in args: servermanager.LoadPlugin(arg, remote) servermanager.vtkSMProxyManager.GetProxyManager().SetBlockProxyDefinitionUpdates(False) servermanager.vtkSMProxyManager.GetProxyManager().UpdateProxyDefinitions() _add_functions(ns)
# -----------------------------------------------------------------------------
[docs]def LoadDistributedPlugin(pluginname, remote=True, ns=None): """Loads a plugin that's distributed with the ParaView executable. This uses the information known about plugins distributed with ParaView to locate the shared library for the plugin to load. :param pluginname: Short name of the plugin (not a file path) :type pluginname: str :param remote: If `True`, loads the plugin on the server unless the connection is not remote. If `False`, loads the plugin on the client. Optional, defaults to `True`. :type remote: bool :param ns: Namespace in which new functions will be loaded. Optional, defaults to `None`. :type ns: dict :raises RuntimeError: If the plugin was not found. """ if not servermanager.ActiveConnection: raise RuntimeError("Cannot load a plugin without a session.") conn = servermanager.ActiveConnection do_remote = remote and conn.IsRemote() plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager() if do_remote: session = servermanager.ActiveConnection.Session info = plm.GetRemoteInformation(session) else: info = plm.GetLocalInformation() for cc in range(0, info.GetNumberOfPlugins()): if info.GetPluginName(cc) == pluginname: return LoadPlugin(info.GetPluginFileName(cc), remote=do_remote, ns=ns) raise RuntimeError("Plugin '%s' not found" % pluginname)
# ============================================================================== # Custom Filters Management # ==============================================================================
[docs]def LoadCustomFilters(filename, ns=None): """Loads a custom filter XML file and updates this module with new constructors if any. If you loaded the simple module with ``from paraview.simple import *``, make sure to pass ``globals()`` as an argument. :param filename: Path to XML file with custom filter definitions. :type filename: str :param ns: Namespace in which new functions will be loaded. Optional, defaults to `None`. :type ns: dict """ servermanager.ProxyManager().SMProxyManager.LoadCustomProxyDefinitions(filename) if not ns: ns = globals() _add_functions(ns)
# ============================================================================== # Selection Management # ============================================================================== def _select(seltype, query=None, proxy=None): """Function to help create query selection sources. :param seltype: Selection type :type seltype: str :param query: Query expression that defines the selection. Optional, defaults to expression that selects all cells. :type query: str :param proxy: The source proxy to select from. Optional, defaults to the active source. :type proxy: Source proxy. :return: The created selection source. :rtype: :class:`servermanager.sources.SelectionQuerySource`""" if not proxy: proxy = GetActiveSource() if not proxy: raise RuntimeError("No active source was found.") if not query: # This ends up being true for all cells. query = "id >= 0" from paraview.vtk import vtkDataObject # Note, selSource is not registered with the proxy manager. selSource = servermanager.sources.SelectionQuerySource() if seltype.lower() == "point": elementType = vtkDataObject.POINT elif seltype.lower() == "cell": elementType = vtkDataObject.CELL else: elementType = seltype selSource.ElementType = elementType selSource.QueryString = str(query) proxy.SMProxy.SetSelectionInput(proxy.Port, selSource.SMProxy, 0) return selSource # -----------------------------------------------------------------------------
[docs]def SelectCells(query=None, proxy=None): """Select cells satisfying the query. :param query: The selection query. If `None`, then all cells are selected. :type query: str :param proxy: The source proxy to select from. Optional, defaults to the active source. :type proxy: Source proxy :return: Selection source :rtype: :class:`servermanager.sources.SelectionQuerySource`""" return _select("CELL", query, proxy)
# -----------------------------------------------------------------------------
[docs]def SelectPoints(query=None, proxy=None): """Select points satisfying the query. :param query: The selection query. If `None`, then all points are selected. :type query: str :param proxy: The source proxy to select from. Optional, defaults to the active source. :type proxy: Source proxy :return: Selection source :rtype: :class:`servermanager.sources.SelectionQuerySource`""" return _select("POINT", query, proxy)
# -----------------------------------------------------------------------------
[docs]def ClearSelection(proxy=None): """Clears the selection on the active source. :param proxy: Source proxy whose selection should be cleared. :type proxy: Source proxy""" if not proxy: proxy = GetActiveSource() if not proxy: raise RuntimeError("No active source was found.") proxy.SMProxy.SetSelectionInput(proxy.Port, None, 0)
# ============================================================================== # Dynamic lights. # ==============================================================================
[docs]def CreateLight(): """Makes a new light and returns it, unattached to a view. :return: The new light :rtype: :class:`paraview.servermanager.Light`""" pxm = servermanager.ProxyManager() lightproxy = pxm.NewProxy("additional_lights", "Light") controller = servermanager.ParaViewPipelineController() controller.SMController.RegisterLightProxy(lightproxy, None) return servermanager._getPyProxy(lightproxy)
[docs]def AddLight(view=None): """Makes a new light and adds it to the designated or active view. :param view: The view to add the light to. Optional, defaults to the active view. :return: The new light :rtype: :class:`paraview.servermanager.Light`""" view = view if view else GetActiveView() if not view: raise ValueError("No 'view' was provided and no active view was found.") if view.IsA("vtkSMRenderViewProxy") is False: return lightproxy = CreateLight() nowlights = [l for l in view.AdditionalLights] nowlights.append(lightproxy) view.AdditionalLights = nowlights # This is not the same as returning lightProxy return GetLight(len(view.AdditionalLights) - 1, view)
[docs]def RemoveLight(light): """Removes an existing light from its view. :param light: The light to be removed. :type light: :class:`paraview.servermanager.Light`""" if not light: raise ValueError("No 'light' was provided.") view = GetViewForLight(light) if view: if (not view.IsA("vtkSMRenderViewProxy")) or (len(view.AdditionalLights) < 1): raise RuntimeError("View retrieved inconsistent with owning a 'light'.") nowlights = [l for l in view.AdditionalLights if l != light] view.AdditionalLights = nowlights controller = servermanager.ParaViewPipelineController() controller.SMController.UnRegisterProxy(light.SMProxy)
[docs]def GetLight(number, view=None): """Get a previously added light. :param number: The index of the light to obtain. :type number: int :param view: The view holding the light. :type view: View proxy. Option, if not provided the active view is used. :return: The requested light. :rtype: :class:`paraview.servermanager.Light` or `None` """ if not view: view = active_objects.view numlights = len(view.AdditionalLights) if numlights < 1 or number < 0 or number >= numlights: return return view.AdditionalLights[number]
[docs]def GetViewForLight(proxy): """Given a light proxy, find which view it belongs to :param proxy: The light proxy whose view you want to retrieve. :type proxy: Light proxy :return: The view associated with the light if found, otherwise `None` :rtype: View proxy or `None`""" # search current views for this light. for cc in range(proxy.GetNumberOfConsumers()): consumer = proxy.GetConsumerProxy(cc) consumer = consumer.GetTrueParentProxy() if consumer.IsA("vtkSMRenderViewProxy") and proxy in consumer.AdditionalLights: return consumer return None
# ============================================================================== # Materials. # ==============================================================================
[docs]def GetMaterialLibrary(): """Returns the material library for the active session. :return: The material library :rtype: :class:`paraview.servermanager.MaterialLibrary`""" if not servermanager.ActiveConnection: raise RuntimeError("Missing active session") session = servermanager.ActiveConnection.Session controller = servermanager.ParaViewPipelineController() return controller.FindMaterialLibrary(session)
# ============================================================================== # Textures. # ==============================================================================
[docs]def CreateTexture(filename=None, trivial_producer_key=None, proxyname=None): """Creates and returns a new ImageTexture proxy. The texture is not attached to anything by default but it can be applied to things, for example the view, like so:: GetActiveView().UseTexturedBackground = 1 GetActiveView().BackgroundTexture = CreateTexture("foo.png") :param filename: The name of the image file to load as a texture. If can be `None`, in which case the texture is read from a trivial producer indentified by the `trivial_producer_key` :type filename: str :param trivial_producer_key: Identifier of the texture image source on the server. This is mainly used by scene importers when `filename` is `None`. :type trivial_producer_key: str :param proxyname: The name for the texture when it is registered in ParaView. :type proxyname: str :return: The newly created texture. :rtype: Image texture proxy. """ pxm = servermanager.ProxyManager() textureproxy = pxm.NewProxy("textures", "ImageTexture") controller = servermanager.ParaViewPipelineController() py_textureproxy = servermanager._getPyProxy(textureproxy) if filename is not None: py_textureproxy.Mode = "ReadFromFile" controller.SMController.RegisterTextureProxy(textureproxy, filename) elif trivial_producer_key is not None: py_textureproxy.Mode = "ReadFromMemory" py_textureproxy.TrivialProducerKey = trivial_producer_key controller.SMController.RegisterTextureProxy(textureproxy, trivial_producer_key, proxyname) return py_textureproxy
[docs]def FindTextureOrCreate(registrationName, filename=None, trivial_producer_key=None): """Finds or creates a new ImageTexture proxy. :param registrationName: The name for the texture when it is registered in ParaView. :type registrationName: str :param filename: Path to the texture image source file. Optional, if not provided, the `trivial_producer_key` should be provided to tell which image source to use for the texture. :type filename: str :param trivial_producer_key: Identifier of the texture image source on the server. This is mainly used by scene importers when `filename` is `None`. :type trivial_producer_key: str""" pxm = servermanager.ProxyManager() textureproxy = pxm.GetProxy("textures", registrationName) if textureproxy is None: return CreateTexture(filename, trivial_producer_key, registrationName) else: return textureproxy
# ============================================================================== # Miscellaneous functions. # ==============================================================================
[docs]def ShowInteractiveWidgets(proxy=None): """If possible in the current environment, this function will request the application to show the interactive widget(s) for the given proxy. :param proxy: The proxy whose associated interactive widgets should be shown. Optional, if not provided the active source's widgets are shown. :type proxy: Source proxy.""" proxy = proxy if proxy else GetActiveSource() if not proxy: raise ValueError("No 'proxy' was provided and no active source was found.") _InvokeWidgetUserEvent(proxy, "ShowWidget")
[docs]def HideInteractiveWidgets(proxy=None): """If possible in the current environment, this function will request the application to hide the interactive widget(s) for the given proxy. :param proxy: The proxy whose associated interactive widgets should be hidden. Optional, if not provided the active source's widgets are hidden. :type proxy: Source proxy.""" proxy = proxy if proxy else GetActiveSource() if not proxy: raise ValueError("No 'proxy' was provided and no active source was found.") _InvokeWidgetUserEvent(proxy, "HideWidget")
def _InvokeWidgetUserEvent(proxy, event): """Internal method used by ShowInteractiveWidgets/HideInteractiveWidgets""" if proxy: proxy.InvokeEvent('UserEvent', event) # Since in 5.0 and earlier, ShowInteractiveWidgets/HideInteractiveWidgets # was called with the proxy being the filter proxy (eg. Clip) and not the # proxy that has the widget i.e. (Clip.ClipType), we explicitly handle it # by iterating of proxy list properties and then invoking the event on # their value proxies too. for smproperty in proxy: if smproperty.FindDomain("vtkSMProxyListDomain"): _InvokeWidgetUserEvent(smproperty.GetData(), event)
[docs]def ExportView(filename, view=None, **params): """Export a view to the specified output file. Based on the view and file extension, an exporter of the right type will be chosen to export the view. :param filename: Name of the exported file. :type filename: str :param view: The view proxy to export. Optional, defaults to the active view. :type view: View proxy. :param params: A variadic list of `key=value` pairs giving values of specific named properties of the exporter.""" view = view if view else GetActiveView() if not view: raise ValueError("No 'view' was provided and no active view was found.") if not filename: raise ValueError("No filename specified") # ensure that the view is up-to-date. view.StillRender() helper = servermanager.vtkSMViewExportHelper() proxy = helper.CreateExporter(filename, view.SMProxy) if not proxy: raise RuntimeError("Failed to create exporter for ", filename) proxy.UnRegister(None) proxy = servermanager._getPyProxy(proxy) SetProperties(proxy, **params) proxy.Write() del proxy del helper
[docs]def ImportView(filename, view=None, **params): """Import a view from a specified input scene file. :param filename: The name of the file to import. :type filename: str :param view: View proxy into which the scene should be imported. Optional, defaults to the active view. :type view: View proxy. :param params: A variadic list of `key=value` pairs giving values of specific named properties of the importer.""" view = view if view else GetActiveView() if not view: raise ValueError ("No 'view' was provided and no active view was found.") if not filename: raise ValueError ("No filename specified") session = servermanager.ActiveConnection.Session proxy = servermanager.vtkSMImporterFactory.CreateImporter(filename, session) if not proxy: raise RuntimeError ("Failed to create importer for ", filename) proxy.UnRegister(None) proxy = servermanager._getPyProxy(proxy) SetProperties(proxy, **params) proxy.UpdatePipelineInformation() proxy.Import(view) view.StillRender() del proxy
[docs]def ResetProperty(propertyName, proxy=None, restoreFromSettings=True): """Resets a proxy property to its default value. :param propertyName: Name of the property to reset. :type propertyName: str :param proxy: The proxy whose property should be reset. Optional, defaults to the active source. :param restoreFromSettings: If `True`, the property will be reset to the default value stored in the settings if available, otherwise it will be reset to ParaView's application default value. Optional, defaults to `True`. :type restoreFromSettings: bool""" if proxy == None: proxy = GetActiveSource() propertyToReset = proxy.SMProxy.GetProperty(propertyName) if propertyToReset != None: propertyToReset.ResetToDefault() if restoreFromSettings: settings = paraview.servermanager.vtkSMSettings.GetInstance() settings.GetPropertySetting(propertyToReset) proxy.SMProxy.UpdateVTKObjects()
[docs]def GetOpenGLInformation(location=servermanager.vtkSMSession.CLIENT): """Recover OpenGL information on either the client or server. :param location: Where the OpenGL information should be retrieved, e.g., pass `vtkPVSession.CLIENT` if you want OpenGL info from the client system (default value), pass in `vtkPVSession.SERVERS` if you want the server. :type location: `vtkPVServer.ServerFlags` enum value""" openGLInfo = paraview.modules.vtkRemotingViews.vtkPVOpenGLInformation() session = servermanager.vtkSMProxyManager.GetProxyManager().GetActiveSession() session.GatherInformation(location, openGLInfo, 0) return openGLInfo
# ============================================================================== # Usage and demo code set # ==============================================================================
[docs]def demo1(): """ Simple demo that create the following pipeline:: sphere - shrink + cone + > append """ # Create a sphere of radius = 2, theta res. = 32 # This object becomes the active source. ss = Sphere(Radius=2, ThetaResolution=32) # Apply the shrink filter. The Input property is optional. If Input # is not specified, the filter is applied to the active source. shr = Shrink(Input=ss) # Create a cone source. cs = Cone() # Append cone and shrink app = AppendDatasets() app.Input = [shr, cs] # Show the output of the append filter. The argument is optional # as the app filter is now the active object. Show(app) # Render the default view. Render()
# -----------------------------------------------------------------------------
[docs]def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"): """This demo shows the use of readers, data information and display properties.""" # Create the exodus reader and specify a file name reader = ExodusIIReader(FileName=fname) # Get the list of point arrays. avail = reader.PointVariables.Available print(avail) # Select all arrays reader.PointVariables = avail # Turn on the visibility of the reader Show(reader) # Set representation to wireframe SetDisplayProperties(Representation="Wireframe") # Black background is not pretty SetViewProperties(Background=[0.4, 0.4, 0.6]) Render() # Change the elevation of the camera. See VTK documentation of vtkCamera # for camera parameters. # NOTE: THIS WILL BE SIMPLER GetActiveCamera().Elevation(45) Render() # Now that the reader executed, let's get some information about it's # output. pdi = reader[0].PointData # This prints a list of all read point data arrays as well as their # value ranges. print('Number of point arrays:', len(pdi)) for i in range(len(pdi)): ai = pdi[i] print("----------------") print("Array:", i, " ", ai.Name, ":") numComps = ai.GetNumberOfComponents() print("Number of components:", numComps) for j in range(numComps): print("Range:", ai.GetRange(j)) # White is boring. Let's color the geometry using a variable. # First create a lookup table. This object controls how scalar # values are mapped to colors. See VTK documentation for # details. # Map min (0.00678) to blue, max (0.0288) to red SetDisplayProperties(LookupTable=MakeBlueToRedLT(0.00678, 0.0288)) # Color by point array called Pres SetDisplayProperties(ColorArrayName=("POINTS", "Pres")) Render()
# -----------------------------------------------------------------------------
[docs]def ListProperties(proxyOrCreateFunction): """Given a proxy or a proxy creation function, e.g. paraview.simple.Sphere, returns the list of properties for the proxy that would be created. :param proxyOrCreateFunction: Proxy or proxy creation function whose property names are desired. :type proxyOrCreateFunction: Proxy or proxy creation function :return: List of property names :rtype: List of str""" try: return _listProperties(proxyOrCreateFunction) except: pass try: return proxyOrCreateFunction.ListProperties() except: pass return None
# ============================================================================== # Set of Internal functions # ============================================================================== def _initializeSession(connection): """Internal method used to initialize a session. Users don't need to call this directly. Whenever a new session is created this method is called by API in this module.""" if not connection: raise RuntimeError("'connection' cannot be empty.") controller = servermanager.ParaViewPipelineController() controller.InitializeSession(connection.Session) def _create_func(key, module, skipRegisteration=False): """Internal function.""" def CreateObject(*input, **params): """ This function creates a new proxy. For pipeline objects that accept inputs, all non-keyword arguments are assumed to be inputs. All keyword arguments are assumed to be property-value pairs and are passed to the new proxy. """ registrationName = None for nameParam in ['registrationName', 'guiName']: if nameParam in params: registrationName = params[nameParam] del params[nameParam] # Create a controller instance. controller = servermanager.ParaViewPipelineController() from .catalyst.detail import IsInsituInput, CreateProducer if IsInsituInput(registrationName): # This is a catalyst input, replace with a trivial producer px = CreateProducer(registrationName) else: # Instantiate the actual object from the given module. px = paraview._backwardscompatibilityhelper.GetProxy(module, key, no_update=True) # preinitialize the proxy. controller.PreInitializeProxy(px) # Make sure non-keyword arguments are valid for inp in input: if inp != None and not isinstance(inp, servermanager.Proxy): if px.GetProperty("Input") != None: raise RuntimeError("Expecting a proxy as input.") else: raise RuntimeError("This function does not accept non-keyword arguments.") # Assign inputs inputName = servermanager.vtkSMCoreUtilities.GetInputPropertyName(px.SMProxy, 0) if px.GetProperty(inputName) != None: if len(input) > 0: px.SetPropertyWithName(inputName, input) else: # If no input is specified, try the active pipeline object if px.GetProperty(inputName).GetRepeatable() and active_objects.get_selected_sources(): px.SetPropertyWithName(inputName, active_objects.get_selected_sources()) elif active_objects.source: px.SetPropertyWithName(inputName, active_objects.source) else: if len(input) > 0: raise RuntimeError("This function does not expect an input.") # Pass all the named arguments as property,value pairs SetProperties(px, **params) # post initialize controller.PostInitializeProxy(px) if isinstance(px, servermanager.MultiplexerSourceProxy): px.UpdateDynamicProperties() if not skipRegisteration: # Register the proxy with the proxy manager (assuming we are only using # these functions for pipeline proxies or animation proxies. if isinstance(px, servermanager.SourceProxy): controller.RegisterPipelineProxy(px, registrationName) elif px.GetXMLGroup() == "animation": controller.RegisterAnimationProxy(px) return px # add special tag to detect these functions in _remove_functions CreateObject.__paraview_create_object_tag = True CreateObject.__paraview_create_object_key = key CreateObject.__paraview_create_object_module = module return CreateObject # ----------------------------------------------------------------------------- def _listProperties(create_func): """Internal function that, given a proxy creation function, e.g., paraview.simple.Sphere, returns the list of named properties that can be set during construction.""" key = create_func.__paraview_create_object_key module = create_func.__paraview_create_object_module prototype_func = _create_func(key, module, skipRegisteration=True) # Find the prototype by XML label name xml_definition = module._findProxy(name=key) xml_group = xml_definition['group'] xml_name = xml_definition['key'] prototype = sm.ProxyManager().GetPrototypeProxy(xml_group, xml_name) # Iterate over properties and add them to the list property_iter = prototype.NewPropertyIterator() property_iter.UnRegister(None) property_names = [] while not property_iter.IsAtEnd(): label = property_iter.GetPropertyLabel() if label is None: label = property_iter.GetKey() property_names.append(paraview.make_name_valid(label)) property_iter.Next() return property_names def _get_function_arguments(function): """The a list of named arguments for a function. Used for autocomplete in PythonShell in ParaView GUI and in pvpython""" import inspect if not inspect.isfunction(function) and not inspect.ismethod(function): raise TypeError(f"input argument: {function} is not a function") result = [] if hasattr(function,"__paraview_create_object_tag") and getattr(function,"__paraview_create_object_tag"): result = ListProperties(function) else: for _,parameter in inspect.signature(function).parameters.items(): # skip *args and **kwargs if parameter.kind != inspect.Parameter.VAR_POSITIONAL and parameter.kind != inspect.Parameter.VAR_KEYWORD: result.append(parameter.name) return result # ----------------------------------------------------------------------------- def _create_doc(new, old): "Internal function." import string res = new + '\n' ts = [] strpd = old.split('\n') for s in strpd: ts.append(s.lstrip()) res += ' '.join(ts) res += '\n' return res # ----------------------------------------------------------------------------- def _func_name_valid(name): "Internal function." valid = True for c in name: if c == '(' or c == ')': valid = False break return valid # ----------------------------------------------------------------------------- def _get_proxymodules_to_import(connection): """ used in _add_functions, _get_generated_proxies, and _remove_functions to get modules to import proxies from. """ if connection and connection.ProxiesNS: modules = connection.ProxiesNS return [modules.filters, modules.sources, modules.writers, modules.animation] else: return [] def _add_functions(g): if not servermanager.ActiveConnection: return activeModule = servermanager.ActiveConnection.ProxiesNS # add deprecated proxies first, so we create the new function and documentation. modules = paraview._backwardscompatibilityhelper.get_deprecated_proxies(activeModule) for proxyModule in modules: for deprecatedProxyPair in modules[proxyModule]: oldProxyLabel = deprecatedProxyPair[0] newProxyLabel = deprecatedProxyPair[1] if not newProxyLabel in g and _func_name_valid(newProxyLabel): f = _create_func(deprecatedProxyPair, proxyModule) f.__doc__ = "{} is a deprecated proxy. It will be automatically replaced by {}".format(oldProxyLabel, newProxyLabel) f.__name__ = oldProxyLabel g[oldProxyLabel] = f for m in _get_proxymodules_to_import(servermanager.ActiveConnection): # Skip registering proxies in certain modules (currently only writers) skipRegisteration = m is activeModule.writers for key in dir(m): if not key in g and _func_name_valid(key): # print "add %s function" % key f = _create_func(key, m, skipRegisteration) f.__name__ = key f.__doc__ = _create_doc(m.getDocumentation(key), f.__doc__) g[key] = f # ----------------------------------------------------------------------------- def _get_generated_proxies(): proxies = [] for m in _get_proxymodules_to_import(servermanager.ActiveConnection): for key in dir(m): proxies.append(key) return proxies # ----------------------------------------------------------------------------- def _remove_functions(g): to_remove = [item[0] for item in g.items() \ if hasattr(item[1], '__paraview_create_object_tag')] for key in to_remove: del g[key] # paraview.print_info("remove %s", key) # ----------------------------------------------------------------------------- def _find_writer(filename): "Internal function." extension = None parts = filename.split('.') if len(parts) > 1: extension = parts[-1] else: raise RuntimeError("Filename has no extension, please specify a write") if extension == 'png': return 'vtkPNGWriter' elif extension == 'bmp': return 'vtkBMPWriter' elif extension == 'ppm': return 'vtkPNMWriter' elif extension == 'tif' or extension == 'tiff': return 'vtkTIFFWriter' elif extension == 'jpg' or extension == 'jpeg': return 'vtkJPEGWriter' else: raise RuntimeError("Cannot infer filetype from extension:", extension) # ----------------------------------------------------------------------------- def _switchToActiveConnectionCallback(caller, event): """Callback called when the active session/connection changes in the ServerManager. We update the Python state to reflect the change.""" if servermanager: session = servermanager.vtkSMProxyManager.GetProxyManager().GetActiveSession() connection = servermanager.GetConnectionFromSession(session) SetActiveConnection(connection) # ============================================================================== # Set of Internal classes # ============================================================================== class _active_session_observer: def __init__(self): pxm = servermanager.vtkSMProxyManager.GetProxyManager() self.ObserverTag = pxm.AddObserver(pxm.ActiveSessionChanged, _switchToActiveConnectionCallback) def __del__(self): if servermanager: if servermanager.vtkSMProxyManager: servermanager.vtkSMProxyManager.GetProxyManager().RemoveObserver(self.ObserverTag) # ----------------------------------------------------------------------------- class _active_objects(object): """This class manages the active objects (source and view). The active objects are shared between Python and the user interface. This class is for internal use. Use the :ref:`SetActiveSource`, :ref:`GetActiveSource`, :ref:`SetActiveView`, and :ref:`GetActiveView` methods for setting and getting active objects.""" def __get_selection_model(self, name, session=None): "Internal method." if session and session != servermanager.ActiveConnection.Session: raise RuntimeError("Try to set an active object with invalid active connection.") pxm = servermanager.ProxyManager(session) model = pxm.GetSelectionModel(name) if not model: model = servermanager.vtkSMProxySelectionModel() pxm.RegisterSelectionModel(name, model) return model def set_view(self, view): "Sets the active view." active_view_model = self.__get_selection_model("ActiveView") if view: active_view_model = self.__get_selection_model("ActiveView", view.GetSession()) active_view_model.SetCurrentProxy(view.SMProxy, active_view_model.CLEAR_AND_SELECT) else: active_view_model = self.__get_selection_model("ActiveView") active_view_model.SetCurrentProxy(None, active_view_model.CLEAR_AND_SELECT) def get_view(self): "Returns the active view." return servermanager._getPyProxy( self.__get_selection_model("ActiveView").GetCurrentProxy()) def set_source(self, source): "Sets the active source." active_sources_model = self.__get_selection_model("ActiveSources") if source: # 3 == CLEAR_AND_SELECT active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession()) active_sources_model.SetCurrentProxy(source.SMProxy, active_sources_model.CLEAR_AND_SELECT) else: active_sources_model = self.__get_selection_model("ActiveSources") active_sources_model.SetCurrentProxy(None, active_sources_model.CLEAR_AND_SELECT) def __convert_proxy(self, px): "Internal method." if not px: return None elif px.IsA("vtkSMOutputPort"): return servermanager.OutputPort( servermanager._getPyProxy(px.GetSourceProxy()), px.GetPortIndex()) else: return servermanager._getPyProxy(px) def get_source(self): "Returns the active source." return self.__convert_proxy( self.__get_selection_model("ActiveSources").GetCurrentProxy()) def get_selected_sources(self): "Returns the set of sources selected in the pipeline browser." model = self.__get_selection_model("ActiveSources") proxies = [] for i in xrange(model.GetNumberOfSelectedProxies()): proxies.append(self.__convert_proxy(model.GetSelectedProxy(i))) return proxies view = property(get_view, set_view) source = property(get_source, set_source) # ----------------------------------------------------------------------------- class _funcs_internals: "Internal class." first_render = True # ============================================================================== # Start the session and initialize the ServerManager # ============================================================================== if not paraview.options.satelite: active_session_observer = _active_session_observer() if not servermanager.ActiveConnection: Connect() else: _add_functions(globals()) active_objects = _active_objects()