1 r"""simple is a module for using paraview server manager in Python. It
2 provides a simple convenience layer to functionality provided by the
3 C++ classes wrapped to Python as well as the servermanager module.
6 from paraview.simple import *
8 # Create a new sphere proxy on the active connection and register it
9 # in the sources group.
10 sphere = Sphere(ThetaResolution=16, PhiResolution=32)
12 # Apply a shrink filter
13 shrink = Shrink(sphere)
15 # Turn the visiblity of the shrink object on.
24 servermanager = paravisSM
27 servermanager.ProxyManager().UnRegisterProxies()
28 active_objects.view = None
29 active_objects.source = None
32 servermanager.Disconnect()
34 def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
35 """Creates a connection to a server. Example usage:
36 > Connect("amber") # Connect to a single server at default port
37 > Connect("amber", 12345) # Connect to a single server at port 12345
38 > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair"""
40 cid = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
41 servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", servermanager.misc.TimeKeeper())
44 def ReverseConnect(port=11111):
45 """Create a reverse connection to a server. Listens on port and waits for
46 an incoming connection from the server."""
48 cid = servermanager.ReverseConnect(port)
49 servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", servermanager.misc.TimeKeeper())
52 def _create_view(view_xml_name):
53 "Creates and returns a 3D render view."
54 view = servermanager._create_view(view_xml_name)
55 servermanager.ProxyManager().RegisterProxy("views", \
56 "my_view%d" % _funcs_internals.view_counter, view)
57 active_objects.view = view
58 _funcs_internals.view_counter += 1
60 tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
67 def CreateRenderView():
68 return _create_view("RenderView")
70 def CreateXYPlotView():
71 return _create_view("XYPlotView")
73 def CreateBarChartView():
74 return _create_view("BarChart")
77 "Returns the active view if there is one. Else creates and returns a new view."
78 view = active_objects.view
79 if not view: view = CreateRenderView()
83 "Returns all render views as a list."
84 return servermanager.GetRenderViews()
86 def GetRepresentation(proxy=None, view=None):
87 """"Given a pipeline object and view, returns the corresponding representation object.
88 If pipeline object and view are not specified, active objects are used."""
90 view = active_objects.view
92 proxy = active_objects.source
93 rep = servermanager.GetRepresentation(proxy, view)
95 rep = servermanager.CreateRepresentation(proxy, view)
96 servermanager.ProxyManager().RegisterProxy("representations", \
97 "my_representation%d" % _funcs_internals.rep_counter, rep)
98 _funcs_internals.rep_counter += 1
101 def GetDisplayProperties(proxy=None, view=None):
102 """"Given a pipeline object and view, returns the corresponding representation object.
103 If pipeline object and/or view are not specified, active objects are used."""
104 return GetRepresentation(proxy, view)
106 def Show(proxy=None, view=None, **params):
107 """Turns the visibility of a given pipeline object on in the given view.
108 If pipeline object and/or view are not specified, active objects are used."""
110 proxy = GetActiveSource()
112 raise RuntimeError, "Show() needs a proxy argument or that an active source is set."
113 if not view and not active_objects.view:
115 rep = GetDisplayProperties(proxy, view)
117 raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel()
118 for param in params.keys():
119 setattr(rep, param, params[param])
123 def Hide(proxy=None, view=None):
124 """Turns the visibility of a given pipeline object off in the given view.
125 If pipeline object and/or view are not specified, active objects are used."""
126 rep = GetDisplayProperties(proxy, view)
129 def Render(view=None):
130 """Renders the given view (default value is active view)"""
132 view = active_objects.view
134 if _funcs_internals.first_render:
135 # Not all views have a ResetCamera method
139 except AttributeError: pass
140 _funcs_internals.first_render = False
143 def ResetCamera(view=None):
144 """Resets the settings of the camera to preserver orientation but include
145 the whole scene. If an argument is not provided, the active view is
148 view = active_objects.view
152 def SetProperties(proxy=None, **params):
153 """Sets one or more properties of the given pipeline object. If an argument
154 is not provided, the active source is used. Pass a list of property_name=value
155 pairs to this function to set property values. For example:
156 SetProperties(Center=[1, 2, 3], Radius=3.5)
159 proxy = active_objects.source
160 for param in params.keys():
161 if not hasattr(proxy, param):
162 raise AttributeError("object has no property %s" % param)
163 setattr(proxy, param, params[param])
165 def SetDisplayProperties(proxy=None, view=None, **params):
166 """Sets one or more display properties of the given pipeline object. If an argument
167 is not provided, the active source is used. Pass a list of property_name=value
168 pairs to this function to set property values. For example:
169 SetProperties(Color=[1, 0, 0], LineWidth=2)
171 rep = GetDisplayProperties(proxy, view)
172 SetProperties(rep, **params)
174 def SetViewProperties(view=None, **params):
175 """Sets one or more properties of the given view. If an argument
176 is not provided, the active view is used. Pass a list of property_name=value
177 pairs to this function to set property values. For example:
178 SetProperties(Background=[1, 0, 0], UseImmediateMode=0)
181 view = active_objects.view
182 SetProperties(view, **params)
184 def RenameSource(newName, proxy=None):
185 """Renames the given source. If the given proxy is not registered
186 in the sources group this method will have no effect. If no source is
187 provided, the active source is used."""
189 proxy = active_objects.source
190 pxm = servermanager.ProxyManager()
191 oldName = pxm.GetProxyName("sources", proxy)
193 pxm.RegisterProxy("sources", newName, proxy)
194 pxm.UnRegisterProxy("sources", oldName, proxy)
196 def FindSource(name):
197 return servermanager.ProxyManager().GetProxy("sources", name)
200 """Given the name of a source, return its Python object."""
201 return servermanager.ProxyManager().GetProxiesInGroup("sources")
203 def GetRepresentations():
204 """Returns all representations (display properties)."""
205 return servermanager.ProxyManager().GetProxiesInGroup("representations")
207 def UpdatePipeline(time=None, proxy=None):
208 """Updates (executes) the given pipeline object for the given time as
209 necessary (i.e. if it did not already execute). If no source is provided,
210 the active source is used instead."""
212 proxy = active_objects.source
214 proxy.UpdatePipeline(time)
216 proxy.UpdatePipeline()
218 def Delete(proxy=None):
219 """Deletes the given pipeline object or the active source if no argument
222 proxy = active_objects.source
223 # Unregister any helper proxies stored by a vtkSMProxyListDomain
225 listdomain = prop.GetDomain('proxy_list')
227 if listdomain.GetClassName() != 'vtkSMProxyListDomain':
229 group = "pq_helper_proxies." + proxy.GetSelfIDAsString()
230 for i in xrange(listdomain.GetNumberOfProxies()):
231 pm = servermanager.ProxyManager()
232 iproxy = listdomain.GetProxy(i)
233 name = pm.GetProxyName(group, iproxy)
235 pm.UnRegisterProxy(group, name, iproxy)
237 # Remove source/view from time keeper
238 tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
239 if isinstance(proxy, servermanager.SourceProxy):
241 idx = tk.TimeSources.index(proxy)
242 del tk.TimeSources[idx]
247 idx = tk.Views.index(proxy)
251 servermanager.UnRegister(proxy)
253 # If this is a representation, remove it from all views.
254 if proxy.SMProxy.IsA("vtkSMRepresentationProxy"):
255 for view in GetRenderViews():
256 view.Representations.remove(proxy)
257 # If this is a source, remove the representation iff it has no consumers
258 # Also change the active source if necessary
259 elif proxy.SMProxy.IsA("vtkSMSourceProxy"):
260 sources = servermanager.ProxyManager().GetProxiesInGroup("sources")
261 for i in range(proxy.GetNumberOfConsumers()):
262 if proxy.GetConsumerProxy(i) in sources:
263 raise RuntimeError("Source has consumers. It cannot be deleted " +
264 "until all consumers are deleted.")
266 if proxy.IsSame(GetActiveSource()):
267 if hasattr(proxy, "Input") and proxy.Input:
268 if isinstance(proxy.Input, servermanager.Proxy):
269 SetActiveSource(proxy.Input)
271 SetActiveSource(proxy.Input[0])
272 else: SetActiveSource(None)
273 for rep in GetRepresentations().values():
275 if rep.Input.IsSame(proxy):
277 # Change the active view if necessary
278 elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"):
280 if proxy.IsSame(GetActiveView()):
281 if len(GetRenderViews()) > 0:
282 SetActiveView(GetRenderViews()[0])
286 def CreateLookupTable(**params):
287 """Create and return a lookup table. Optionally, parameters can be given
288 to assign to the lookup table.
290 lt = servermanager.rendering.PVLookupTable()
291 servermanager.Register(lt)
292 SetProperties(lt, **params)
295 def CreatePiecewiseFunction(**params):
296 """Create and return a piecewise function. Optionally, parameters can be
297 given to assign to the piecewise function.
299 pfunc = servermanager.piecewise_functions.PiecewiseFunction()
300 servermanager.Register(pfunc)
301 SetProperties(pfunc, **params)
304 def CreateScalarBar(**params):
305 """Create and return a scalar bar widget. The returned widget may
306 be added to a render view by appending it to the view's representations
307 The widget must have a valid lookup table before it is added to a view.
308 It is possible to pass the lookup table (and other properties) as arguments
311 lt = MakeBlueToRedLt(3.5, 7.5)
312 bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
313 GetRenderView().Representations.append(bar)
315 By default the returned widget is selectable and resizable.
317 sb = servermanager.rendering.ScalarBarWidgetRepresentation()
318 servermanager.Register(sb)
323 SetProperties(sb, **params)
326 # TODO: Change this to take the array name and number of components. Register
327 # the lt under the name ncomp.array_name
328 def MakeBlueToRedLT(min, max):
329 # Define RGB points. These are tuples of 4 values. First one is
330 # the scalar values, the other 3 the RGB values.
331 rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
332 return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
334 def _find_writer(filename):
337 parts = filename.split('.')
339 extension = parts[-1]
341 raise RuntimeError, "Filename has no extension, please specify a write"
343 if extension == 'png':
344 return 'vtkPNGWriter'
345 elif extension == 'bmp':
346 return 'vtkBMPWriter'
347 elif extension == 'ppm':
348 return 'vtkPNMWriter'
349 elif extension == 'tif' or extension == 'tiff':
350 return 'vtkTIFFWriter'
351 elif extension == 'jpg' or extension == 'jpeg':
352 return 'vtkJPEGWriter'
354 raise RuntimeError, "Cannot infer filetype from extension:", extension
356 def AddCameraLink(viewProxy, viewProxyOther, linkName):
357 """Create a camera link between two view proxies. A name must be given
358 so that the link can be referred to by name. If a link with the given
359 name already exists it will be removed first."""
360 if not viewProxyOther: viewProxyOther = GetActiveView()
361 link = servermanager.vtkSMCameraLink()
362 link.AddLinkedProxy(viewProxy.SMProxy, 1)
363 link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
364 link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
365 link.AddLinkedProxy(viewProxy.SMProxy, 2)
366 RemoveCameraLink(linkName)
367 servermanager.ProxyManager().RegisterLink(linkName, link)
369 def RemoveCameraLink(linkName):
370 """Remove a camera link with the given name."""
371 servermanager.ProxyManager().UnRegisterLink(linkName)
373 def WriteImage(filename, view=None, **params):
374 """Saves the given view (or the active one if none is given) as an
375 image. Optionally, you can specify the writer and the magnification
376 using the Writer and Magnification named arguments. For example:
377 WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)
378 If no writer is provided, the type is determined from the file extension.
379 Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
380 The writer is a VTK class that is capable of writing images.
381 Magnification is used to determine the size of the written image. The size
382 is obtained by multiplying the size of the view with the magnification.
383 Rendering may be done using tiling to obtain the correct size without
384 resizing the view."""
386 view = active_objects.view
388 if params.has_key('Writer'):
389 writer = params['Writer']
391 if params.has_key('Magnification'):
392 mag = int(params['Magnification'])
394 writer = _find_writer(filename)
395 view.WriteImage(filename, writer, mag)
397 def AnimateReader(reader=None, view=None, filename=None):
398 """This is a utility function that, given a reader and a view
399 animates over all time steps of the reader. If the optional
400 filename is provided, a movie is created (type depends on the
401 extension of the filename."""
403 reader = active_objects.source
405 view = active_objects.view
407 return servermanager.AnimateReader(reader, view, filename)
410 def _create_func(key, module):
413 def CreateObject(*input, **params):
414 """This function creates a new proxy. For pipeline objects that accept inputs,
415 all non-keyword arguments are assumed to be inputs. All keyword arguments are
416 assumed to be property,value pairs and are passed to the new proxy."""
418 # Instantiate the actual object from the given module.
419 px = module.__dict__[key]()
421 # Make sure non-keyword arguments are valid
423 if inp != None and not isinstance(inp, servermanager.Proxy):
424 if px.GetProperty("Input") != None:
425 raise RuntimeError, "Expecting a proxy as input."
427 raise RuntimeError, "This function does not accept non-keyword arguments."
430 if px.GetProperty("Input") != None:
434 # If no input is specified, try the active pipeline object
435 if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
436 px.Input = active_objects.get_selected_sources()
437 elif active_objects.source:
438 px.Input = active_objects.source
441 raise RuntimeError, "This function does not expect an input."
443 registrationName = None
444 for nameParam in ['registrationName', 'guiName']:
445 if nameParam in params:
446 registrationName = params[nameParam]
447 del params[nameParam]
449 # Pass all the named arguments as property,value pairs
450 for param in params.keys():
451 setattr(px, param, params[param])
454 # Register the proxy with the proxy manager.
456 group, name = servermanager.Register(px, registrationName=registrationName)
458 group, name = servermanager.Register(px)
461 # Register pipeline objects with the time keeper. This is used to extract time values
462 # from sources. NOTE: This should really be in the servermanager controller layer.
463 if group == "sources":
464 tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
465 sources = tk.TimeSources
466 if not px in sources:
469 active_objects.source = px
470 except servermanager.MissingRegistrationInformation:
477 def _create_doc(new, old):
481 for doc in (new, old):
483 strpd = doc.split('\n')
485 ts.append(s.lstrip())
486 res += string.join(ts)
490 def _func_name_valid(name):
494 if c == '(' or c ==')':
499 def _add_functions(g):
500 for m in [servermanager.filters, servermanager.sources, servermanager.writers]:
502 for key in dt.keys():
504 if not isinstance(cl, str):
505 if not key in g and _func_name_valid(key):
506 g[key] = _create_func(key, m)
507 exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key
510 "Returns the active view."
511 return active_objects.view
513 def SetActiveView(view):
514 "Sets the active view."
515 active_objects.view = view
517 def GetActiveSource():
518 "Returns the active source."
519 return active_objects.source
521 def SetActiveSource(source):
522 "Sets the active source."
523 active_objects.source = source
525 def GetActiveCamera():
526 """Returns the active camera for the active view. The returned object
527 is an instance of vtkCamera."""
528 return GetActiveView().GetActiveCamera()
530 def LoadXML(xmlstring, ns=None):
531 """Given a server manager XML as a string, parse and process it.
532 If you loaded the simple module with from paraview.simple import *,
533 make sure to pass globals() as the second arguments:
534 LoadXML(xmlstring, globals())
535 Otherwise, the new functions will not appear in the global namespace."""
538 servermanager.LoadXML(xmlstring)
541 def LoadPlugin(filename, remote=True, ns=None):
542 """Loads a ParaView plugin and updates this module with new constructors
543 if any. The remote argument (default to True) is to specify whether
544 the plugin will be loaded on client (remote=False) or on server (remote=True).
545 If you loaded the simple module with from paraview.simple import *,
546 make sure to pass globals() as an argument:
547 LoadPlugin("myplugin", False, globals()), to load on client;
548 LoadPlugin("myplugin", True, globals()), to load on server;
549 LoadPlugin("myplugin", ns=globals()), to load on server.
550 Otherwise, the new functions will not appear in the global namespace."""
554 servermanager.LoadPlugin(filename, remote)
557 class ActiveObjects(object):
558 """This class manages the active objects (source and view). The active
559 objects are shared between Python and the user interface. This class
560 is for internal use. Use the Set/Get methods for setting and getting
562 def __get_selection_model(self, name):
564 pxm = servermanager.ProxyManager()
565 model = pxm.GetSelectionModel(name)
567 model = servermanager.vtkSMProxySelectionModel()
568 pxm.RegisterSelectionModel(name, model)
571 def set_view(self, view):
572 "Sets the active view."
573 active_view_model = self.__get_selection_model("ActiveView")
575 active_view_model.SetCurrentProxy(view.SMProxy, 0)
577 active_view_model.SetCurrentProxy(None, 0)
580 "Returns the active view."
581 return servermanager._getPyProxy(
582 self.__get_selection_model("ActiveView").GetCurrentProxy())
584 def set_source(self, source):
585 "Sets the active source."
586 active_sources_model = self.__get_selection_model("ActiveSources")
588 # 3 == CLEAR_AND_SELECT
589 active_sources_model.SetCurrentProxy(source.SMProxy, 3)
591 active_sources_model.SetCurrentProxy(None, 3)
593 def __convert_proxy(self, px):
597 if px.IsA("vtkSMSourceProxy"):
598 return servermanager._getPyProxy(px)
600 return servermanager.OutputPort(
601 servermanager._getPyProxy(px.GetSourceProxy()),
604 def get_source(self):
605 "Returns the active source."
606 return self.__convert_proxy(
607 self.__get_selection_model("ActiveSources").GetCurrentProxy())
609 def get_selected_sources(self):
610 "Returns the set of sources selected in the pipeline browser."
611 model = self.__get_selection_model("ActiveSources")
613 for i in xrange(model.GetNumberOfSelectedProxies()):
614 proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
617 view = property(get_view, set_view)
618 source = property(get_source, set_source)
620 class _funcs_internals:
627 """Simple demo that create the following pipeline
632 # Create a sphere of radius = 2, theta res. = 32
633 # This object becomes the active source.
634 ss = Sphere(Radius=2, ThetaResolution=32)
635 # Apply the shrink filter. The Input property is optional. If Input
636 # is not specified, the filter is applied to the active source.
637 shr = Shrink(Input=ss)
638 # Create a cone source.
640 # Append cone and shrink
641 app = AppendDatasets()
642 app.Input = [shr, cs]
643 # Show the output of the append filter. The argument is optional
644 # as the app filter is now the active object.
646 # Render the default view.
649 def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"):
650 """This demo shows the use of readers, data information and display
653 # Create the exodus reader and specify a file name
654 reader = ExodusIIReader(FileName=fname)
655 # Get the list of point arrays.
656 avail = reader.PointVariables.Available
659 reader.PointVariables = avail
661 # Turn on the visibility of the reader
663 # Set representation to wireframe
664 SetDisplayProperties(Representation = "Wireframe")
665 # Black background is not pretty
666 SetViewProperties(Background = [0.4, 0.4, 0.6])
668 # Change the elevation of the camera. See VTK documentation of vtkCamera
669 # for camera parameters.
670 # NOTE: THIS WILL BE SIMPLER
671 GetActiveCamera().Elevation(45)
673 # Now that the reader executed, let's get some information about it's
675 pdi = reader[0].PointData
676 # This prints a list of all read point data arrays as well as their
678 print 'Number of point arrays:', len(pdi)
679 for i in range(len(pdi)):
681 print "----------------"
682 print "Array:", i, " ", ai.Name, ":"
683 numComps = ai.GetNumberOfComponents()
684 print "Number of components:", numComps
685 for j in range(numComps):
686 print "Range:", ai.GetRange(j)
687 # White is boring. Let's color the geometry using a variable.
688 # First create a lookup table. This object controls how scalar
689 # values are mapped to colors. See VTK documentation for
691 # Map min (0.00678) to blue, max (0.0288) to red
692 SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
693 # Color by point array called Pres
694 SetDisplayProperties(ColorAttributeType = "POINT_DATA")
695 SetDisplayProperties(ColorArrayName = "Pres")
699 print paravisSM.myParavis.GetTrace()
701 def SaveTrace(fileName):
702 paravisSM.myParavis.SaveTrace(fileName)
705 _add_functions(globals())
706 active_objects = ActiveObjects()
707 ## Initialisation for SALOME GUI
708 active_objects.view = servermanager.GetRenderView()
710 if not servermanager.ActiveConnection:
713 def ImportFile(theFileName):
714 paravisSM.ImportFile(theFileName)