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
26 def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
27 """Creates a connection to a server. Example usage:
28 > Connect("amber") # Connect to a single server at default port
29 > Connect("amber", 12345) # Connect to a single server at port 12345
30 > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair
31 This also create a default render view."""
32 servermanager.ProxyManager().UnRegisterProxies()
33 active_objects.view = None
34 active_objects.source = None
37 servermanager.Disconnect()
38 cid = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
39 servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", servermanager.misc.TimeKeeper())
43 def CreateRenderView():
44 "Creates and returns a 3D render view."
45 view = servermanager.CreateRenderView()
46 servermanager.ProxyManager().RegisterProxy("views", \
47 "my_view%d" % _funcs_internals.view_counter, view)
48 active_objects.view = view
49 _funcs_internals.view_counter += 1
51 tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
59 "Returns the active view if there is one. Else creates and returns a new view."
60 view = active_objects.view
61 if not view: view = CreateRenderView()
65 "Returns all render views as a list."
66 return servermanager.GetRenderViews()
68 def GetRepresentation(proxy=None, view=None):
69 """"Given a pipeline object and view, returns the corresponding representation object.
70 If pipeline object and view are not specified, active objects are used."""
72 view = active_objects.view
74 proxy = active_objects.source
75 rep = servermanager.GetRepresentation(proxy, view)
77 rep = servermanager.CreateRepresentation(proxy, view)
78 servermanager.ProxyManager().RegisterProxy("representations", \
79 "my_representation%d" % _funcs_internals.rep_counter, rep)
80 _funcs_internals.rep_counter += 1
83 def GetDisplayProperties(proxy=None, view=None):
84 """"Given a pipeline object and view, returns the corresponding representation object.
85 If pipeline object and/or view are not specified, active objects are used."""
86 return GetRepresentation(proxy, view)
88 def Show(proxy=None, view=None, **params):
89 """Turns the visibility of a given pipeline object on in the given view.
90 If pipeline object and/or view are not specified, active objects are used."""
92 proxy = GetActiveSource()
94 raise RuntimeError, "Show() needs a proxy argument or that an active source is set."
95 if not view and len(GetRenderViews()) == 0:
97 rep = GetDisplayProperties(proxy, view)
99 raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel()
100 for param in params.keys():
101 setattr(rep, param, params[param])
105 def Hide(proxy=None, view=None):
106 """Turns the visibility of a given pipeline object off in the given view.
107 If pipeline object and/or view are not specified, active objects are used."""
108 rep = GetDisplayProperties(proxy, view)
111 def Render(view=None):
112 """Renders the given view (default value is active view)"""
114 view = active_objects.view
116 if _funcs_internals.first_render:
119 _funcs_internals.first_render = False
122 def ResetCamera(view=None):
123 """Resets the settings of the camera to preserver orientation but include
124 the whole scene. If an argument is not provided, the active view is
127 view = active_objects.view
131 def SetProperties(proxy=None, **params):
132 """Sets one or more properties of the given pipeline object. If an argument
133 is not provided, the active source is used. Pass a list of property_name=value
134 pairs to this function to set property values. For example:
135 SetProperties(Center=[1, 2, 3], Radius=3.5)
138 proxy = active_objects.source
139 for param in params.keys():
140 if not hasattr(proxy, param):
141 raise AttributeError("object has no property %s" % param)
142 setattr(proxy, param, params[param])
144 def SetDisplayProperties(proxy=None, view=None, **params):
145 """Sets one or more display properties of the given pipeline object. If an argument
146 is not provided, the active source is used. Pass a list of property_name=value
147 pairs to this function to set property values. For example:
148 SetProperties(Color=[1, 0, 0], LineWidth=2)
150 rep = GetDisplayProperties(proxy, view)
151 SetProperties(rep, **params)
153 def SetViewProperties(view=None, **params):
154 """Sets one or more properties of the given view. If an argument
155 is not provided, the active view is used. Pass a list of property_name=value
156 pairs to this function to set property values. For example:
157 SetProperties(Background=[1, 0, 0], UseImmediateMode=0)
160 view = active_objects.view
161 SetProperties(view, **params)
163 def RenameSource(newName, proxy=None):
164 """Renames the given source. If the given proxy is not registered
165 in the sources group this method will have no effect. If no source is
166 provided, the active source is used."""
168 proxy = active_objects.source
169 pxm = servermanager.ProxyManager()
170 oldName = pxm.GetProxyName("sources", proxy)
172 pxm.RegisterProxy("sources", newName, proxy)
173 pxm.UnRegisterProxy("sources", oldName, proxy)
175 def FindSource(name):
176 return servermanager.ProxyManager().GetProxy("sources", name)
179 """Given the name of a source, return its Python object."""
180 return servermanager.ProxyManager().GetProxiesInGroup("sources")
182 def GetRepresentations():
183 """Returns all representations (display properties)."""
184 return servermanager.ProxyManager().GetProxiesInGroup("representations")
186 def UpdatePipeline(time=None, proxy=None):
187 """Updates (executes) the given pipeline object for the given time as
188 necessary (i.e. if it did not already execute). If no source is provided,
189 the active source is used instead."""
191 proxy = active_objects.source
193 proxy.UpdatePipeline(time)
195 proxy.UpdatePipeline()
197 def Delete(proxy=None):
198 """Deletes the given pipeline object or the active source if no argument
201 proxy = active_objects.source
202 # Unregister any helper proxies stored by a vtkSMProxyListDomain
204 listdomain = prop.GetDomain('proxy_list')
206 if listdomain.GetClassName() != 'vtkSMProxyListDomain':
208 group = "pq_helper_proxies." + proxy.GetSelfIDAsString()
209 for i in xrange(listdomain.GetNumberOfProxies()):
210 pm = servermanager.ProxyManager()
211 iproxy = listdomain.GetProxy(i)
212 name = pm.GetProxyName(group, iproxy)
214 pm.UnRegisterProxy(group, name, iproxy)
216 # Remove source/view from time keeper
217 tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
218 if isinstance(proxy, servermanager.SourceProxy):
220 idx = tk.TimeSources.index(proxy)
221 del tk.TimeSources[idx]
226 idx = tk.Views.index(proxy)
230 servermanager.UnRegister(proxy)
232 # If this is a representation, remove it from all views.
233 if proxy.SMProxy.IsA("vtkSMRepresentationProxy"):
234 for view in GetRenderViews():
235 view.Representations.remove(proxy)
236 # If this is a source, remove the representation iff it has no consumers
237 # Also change the active source if necessary
238 elif proxy.SMProxy.IsA("vtkSMSourceProxy"):
239 sources = servermanager.ProxyManager().GetProxiesInGroup("sources")
240 for i in range(proxy.GetNumberOfConsumers()):
241 if proxy.GetConsumerProxy(i) in sources:
242 raise RuntimeError("Source has consumers. It cannot be deleted " +
243 "until all consumers are deleted.")
245 if proxy.IsSame(GetActiveSource()):
246 if hasattr(proxy, "Input") and proxy.Input:
247 if isinstance(proxy.Input, servermanager.Proxy):
248 SetActiveSource(proxy.Input)
250 SetActiveSource(proxy.Input[0])
251 else: SetActiveSource(None)
252 for rep in GetRepresentations().values():
254 if rep.Input.IsSame(proxy):
256 # Change the active view if necessary
257 elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"):
259 if proxy.IsSame(GetActiveView()):
260 if len(GetRenderViews()) > 0:
261 SetActiveView(GetRenderViews()[0])
265 def CreateLookupTable(**params):
266 """Create and return a lookup table. Optionally, parameters can be given
267 to assign to the lookup table.
269 lt = servermanager.rendering.PVLookupTable()
270 servermanager.Register(lt)
271 SetProperties(lt, **params)
274 def CreateScalarBar(**params):
275 """Create and return a scalar bar widget. The returned widget may
276 be added to a render view by appending it to the view's representations
277 The widget must have a valid lookup table before it is added to a view.
278 It is possible to pass the lookup table (and other properties) as arguments
281 lt = MakeBlueToRedLt(3.5, 7.5)
282 bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
283 GetRenderView().Representations.append(bar)
285 By default the returned widget is selectable and resizable.
287 sb = servermanager.rendering.ScalarBarWidgetRepresentation()
288 servermanager.Register(sb)
293 SetProperties(sb, **params)
296 # TODO: Change this to take the array name and number of components. Register
297 # the lt under the name ncomp.array_name
298 def MakeBlueToRedLT(min, max):
299 # Define RGB points. These are tuples of 4 values. First one is
300 # the scalar values, the other 3 the RGB values.
301 rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
302 return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
304 def _find_writer(filename):
307 parts = filename.split('.')
309 extension = parts[-1]
311 raise RuntimeError, "Filename has no extension, please specify a write"
313 if extension == 'png':
314 return 'vtkPNGWriter'
315 elif extension == 'bmp':
316 return 'vtkBMPWriter'
317 elif extension == 'ppm':
319 elif extension == 'tif' or extension == 'tiff':
320 return 'vtkTIFFWriter'
321 elif extension == 'jpg' or extension == 'jpeg':
322 return 'vtkJPEGWriter'
324 raise RuntimeError, "Cannot infer filetype from extension:", extension
326 def AddCameraLink(viewProxy, viewProxyOther, linkName):
327 """Create a camera link between two view proxies. A name must be given
328 so that the link can be referred to by name. If a link with the given
329 name already exists it will be removed first."""
330 if not viewProxyOther: viewProxyOther = GetActiveView()
331 link = servermanager.vtkSMCameraLink()
332 link.AddLinkedProxy(viewProxy.SMProxy, 1)
333 link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
334 link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
335 link.AddLinkedProxy(viewProxy.SMProxy, 2)
336 RemoveCameraLink(linkName)
337 servermanager.ProxyManager().RegisterLink(linkName, link)
339 def RemoveCameraLink(linkName):
340 """Remove a camera link with the given name."""
341 servermanager.ProxyManager().UnRegisterLink(linkName)
343 def WriteImage(filename, view=None, **params):
344 """Saves the given view (or the active one if none is given) as an
345 image. Optionally, you can specify the writer and the magnification
346 using the Writer and Magnification named arguments. For example:
347 WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)
348 If no writer is provided, the type is determined from the file extension.
349 Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
350 The writer is a VTK class that is capable of writing images.
351 Magnification is used to determine the size of the written image. The size
352 is obtained by multiplying the size of the view with the magnification.
353 Rendering may be done using tiling to obtain the correct size without
354 resizing the view."""
356 view = active_objects.view
358 if params.has_key('Writer'):
359 writer = params['Writer']
361 if params.has_key('Magnification'):
362 mag = int(params['Magnification'])
364 writer = _find_writer(filename)
365 view.WriteImage(filename, writer, mag)
367 def AnimateReader(reader=None, view=None, filename=None):
368 """This is a utility function that, given a reader and a view
369 animates over all time steps of the reader. If the optional
370 filename is provided, a movie is created (type depends on the
371 extension of the filename."""
373 reader = active_objects.source
375 view = active_objects.view
377 return servermanager.AnimateReader(reader, view, filename)
380 def _create_func(key, module):
383 def CreateObject(*input, **params):
384 """This function creates a new proxy. For pipeline objects that accept inputs,
385 all non-keyword arguments are assumed to be inputs. All keyword arguments are
386 assumed to be property,value pairs and are passed to the new proxy."""
388 # Instantiate the actual object from the given module.
389 px = module.__dict__[key]()
391 # Make sure non-keyword arguments are valid
393 if inp != None and not isinstance(inp, servermanager.Proxy):
394 if px.GetProperty("Input") != None:
395 raise RuntimeError, "Expecting a proxy as input."
397 raise RuntimeError, "This function does not accept non-keyword arguments."
400 if px.GetProperty("Input") != None:
404 # If no input is specified, try the active pipeline object
405 if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
406 px.Input = active_objects.get_selected_sources()
407 elif active_objects.source:
408 px.Input = active_objects.source
411 raise RuntimeError, "This function does not expect an input."
413 registrationName = None
414 for nameParam in ['registrationName', 'guiName']:
415 if nameParam in params:
416 registrationName = params[nameParam]
417 del params[nameParam]
419 # Pass all the named arguments as property,value pairs
420 for param in params.keys():
421 setattr(px, param, params[param])
424 # Register the proxy with the proxy manager.
426 group, name = servermanager.Register(px, registrationName=registrationName)
428 group, name = servermanager.Register(px)
431 # Register pipeline objects with the time keeper. This is used to extract time values
432 # from sources. NOTE: This should really be in the servermanager controller layer.
433 if group == "sources":
434 tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
435 sources = tk.TimeSources
436 if not px in sources:
439 active_objects.source = px
440 except servermanager.MissingRegistrationInformation:
447 def _create_doc(new, old):
451 for doc in (new, old):
453 strpd = doc.split('\n')
455 ts.append(s.lstrip())
456 res += string.join(ts)
460 def _func_name_valid(name):
464 if c == '(' or c ==')':
469 def _add_functions(g):
470 for m in [servermanager.filters, servermanager.sources, servermanager.writers]:
472 for key in dt.keys():
474 if not isinstance(cl, str):
475 if not key in g and _func_name_valid(key):
476 g[key] = _create_func(key, m)
477 exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key
480 "Returns the active view."
481 return active_objects.view
483 def SetActiveView(view):
484 "Sets the active view."
485 active_objects.view = view
487 def GetActiveSource():
488 "Returns the active source."
489 return active_objects.source
491 def SetActiveSource(source):
492 "Sets the active source."
493 active_objects.source = source
495 def GetActiveCamera():
496 """Returns the active camera for the active view. The returned object
497 is an instance of vtkCamera."""
498 return GetActiveView().GetActiveCamera()
500 def LoadXML(xmlstring, ns=None):
501 """Given a server manager XML as a string, parse and process it.
502 If you loaded the simple module with from paraview.simple import *,
503 make sure to pass globals() as the second arguments:
504 LoadXML(xmlstring, globals())
505 Otherwise, the new functions will not appear in the global namespace."""
508 servermanager.LoadXML(xmlstring)
511 def LoadPlugin(filename, remote=True, ns=None):
512 """Loads a ParaView plugin and updates this module with new constructors
513 if any. The remote argument (default to True) is to specify whether
514 the plugin will be loaded on client (remote=False) or on server (remote=True).
515 If you loaded the simple module with from paraview.simple import *,
516 make sure to pass globals() as an argument:
517 LoadPlugin("myplugin", False, globals()), to load on client;
518 LoadPlugin("myplugin", True, globals()), to load on server;
519 LoadPlugin("myplugin", ns=globals()), to load on server.
520 Otherwise, the new functions will not appear in the global namespace."""
524 servermanager.LoadPlugin(filename, remote)
527 class ActiveObjects(object):
528 """This class manages the active objects (source and view). The active
529 objects are shared between Python and the user interface. This class
530 is for internal use. Use the Set/Get methods for setting and getting
532 def __get_selection_model(self, name):
534 pxm = servermanager.ProxyManager()
535 model = pxm.GetSelectionModel(name)
537 model = servermanager.vtkSMProxySelectionModel()
538 pxm.RegisterSelectionModel(name, model)
541 def set_view(self, view):
542 "Sets the active view."
543 active_view_model = self.__get_selection_model("ActiveView")
545 active_view_model.SetCurrentProxy(view.SMProxy, 0)
547 active_view_model.SetCurrentProxy(None, 0)
550 "Returns the active view."
551 return servermanager._getPyProxy(
552 self.__get_selection_model("ActiveView").GetCurrentProxy())
554 def set_source(self, source):
555 "Sets the active source."
556 active_sources_model = self.__get_selection_model("ActiveSources")
558 # 3 == CLEAR_AND_SELECT
559 active_sources_model.SetCurrentProxy(source.SMProxy, 3)
561 active_sources_model.SetCurrentProxy(None, 3)
563 def __convert_proxy(self, px):
567 if px.IsA("vtkSMSourceProxy"):
568 return servermanager._getPyProxy(px)
570 return servermanager.OutputPort(
571 servermanager._getPyProxy(px.GetSourceProxy()),
574 def get_source(self):
575 "Returns the active source."
576 return self.__convert_proxy(
577 self.__get_selection_model("ActiveSources").GetCurrentProxy())
579 def get_selected_sources(self):
580 "Returns the set of sources selected in the pipeline browser."
581 model = self.__get_selection_model("ActiveSources")
583 for i in xrange(model.GetNumberOfSelectedProxies()):
584 proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
587 view = property(get_view, set_view)
588 source = property(get_source, set_source)
590 class _funcs_internals:
597 """Simple demo that create the following pipeline
602 # Create a sphere of radius = 2, theta res. = 32
603 # This object becomes the active source.
604 ss = Sphere(Radius=2, ThetaResolution=32)
605 # Apply the shrink filter. The Input property is optional. If Input
606 # is not specified, the filter is applied to the active source.
607 shr = Shrink(Input=ss)
608 # Create a cone source.
610 # Append cone and shrink
611 app = AppendDatasets()
612 app.Input = [shr, cs]
613 # Show the output of the append filter. The argument is optional
614 # as the app filter is now the active object.
616 # Render the default view.
619 def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"):
620 """This demo shows the use of readers, data information and display
623 # Create the exodus reader and specify a file name
624 reader = ExodusIIReader(FileName=fname)
625 # Get the list of point arrays.
626 avail = reader.PointVariables.Available
629 reader.PointVariables = avail
631 # Turn on the visibility of the reader
633 # Set representation to wireframe
634 SetDisplayProperties(Representation = "Wireframe")
635 # Black background is not pretty
636 SetViewProperties(Background = [0.4, 0.4, 0.6])
638 # Change the elevation of the camera. See VTK documentation of vtkCamera
639 # for camera parameters.
640 # NOTE: THIS WILL BE SIMPLER
641 GetActiveCamera().Elevation(45)
643 # Now that the reader executed, let's get some information about it's
645 pdi = reader[0].PointData
646 # This prints a list of all read point data arrays as well as their
648 print 'Number of point arrays:', len(pdi)
649 for i in range(len(pdi)):
651 print "----------------"
652 print "Array:", i, " ", ai.Name, ":"
653 numComps = ai.GetNumberOfComponents()
654 print "Number of components:", numComps
655 for j in range(numComps):
656 print "Range:", ai.GetRange(j)
657 # White is boring. Let's color the geometry using a variable.
658 # First create a lookup table. This object controls how scalar
659 # values are mapped to colors. See VTK documentation for
661 # Map min (0.00678) to blue, max (0.0288) to red
662 SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
663 # Color by point array called Pres
664 SetDisplayProperties(ColorAttributeType = "POINT_DATA")
665 SetDisplayProperties(ColorArrayName = "Pres")
669 print paravisSM.myParavis.GetTrace()
671 def SaveTrace(fileName):
672 paravisSM.myParavis.SaveTrace(fileName)
675 _add_functions(globals())
676 active_objects = ActiveObjects()
677 ## Initialisation for SALOME GUI
678 active_objects.view = servermanager.GetRenderView()
680 if not servermanager.ActiveConnection: