1 r"""servermanager is a module for using paraview server manager in Python.
2 One can always use the server manager API directly. However, this module
3 provides an interface easier to use from Python by wrapping several VTK
4 classes around Python classes.
6 Note that, upon load, this module will create several sub-modules: sources,
7 filters and rendering. These modules can be used to instantiate specific
8 proxy types. For a list, try "dir(servermanager.sources)"
11 from paraview.servermanager import *
13 # Creates a new built-in connection and makes it the active connection.
16 # Creates a new render view on the active connection.
17 renModule = CreateRenderView()
19 # Create a new sphere proxy on the active connection and register it
20 # in the sources group.
21 sphere = sources.SphereSource(registrationGroup="sources", ThetaResolution=16, PhiResolution=32)
23 # Create a representation for the sphere proxy and adds it to the render
25 display = CreateRepresentation(sphere, renModule)
27 renModule.StillRender()
32 import re, os, new, sys
37 def _wrap_property(proxy, smproperty):
38 """ Internal function.
39 Given a server manager property and its domains, returns the
40 appropriate python object.
43 if smproperty.IsA("vtkSMStringVectorProperty"):
44 al = smproperty.GetDomain("array_list")
45 if al and al.IsA("vtkSMArraySelectionDomain") and smproperty.GetRepeatable():
46 property = ArrayListProperty(proxy, smproperty)
47 elif al and al.IsA("vtkSMArrayListDomain") and smproperty.GetNumberOfElements() == 5:
48 property = ArraySelectionProperty(proxy, smproperty)
50 iter = smproperty.NewDomainIterator()
52 while not iter.IsAtEnd():
53 if iter.GetDomain().IsA("vtkSMFileListDomain"):
59 property = FileNameProperty(proxy, smproperty)
60 elif _make_name_valid(smproperty.GetXMLLabel()) == 'ColorArrayName':
61 property = ColorArrayProperty(proxy, smproperty)
63 property = VectorProperty(proxy, smproperty)
64 elif smproperty.IsA("vtkSMVectorProperty"):
65 if smproperty.IsA("vtkSMIntVectorProperty") and smproperty.GetDomain("enum"):
66 property = EnumerationProperty(proxy, smproperty)
68 property = VectorProperty(proxy, smproperty)
69 elif smproperty.IsA("vtkSMInputProperty"):
70 property = InputProperty(proxy, smproperty)
71 elif smproperty.IsA("vtkSMProxyProperty"):
72 property = ProxyProperty(proxy, smproperty)
74 property = Property(proxy, smproperty)
78 """Proxy for a server side object. A proxy manages the lifetime of
79 one or more server manager objects. It also provides an interface
80 to set and get the properties of the server side objects. These
81 properties are presented as Python properties. For example,
82 you can set a property Foo using the following:
85 proxy.Foo.SetData((1,2))
87 proxy.Foo[0:2] = (1,2)
88 For more information, see the documentation of the property which
92 This class also provides an iterator which can be used to iterate
95 proxy = Proxy(proxy=smproxy)
96 for property in proxy:
100 This is a python class that wraps a vtkSMProxy.. Makes it easier to
103 proxy.GetProperty("Foo").SetElement(0, 1)
104 proxy.GetProperty("Foo").SetElement(0, 2)
108 proxy.Foo.SetData((1,2))
110 proxy.Foo[0:2] = (1,2)
112 proxy.GetProperty("Foo").GetElement(0)
114 proxy.Foo.GetData()[0]
117 For proxy properties, you can use append:
118 proxy.GetProperty("Bar").AddProxy(foo)
120 proxy.Bar.append(foo)
121 Properties support most of the list API. See VectorProperty and
122 ProxyProperty documentation for details.
124 Please note that some of the methods accessible through the Proxy
125 class are not listed by help() because the Proxy objects forward
126 unresolved attributes to the underlying object. To get the full list,
127 see also dir(proxy.SMProxy). See also the doxygen based documentation
128 of the vtkSMProxy C++ class.
131 def __init__(self, **args):
132 """ Default constructor. It can be used to initialize properties
133 by passing keyword arguments where the key is the name of the
134 property. In addition registrationGroup and registrationName (optional)
135 can be specified (as keyword arguments) to automatically register
136 the proxy with the proxy manager. """
137 self.add_attribute('Observed', None)
138 self.add_attribute('ObserverTag', -1)
139 self.add_attribute('_Proxy__Properties', {})
140 self.add_attribute('_Proxy__LastAttrName', None)
141 self.add_attribute('SMProxy', None)
142 self.add_attribute('Port', 0)
145 self.Port = args['port']
149 self.InitializeFromProxy(args['proxy'])
153 if 'registrationGroup' in args:
154 registrationGroup = args['registrationGroup']
155 del args['registrationGroup']
156 registrationName = self.SMProxy.GetSelfIDAsString()
157 if 'registrationName' in args:
158 registrationName = args['registrationName']
159 del args['registrationName']
161 pxm.RegisterProxy(registrationGroup, registrationName, self.SMProxy)
162 for key in args.keys():
163 setattr(self, key, args[key])
164 self.UpdateVTKObjects()
165 # Visit all properties so that they are created
169 def __setattr__(self, name, value):
171 setter = getattr(self.__class__, name)
172 setter = setter.__set__
173 except AttributeError:
174 if not hasattr(self, name):
175 raise AttributeError("Attribute %s does not exist. " % name +
176 " This class does not allow addition of new attributes to avoid " +
177 "mistakes due to typos. Use add_attribute() if you really want " +
178 "to add this attribute.")
179 self.__dict__[name] = value
183 def add_attribute(self, name, value):
184 self.__dict__[name] = value
187 """Destructor. Cleans up all observers as well as remove
188 the proxy from the _pyproxies dictionary"""
189 # Make sure that we remove observers we added
191 observed = self.Observed
192 tag = self.ObserverTag
194 self.ObserverTag = -1
195 observed.RemoveObserver(tag)
196 if self.SMProxy and (self.SMProxy, self.Port) in _pyproxies:
197 del _pyproxies[(self.SMProxy, self.Port)]
199 def InitializeFromProxy(self, aProxy):
200 """Constructor. Assigns proxy to self.SMProxy, updates the server
201 object as well as register the proxy in _pyproxies dictionary."""
203 self.SMProxy = aProxy
204 self.SMProxy.UpdateVTKObjects()
205 _pyproxies[(self.SMProxy, self.Port)] = weakref.ref(self)
207 def Initialize(self):
208 "Overridden by the subclass created automatically"
211 def __eq__(self, other):
212 "Returns true if the underlying SMProxies are the same."
213 if isinstance(other, Proxy):
214 ## VSV using IsSame instead
215 return self.SMProxy.IsSame(other.SMProxy)
216 return self.SMProxy.IsSame(other)
218 def __ne__(self, other):
219 "Returns false if the underlying SMProxies are the same."
220 return not self.__eq__(other)
223 "Creates an iterator for the properties."
224 return PropertyIterator(self)
226 def SetPropertyWithName(self, pname, arg):
227 """Generic method for setting the value of a property."""
228 prop = self.GetProperty(pname)
230 raise RuntimeError, "Property %s does not exist. Please check the property name for typos." % pname
233 def GetPropertyValue(self, name):
234 """Returns a scalar for properties with 1 elements, the property
235 itself for vectors."""
236 p = self.GetProperty(name)
237 if isinstance(p, VectorProperty):
238 if p.GetNumberOfElements() == 1 and not p.GetRepeatable():
239 if p.SMProperty.IsA("vtkSMStringVectorProperty") or not p.GetArgumentIsArray():
241 elif isinstance(p, InputProperty):
242 if not p.GetMultipleInput():
247 elif isinstance(p, ProxyProperty):
248 if not p.GetRepeatable():
255 def GetProperty(self, name):
256 """Given a property name, returns the property object."""
257 if name in self.__Properties and self.__Properties[name]():
258 return self.__Properties[name]()
259 smproperty = self.SMProxy.GetProperty(name)
260 # Maybe they are looking by the label. Try to match that.
262 iter = PropertyIterator(self)
264 if name == _make_name_valid(iter.PropertyLabel):
265 smproperty = prop.SMProperty
268 property = _wrap_property(self, smproperty)
269 if property is not None:
271 self.__Properties[name] = weakref.ref(property)
275 def ListProperties(self):
276 """Returns a list of all property names on this proxy."""
278 iter = self.__iter__()
279 for property in iter:
280 name = _make_name_valid(iter.PropertyLabel)
282 property_list.append(name)
285 def __ConvertArgumentsAndCall(self, *args):
286 """ Internal function.
287 Used to call a function on SMProxy. Converts input and
288 output values as appropriate.
292 if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
293 newArgs.append(arg.SMProxy)
296 func = getattr(self.SMProxy, self.__LastAttrName)
297 retVal = func(*newArgs)
298 if type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProxy"):
299 return _getPyProxy(retVal)
300 elif type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProperty"):
301 return _wrap_property(self, retVal)
305 def __GetActiveCamera(self):
306 """ This method handles GetActiveCamera specially. It adds
307 an observer to the camera such that everytime it is modified
308 the render view updated"""
310 c = self.SMProxy.GetActiveCamera()
311 # VSV: Observers are not supported
312 ## if not c.HasObserver("ModifiedEvent"):
313 ## self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self)))
317 def __getattr__(self, name):
318 """With the exception of a few overloaded methods,
319 returns the SMProxy method"""
321 raise AttributeError("class has no attribute %s" % name)
323 # Handle GetActiveCamera specially.
324 if name == "GetActiveCamera" and \
325 hasattr(self.SMProxy, "GetActiveCamera"):
326 return self.__GetActiveCamera
327 if name == "SaveDefinition" and hasattr(self.SMProxy, "SaveDefinition"):
328 return self.__SaveDefinition
329 # If not a property, see if SMProxy has the method
331 proxyAttr = getattr(self.SMProxy, name)
332 self.__LastAttrName = name
333 return self.__ConvertArgumentsAndCall
336 return getattr(self.SMProxy, name)
338 class SourceProxy(Proxy):
339 """Proxy for a source object. This class adds a few methods to Proxy
340 that are specific to sources. It also provides access to the output
341 ports. Output ports can be accessed by name or index:
344 > op = source['some name'].
346 def UpdatePipeline(self, time=None):
347 """This method updates the server-side VTK pipeline and the associated
348 data information. Make sure to update a source to validate the output
351 self.SMProxy.UpdatePipeline(time)
353 self.SMProxy.UpdatePipeline()
354 # Fetch the new information. This is also here to cause a receive
355 # on the client side so that progress works properly.
356 self.SMProxy.GetDataInformation()
358 def FileNameChanged(self):
359 "Called when the filename of a source proxy is changed."
360 self.UpdatePipelineInformation()
362 def UpdatePipelineInformation(self):
363 """This method updates the meta-data of the server-side VTK pipeline and
364 the associated information properties"""
365 self.SMProxy.UpdatePipelineInformation()
367 def GetDataInformation(self, idx=None):
368 """This method returns a DataInformation wrapper around a
369 vtkPVDataInformation"""
373 return DataInformation( \
374 self.SMProxy.GetDataInformation(idx), \
377 def __getitem__(self, idx):
378 """Given a slice, int or string, returns the corresponding
380 if isinstance(idx, slice):
381 indices = idx.indices(self.SMProxy.GetNumberOfOutputPorts())
383 for i in range(*indices):
384 retVal.append(OutputPort(self, i))
386 elif isinstance(idx, int):
387 if idx >= self.SMProxy.GetNumberOfOutputPorts() or idx < 0:
389 return OutputPort(self, idx)
391 return OutputPort(self, self.SMProxy.GetOutputPortIndex(idx))
393 def GetPointDataInformation(self):
394 """Returns the associated point data information."""
395 self.UpdatePipeline()
396 return FieldDataInformation(self.SMProxy, self.Port, "PointData")
398 def GetCellDataInformation(self):
399 """Returns the associated cell data information."""
400 self.UpdatePipeline()
401 return FieldDataInformation(self.SMProxy, self.Port, "CellData")
403 def GetFieldDataInformation(self):
404 """Returns the associated cell data information."""
405 self.UpdatePipeline()
406 return FieldDataInformation(self.SMProxy, self.Port, "FieldData")
408 PointData = property(GetPointDataInformation, None, None, "Returns point data information")
409 CellData = property(GetCellDataInformation, None, None, "Returns cell data information")
410 FieldData = property(GetFieldDataInformation, None, None, "Returns field data information")
413 class ExodusIIReaderProxy(SourceProxy):
414 """Special class to define convenience functions for array
417 def FileNameChanged(self):
418 "Called when the filename changes. Selects all variables."
419 SourceProxy.FileNameChanged(self)
420 self.SelectAllVariables()
422 def SelectAllVariables(self):
423 "Select all available variables for reading."
424 for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
425 'ElementVariables', 'GlobalVariables'):
426 f = getattr(self, prop)
429 def DeselectAllVariables(self):
430 "Deselects all variables."
431 for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
432 'ElementVariables', 'GlobalVariables'):
433 f = getattr(self, prop)
436 class Property(object):
437 """Generic property object that provides access to one of the properties of
438 a server object. This class does not allow setting/getting any values but
439 provides an interface to update a property using __call__. This can be used
440 for command properties that correspond to function calls without arguments.
443 would push a Foo property which may cause the proxy to call a Foo method
444 on the actual VTK object.
447 Python wrapper around a vtkSMProperty with a simple interface.
448 In addition to all method provided by vtkSMProperty (obtained by
449 forwarding unknown attributes requests to the underlying SMProxy),
450 Property and sub-class provide a list API.
452 Please note that some of the methods accessible through the Property
453 class are not listed by help() because the Property objects forward
454 unresolved attributes to the underlying object. To get the full list,
455 see also dir(proxy.SMProperty). See also the doxygen based documentation
456 of the vtkSMProperty C++ class.
458 def __init__(self, proxy, smproperty):
459 """Default constructor. Stores a reference to the proxy."""
461 self.SMProperty = smproperty
465 """Returns a string representation containing property name
467 if not type(self) is Property:
468 if self.GetData() is not None:
469 repr = self.GetData().__repr__()
473 repr = "Property name= "
474 name = self.Proxy.GetPropertyName(self.SMProperty)
483 """Forces a property update using InvokeCommand."""
484 if type(self) is Property:
485 self.Proxy.SMProxy.InvokeCommand(self._FindPropertyName())
487 raise RuntimeError, "Cannot invoke this property"
489 def _FindPropertyName(self):
490 "Returns the name of this property."
491 return self.Proxy.GetPropertyName(self.SMProperty)
493 def _UpdateProperty(self):
494 "Pushes the value of this property to the server."
495 # For now, we are updating all properties. This is due to an
496 # issue with the representations. Their VTK objects are not
497 # created until Input is set therefore, updating a property
498 # has no effect. Updating all properties everytime one is
499 # updated has the effect of pushing values set before Input
500 # when Input is updated.
501 # self.Proxy.SMProxy.UpdateProperty(self._FindPropertyName())
502 self.Proxy.SMProxy.UpdateVTKObjects()
504 def __getattr__(self, name):
505 "Unknown attribute requests get forwarded to SMProperty."
506 return getattr(self.SMProperty, name)
508 class GenericIterator(object):
509 """Iterator for container type objects"""
511 def __init__(self, obj):
519 if self.index >= len(self.Object):
524 return self.Object[idx]
526 class VectorProperty(Property):
527 """A VectorProperty provides access to one or more values. You can use
528 a slice to get one or more property values:
531 > vals = property[0:5:2]
532 You can use a slice to set one or more property values:
535 > property[1:3] = (1,2)
537 def ConvertValue(self, value):
541 """Returns the number of elements."""
542 return self.SMProperty.GetNumberOfElements()
545 """Implementation of the sequence API"""
546 return GenericIterator(self)
548 def __setitem__(self, idx, value):
549 """Given a list or tuple of values, sets a slice of values [min, max)"""
550 if isinstance(idx, slice):
551 indices = idx.indices(len(self))
552 for i, j in zip(range(*indices), value):
553 self.SMProperty.SetElement(i, self.ConvertValue(j))
554 self._UpdateProperty()
555 elif idx >= len(self) or idx < 0:
558 self.SMProperty.SetElement(idx, self.ConvertValue(value))
559 self._UpdateProperty()
561 def GetElement(self, index):
562 return self.SMProperty.GetElement(index)
564 def __getitem__(self, idx):
565 """Returns the range [min, max) of elements. Raises an IndexError
566 exception if an argument is out of bounds."""
568 if isinstance(idx, slice):
569 indices = idx.indices(ls)
571 for i in range(*indices):
572 retVal.append(self.GetElement(i))
581 return self.GetElement(idx)
584 "Returns all elements as either a list or a single value."
585 property = self.SMProperty
586 if property.GetRepeatable() or \
587 property.GetNumberOfElements() > 1:
588 return self[0:len(self)]
589 elif property.GetNumberOfElements() == 1:
590 return self.GetElement(0)
592 def SetData(self, values):
593 """Allows setting of all values at once. Requires a single value or
594 a iterable object."""
595 if not hasattr(values, "__iter__"):
597 iup = self.SMProperty.GetImmediateUpdate()
598 self.SMProperty.SetImmediateUpdate(False)
599 if not self.GetRepeatable() and len(values) != self.GetNumberOfElements():
600 raise RuntimeError("This property requires %d values." % self.GetNumberOfElements())
601 if self.GetRepeatable():
603 self.SMProperty.SetNumberOfElements(0)
606 self.SMProperty.SetElement(idx, self.ConvertValue(val))
608 self.SMProperty.SetImmediateUpdate(iup)
609 self._UpdateProperty()
612 "Removes all elements."
613 self.SMProperty().SetNumberOfElements(0)
614 self._UpdateProperty()
616 class ColorArrayProperty(VectorProperty):
617 """This subclass of VectorProperty handles setting of the array to
618 color by. It handles attribute type as well as well array name."""
620 def GetAvailable(self):
621 """"Returns the list of available arrays as (attribute type, array name
624 for a in self.Proxy.Input.PointData:
625 arrays.append(('POINT_DATA', a.GetName()))
626 for a in self.Proxy.Input.CellData:
627 arrays.append(('CELL_DATA', a.GetName()))
630 def SetData(self, value):
631 """Overwritten to enable setting attribute type (the ColorAttributeType
632 property and the array name. The argument should be the array name
633 (in which case the first appropriate attribute type is picked) or
634 a tuple of attribute type and array name."""
635 if isinstance(value, tuple) and len(value) == 2:
638 elif isinstance(value, str):
642 raise ValueError("Expected a tuple of 2 values or a string.")
645 self.SMProperty.SetElement(0, '')
646 self._UpdateProperty()
650 for a in self.Available:
651 if a[1] == arr and (not att or att == a[0]):
657 raise ValueError("Could not locate array %s in the input." % arr)
659 catt = self.Proxy.GetProperty("ColorAttributeType")
661 self.SMProperty.SetElement(0, arr)
662 self._UpdateProperty()
664 Available = property(GetAvailable, None, None, \
665 "This read-only property returns the list of arrays that can be colored by.")
668 class EnumerationProperty(VectorProperty):
669 """"Subclass of VectorProperty that is applicable for enumeration type
672 def GetElement(self, index):
673 """Returns the text for the given element if available. Returns
674 the numerical values otherwise."""
675 val = self.SMProperty.GetElement(index)
676 domain = self.SMProperty.GetDomain("enum")
677 for i in range(domain.GetNumberOfEntries()):
678 if domain.GetEntryValue(i) == val:
679 return domain.GetEntryText(i)
682 def ConvertValue(self, value):
683 """Converts value to type suitable for vtSMProperty::SetElement()"""
684 if type(value) == str:
685 domain = self.SMProperty.GetDomain("enum")
686 if domain.HasEntryText(value):
687 return domain.GetEntryValueForText(value)
689 raise ValueError("%s is not a valid value." % value)
690 return VectorProperty.ConvertValue(self, value)
692 def GetAvailable(self):
693 "Returns the list of available values for the property."
695 domain = self.SMProperty.GetDomain("enum")
696 for i in range(domain.GetNumberOfEntries()):
697 retVal.append(domain.GetEntryText(i))
700 Available = property(GetAvailable, None, None, \
701 "This read-only property contains the list of values that can be applied to this property.")
704 class FileNameProperty(VectorProperty):
705 """Property to set/get one or more file names.
706 This property updates the pipeline information everytime its value changes.
707 This is used to keep the array lists up to date."""
709 def _UpdateProperty(self):
710 "Pushes the value of this property to the server."
711 VectorProperty._UpdateProperty(self)
712 self.Proxy.FileNameChanged()
714 class ArraySelectionProperty(VectorProperty):
715 "Property to select an array to be processed by a filter."
717 def GetAssociation(self):
718 val = self.GetElement(3)
721 for key, value in ASSOCIATIONS.iteritems():
722 if value == int(val):
727 def GetArrayName(self):
728 return self.GetElement(4)
731 """Returns the number of elements."""
734 def __setitem__(self, idx, value):
735 raise RuntimeError, "This property cannot be accessed using __setitem__"
737 def __getitem__(self, idx):
738 """Returns attribute type for index 0, array name for index 1"""
739 if isinstance(idx, slice):
740 indices = idx.indices(len(self))
742 for i in range(*indices):
746 retVal.append(self.GetAssociation())
748 retVal.append(self.GetArrayName())
750 elif idx >= 2 or idx < 0:
754 return self.GetAssociation()
756 return self.GetArrayName()
758 def SetData(self, values):
759 """Allows setting of all values at once. Requires a single value,
761 if not isinstance(values, tuple) and \
762 not isinstance(values, list):
765 self.SMProperty.SetElement(4, values[0])
766 elif len(values) == 2:
767 if isinstance(values[0], str):
768 val = str(ASSOCIATIONS[values[0]])
769 self.SMProperty.SetElement(3, str(val))
770 self.SMProperty.SetElement(4, values[1])
772 raise RuntimeError, "Expected 1 or 2 values."
773 self._UpdateProperty()
775 def UpdateDefault(self):
776 "Helper method to set default values."
777 if self.SMProperty.GetNumberOfElements() != 5:
779 if self.GetElement(4) != '' or \
780 self.GetElement(3) != '':
784 if self.GetElement(i) == '':
785 self.SMProperty.SetElement(i, '0')
786 al = self.SMProperty.GetDomain("array_list")
787 al.Update(self.SMProperty)
788 al.SetDefaultValues(self.SMProperty)
790 class ArrayListProperty(VectorProperty):
791 """This property provides a simpler interface for selecting arrays.
792 Simply assign a list of arrays that should be loaded by the reader.
793 Use the Available property to get a list of available arrays."""
795 def __init__(self, proxy, smproperty):
796 VectorProperty.__init__(self, proxy, smproperty)
799 def GetAvailable(self):
800 "Returns the list of available arrays"
801 dm = self.GetDomain("array_list")
803 for i in range(dm.GetNumberOfStrings()):
804 retVal.append(dm.GetString(i))
807 Available = property(GetAvailable, None, None, \
808 "This read-only property contains the list of items that can be read by a reader.")
811 "Selects all arrays."
812 self.SetData(self.Available)
814 def DeselectAll(self):
815 "Deselects all arrays."
819 """Implementation of the sequence API"""
820 return GenericIterator(self)
823 """Returns the number of elements."""
824 return len(self.GetData())
826 def __setitem__(self, idx, value):
827 """Given a list or tuple of values, sets a slice of values [min, max)"""
829 if isinstance(idx, slice):
830 indices = idx.indices(len(self))
831 for i, j in zip(range(*indices), value):
833 self.SetData(self.__arrays)
834 elif idx >= len(self) or idx < 0:
837 self.__arrays[idx] = self.ConvertValue(value)
838 self.SetData(self.__arrays)
840 def __getitem__(self, idx):
841 """Returns the range [min, max) of elements. Raises an IndexError
842 exception if an argument is out of bounds."""
844 if isinstance(idx, slice):
845 indices = idx.indices(len(self))
847 for i in range(*indices):
848 retVal.append(self.__arrays[i])
850 elif idx >= len(self) or idx < 0:
852 return self.__arrays[idx]
854 def SetData(self, values):
855 """Allows setting of all values at once. Requires a single value,
858 iup = self.SMProperty.GetImmediateUpdate()
859 self.SMProperty.SetImmediateUpdate(False)
861 self.SMProperty.SetNumberOfElements(0)
862 if not isinstance(values, tuple) and \
863 not isinstance(values, list):
866 for i in range(len(values)):
867 val = self.ConvertValue(values[i])
868 fullvalues.append(val)
869 fullvalues.append('1')
870 for array in self.Available:
871 if not values.__contains__(array):
872 fullvalues.append(array)
873 fullvalues.append('0')
875 for value in fullvalues:
876 self.SMProperty.SetElement(i, value)
879 self._UpdateProperty()
880 self.SMProperty.SetImmediateUpdate(iup)
883 "Returns all elements as a list."
884 property = self.SMProperty
885 nElems = property.GetNumberOfElements()
887 raise ValueError, "The SMProperty with XML label '%s' has a size that is not a multiple of 2." % property.GetXMLLabel()
889 for i in range(0, nElems, 2):
890 if self.GetElement(i+1) != '0':
891 self.__arrays.append(self.GetElement(i))
892 return list(self.__arrays)
894 class ProxyProperty(Property):
895 """A ProxyProperty provides access to one or more proxies. You can use
896 a slice to get one or more property values:
897 > proxy = property[2]
899 > proxies = property[0:5:2]
900 You can use a slice to set one or more property values:
901 > property[2] = proxy
903 > property[1:3] = (proxy1, proxy2)
904 You can also append and delete:
905 > property.append(proxy)
909 You can also remove all elements with Clear().
911 Note that some properties expect only 1 proxy and will complain if
912 you set the number of values to be something else.
914 def __init__(self, proxy, smproperty):
915 """Default constructor. Stores a reference to the proxy. Also looks
916 at domains to find valid values."""
917 Property.__init__(self, proxy, smproperty)
918 # Check to see if there is a proxy list domain and, if so,
919 # initialize ourself. (Should this go in ProxyProperty?)
920 listdomain = self.GetDomain('proxy_list')
922 if listdomain.GetClassName() != 'vtkSMProxyListDomain':
923 raise ValueError, "Found a 'proxy_list' domain on an InputProperty that is not a ProxyListDomain."
925 group = "pq_helper_proxies." + proxy.GetSelfIDAsString()
926 if listdomain.GetNumberOfProxies() == 0:
927 for i in xrange(listdomain.GetNumberOfProxyTypes()):
928 igroup = listdomain.GetProxyGroup(i)
929 name = listdomain.GetProxyName(i)
930 iproxy = CreateProxy(igroup, name)
931 listdomain.AddProxy(iproxy)
932 pm.RegisterProxy(group, proxy.GetPropertyName(smproperty), iproxy)
933 listdomain.SetDefaultValues(self.SMProperty)
935 def GetAvailable(self):
936 """If this proxy has a list domain, then this function returns the
937 strings you can use to select from the domain. If there is no such
938 list domain, the returned list is empty."""
939 listdomain = self.GetDomain('proxy_list')
942 for i in xrange(listdomain.GetNumberOfProxies()):
943 proxy = listdomain.GetProxy(i)
944 retval.append(proxy.GetXMLLabel())
947 Available = property(GetAvailable, None, None,
948 """This read only property is a list of strings you can
949 use to select from the list domain. If there is no
950 such list domain, the array is empty.""")
953 """Implementation of the sequence API"""
954 return GenericIterator(self)
957 """Returns the number of elements."""
958 return self.SMProperty.GetNumberOfProxies()
960 def remove(self, proxy):
961 """Removes the first occurence of the proxy from the property."""
962 self.SMProperty.RemoveProxy(proxy.SMProxy)
963 self._UpdateProperty()
965 def __setitem__(self, idx, value):
966 """Given a list or tuple of values, sets a slice of values [min, max)"""
967 if isinstance(idx, slice):
968 indices = idx.indices(len(self))
969 for i, j in zip(range(*indices), value):
970 self.SMProperty.SetProxy(i, j.SMProxy)
971 self._UpdateProperty()
972 elif idx >= len(self) or idx < 0:
975 self.SMProperty.SetProxy(idx, value.SMProxy)
976 self._UpdateProperty()
978 def __delitem__(self,idx):
979 """Removes the element idx"""
980 if isinstance(idx, slice):
981 indices = idx.indices(len(self))
982 # Collect the elements to delete to a new list first.
983 # Otherwise indices are screwed up during the actual
986 for i in range(*indices):
987 toremove.append(self[i])
989 self.SMProperty.RemoveProxy(i.SMProxy)
990 self._UpdateProperty()
991 elif idx >= len(self) or idx < 0:
994 self.SMProperty.RemoveProxy(self[idx].SMProxy)
995 self._UpdateProperty()
997 def __getitem__(self, idx):
998 """Returns the range [min, max) of elements. Raises an IndexError
999 exception if an argument is out of bounds."""
1000 if isinstance(idx, slice):
1001 indices = idx.indices(len(self))
1003 for i in range(*indices):
1004 retVal.append(_getPyProxy(self.SMProperty.GetProxy(i)))
1006 elif idx >= len(self) or idx < 0:
1008 return _getPyProxy(self.SMProperty.GetProxy(idx))
1010 def __getattr__(self, name):
1011 "Unknown attribute requests get forwarded to SMProperty."
1012 return getattr(self.SMProperty, name)
1014 def index(self, proxy):
1018 if proxy.IsSame(px):
1021 raise ValueError("proxy is not in the list.")
1023 def append(self, proxy):
1024 "Appends the given proxy to the property values."
1025 self.SMProperty.AddProxy(proxy.SMProxy)
1026 self._UpdateProperty()
1029 "Returns all elements as either a list or a single value."
1030 property = self.SMProperty
1031 if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
1032 return self[0:len(self)]
1034 if property.GetNumberOfProxies() > 0:
1035 return _getPyProxy(property.GetProxy(0))
1038 def SetData(self, values):
1039 """Allows setting of all values at once. Requires a single value,
1041 if isinstance(values, str):
1044 position = self.Available.index(values)
1046 raise ValueError, values + " is not a valid object in the domain."
1047 values = self.GetDomain('proxy_list').GetProxy(position)
1048 if not isinstance(values, tuple) and \
1049 not isinstance(values, list):
1051 self.SMProperty.RemoveAllProxies()
1052 for value in values:
1053 if isinstance(value, Proxy):
1054 value_proxy = value.SMProxy
1057 self.SMProperty.AddProxy(value_proxy)
1058 self._UpdateProperty()
1061 "Removes all elements."
1062 self.SMProperty.RemoveAllProxies()
1063 self._UpdateProperty()
1065 class InputProperty(ProxyProperty):
1066 """An InputProperty allows making pipeline connections. You can set either
1067 a source proxy or an OutputProperty to an input property:
1069 > property[0] = proxy
1071 > property[0] = OuputPort(proxy, 1)
1073 > property.append(proxy)
1075 > property.append(OutputPort(proxy, 0))
1077 def __setitem__(self, idx, value):
1078 """Given a list or tuple of values, sets a slice of values [min, max)"""
1079 if isinstance(idx, slice):
1080 indices = idx.indices(len(self))
1081 for i, j in zip(range(*indices), value):
1083 self.SMProperty.SetInputConnection(i, op.SMProxy, op.Port)
1084 self._UpdateProperty()
1085 elif idx >= len(self) or idx < 0:
1088 self.SMProperty.SetInputConnection(idx, value.SMProxy, value.Port)
1089 self._UpdateProperty()
1091 def __getitem__(self, idx):
1092 """Returns the range [min, max) of elements. Raises an IndexError
1093 exception if an argument is out of bounds."""
1094 if isinstance(idx, slice):
1095 indices = idx.indices(len(self))
1097 for i in range(*indices):
1099 if self.SMProperty.GetProxy(i):
1100 port = OutputPort(_getPyProxy(self.SMProperty.GetProxy(i)),\
1101 self.SMProperty.GetOutputPortForConnection(i))
1104 elif idx >= len(self) or idx < 0:
1106 return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\
1107 self.SMProperty.GetOutputPortForConnection(idx))
1109 def append(self, value):
1110 """Appends the given proxy to the property values.
1111 Accepts Proxy or OutputPort objects."""
1112 self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
1113 self._UpdateProperty()
1116 """Returns all elements as either a list of OutputPort objects or
1117 a single OutputPort object."""
1118 property = self.SMProperty
1119 if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
1120 return self[0:len(self)]
1122 if property.GetNumberOfProxies() > 0:
1123 return OutputPort(_getPyProxy(property.GetProxy(0)),\
1124 self.SMProperty.GetOutputPortForConnection(0))
1127 def SetData(self, values):
1128 """Allows setting of all values at once. Requires a single value,
1129 a tuple or list. Accepts Proxy or OutputPort objects."""
1130 if isinstance(values, str):
1131 ProxyProperty.SetData(self, values)
1133 if not isinstance(values, tuple) and \
1134 not isinstance(values, list):
1136 self.SMProperty.RemoveAllProxies()
1137 for value in values:
1139 self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
1140 self._UpdateProperty()
1142 def _UpdateProperty(self):
1143 "Pushes the value of this property to the server."
1144 ProxyProperty._UpdateProperty(self)
1145 iter = PropertyIterator(self.Proxy)
1147 if isinstance(prop, ArraySelectionProperty):
1148 prop.UpdateDefault()
1151 class DataInformation(object):
1152 """DataInformation is a contained for meta-data associated with an
1155 DataInformation is a python wrapper around a vtkPVDataInformation.
1156 In addition to proving all methods of a vtkPVDataInformation, it provides
1157 a few convenience methods.
1159 Please note that some of the methods accessible through the DataInformation
1160 class are not listed by help() because the DataInformation objects forward
1161 unresolved attributes to the underlying object. To get the full list,
1162 see also dir(proxy.DataInformation).
1163 See also the doxygen based documentation of the vtkPVDataInformation C++
1166 def __init__(self, dataInformation, proxy, idx):
1167 """Default constructor. Requires a vtkPVDataInformation, a source proxy
1168 and an output port id."""
1169 self.DataInformation = dataInformation
1174 """****Deprecated**** There is no reason anymore to use this method
1175 explicitly, it is called automatically when one gets any value from the
1176 data information object.
1177 Update the data information if necessary. Note that this
1178 does not cause execution of the underlying object. In certain
1179 cases, you may have to call UpdatePipeline() on the proxy."""
1181 self.Proxy.GetDataInformation(self.Idx)
1183 def GetDataSetType(self):
1184 """Returns the dataset type as defined in vtkDataObjectTypes."""
1186 if not self.DataInformation:
1187 raise RuntimeError, "No data information is available"
1188 if self.DataInformation.GetCompositeDataSetType() > -1:
1189 return self.DataInformation.GetCompositeDataSetType()
1190 return self.DataInformation.GetDataSetType()
1192 def GetDataSetTypeAsString(self):
1193 """Returns the dataset type as a user-friendly string. This is
1194 not the same as the enumaration used by VTK"""
1195 return vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType())
1197 def __getattr__(self, name):
1198 """Forwards unknown attribute requests to the underlying
1199 vtkPVInformation."""
1200 if not self.DataInformation:
1201 raise AttributeError("class has no attribute %s" % name)
1204 return getattr(self.DataInformation, name)
1206 class ArrayInformation(object):
1207 """Meta-information associated with an array. Use the Name
1208 attribute to get the array name.
1210 Please note that some of the methods accessible through the ArrayInformation
1211 class are not listed by help() because the ArrayInformation objects forward
1212 unresolved attributes to the underlying object.
1213 See the doxygen based documentation of the vtkPVArrayInformation C++
1214 class for a full list.
1216 def __init__(self, proxy, field, name):
1218 self.FieldData = field
1221 def __getattr__(self, name):
1222 """Forward unknown methods to vtkPVArrayInformation"""
1223 array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
1224 if not array: return None
1225 return getattr(array, name)
1228 """Returns a user-friendly representation string."""
1229 return "Array: " + self.Name
1231 def GetRange(self, component=0):
1232 """Given a component, returns its value range as a tuple of 2 values."""
1233 array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
1234 range = array.GetComponentRange(component)
1235 return (range[0], range[1])
1238 class FieldDataInformationIterator(object):
1239 """Iterator for FieldDataInformation"""
1241 def __init__(self, info, items=False):
1242 self.FieldDataInformation = info
1250 if self.index >= self.FieldDataInformation.GetNumberOfArrays():
1254 ai = self.FieldDataInformation[self.index-1]
1256 return (ai.GetName(), ai)
1261 class FieldDataInformation(object):
1262 """Meta-data for a field of an output object (point data, cell data etc...).
1263 Provides easy access to the arrays using the slice interface:
1264 > narrays = len(field_info)
1265 > for i in range(narrays):
1266 > array_info = field_info[i]
1268 Full slice interface is supported:
1269 > arrays = field_info[0:5:3]
1270 where arrays is a list.
1272 Array access by name is also possible:
1273 > array_info = field_info['Temperature']
1275 The number of arrays can also be accessed using the NumberOfArrays
1278 def __init__(self, proxy, idx, field):
1280 self.OutputPort = idx
1281 self.FieldData = field
1283 def GetFieldData(self):
1284 """Convenience method to get the underlying
1285 vtkPVDataSetAttributesInformation"""
1286 return getattr(self.Proxy.GetDataInformation(self.OutputPort), "Get%sInformation" % self.FieldData)()
1288 def GetNumberOfArrays(self):
1289 """Returns the number of arrays."""
1290 self.Proxy.UpdatePipeline()
1291 return self.GetFieldData().GetNumberOfArrays()
1293 def GetArray(self, idx):
1294 """Given an index or a string, returns an array information.
1295 Raises IndexError if the index is out of bounds."""
1296 self.Proxy.UpdatePipeline()
1297 if not self.GetFieldData().GetArrayInformation(idx):
1299 if isinstance(idx, str):
1300 return ArrayInformation(self.Proxy, self, idx)
1301 elif idx >= len(self) or idx < 0:
1303 return ArrayInformation(self.Proxy, self, self.GetFieldData().GetArrayInformation(idx).GetName())
1306 """Returns the number of arrays."""
1307 return self.GetNumberOfArrays()
1309 def __getitem__(self, idx):
1310 """Implements the [] operator. Accepts an array name."""
1311 if isinstance(idx, slice):
1312 indices = idx.indices(self.GetNumberOfArrays())
1314 for i in range(*indices):
1315 retVal.append(self.GetArray(i))
1317 return self.GetArray(idx)
1320 """Implementation of the dictionary API"""
1322 narrays = self.GetNumberOfArrays()
1323 for i in range(narrays):
1324 kys.append(self.GetArray(i).GetName())
1328 """Implementation of the dictionary API"""
1330 narrays = self.GetNumberOfArrays()
1331 for i in range(narrays):
1332 vals.append(self.GetArray(i))
1335 def iteritems(self):
1336 """Implementation of the dictionary API"""
1337 return FieldDataInformationIterator(self, True)
1340 """Implementation of the dictionary API"""
1342 narrays = self.GetNumberOfArrays()
1343 for i in range(narrays):
1344 ai = self.GetArray(i)
1345 itms.append((ai.GetName(), ai))
1348 def has_key(self, key):
1349 """Implementation of the dictionary API"""
1350 if self.GetArray(key):
1355 """Implementation of the dictionary API"""
1356 return FieldDataInformationIterator(self)
1358 def __getattr__(self, name):
1359 """Forwards unknown attributes to the underlying
1360 vtkPVDataSetAttributesInformation"""
1361 array = self.GetArray(name)
1362 if array: return array
1363 raise AttributeError("class has no attribute %s" % name)
1366 NumberOfArrays = property(GetNumberOfArrays, None, None, "Returns the number of arrays.")
1368 def OutputPort(proxy, outputPort=0):
1371 if isinstance(outputPort, str):
1372 outputPort = proxy.GetOutputPortIndex(outputPort)
1373 if outputPort >= proxy.GetNumberOfOutputPorts():
1375 if proxy.Port == outputPort:
1377 newinstance = _getPyProxy(proxy.SMProxy, outputPort)
1378 newinstance.Port = outputPort
1379 newinstance._Proxy__Properties = proxy._Proxy__Properties
1382 class ProxyManager(object):
1383 """When running scripts from the python shell in the ParaView application,
1384 registering proxies with the proxy manager is the ony mechanism to
1385 notify the graphical user interface (GUI) that a proxy
1386 exists. Therefore, unless a proxy is registered, it will not show up in
1387 the user interface. Also, the proxy manager is the only way to get
1388 access to proxies created using the GUI. Proxies created using the GUI
1389 are automatically registered under an appropriate group (sources,
1390 filters, representations and views). To get access to these objects,
1391 you can use proxyManager.GetProxy(group, name). The name is the same
1392 as the name shown in the pipeline browser.
1394 This class is a python wrapper for vtkSMProxyManager. Note that the
1395 underlying vtkSMProxyManager is a singleton. All instances of this
1396 class wil refer to the same object. In addition to all methods provided by
1397 vtkSMProxyManager (all unknown attribute requests are forwarded
1398 to the vtkSMProxyManager), this class provides several convenience
1401 Please note that some of the methods accessible through the ProxyManager
1402 class are not listed by help() because the ProxyManager objects forwards
1403 unresolved attributes to the underlying object. To get the full list,
1404 see also dir(proxy.SMProxyManager). See also the doxygen based documentation
1405 of the vtkSMProxyManager C++ class.
1409 """Constructor. Assigned self.SMProxyManager to
1410 vtkSMObject.GetPropertyManager()."""
1411 self.SMProxyManager = vtkSMObject.GetProxyManager()
1413 def RegisterProxy(self, group, name, aProxy):
1414 """Registers a proxy (either SMProxy or proxy) with the
1416 if isinstance(aProxy, Proxy):
1417 self.SMProxyManager.RegisterProxy(group, name, aProxy.SMProxy)
1419 self.SMProxyManager.RegisterProxy(group, name, aProxy)
1421 def NewProxy(self, group, name):
1422 """Creates a new proxy of given group and name and returns an SMProxy.
1423 Note that this is a server manager object. You should normally create
1424 proxies using the class objects. For example:
1425 obj = servermanager.sources.SphereSource()"""
1426 if not self.SMProxyManager:
1428 aProxy = self.SMProxyManager.NewProxy(group, name)
1431 aProxy.UnRegister(None)
1434 def GetProxy(self, group, name):
1435 """Returns a Proxy registered under a group and name"""
1436 if not self.SMProxyManager:
1438 aProxy = self.SMProxyManager.GetProxy(group, name)
1441 return _getPyProxy(aProxy)
1443 def GetPrototypeProxy(self, group, name):
1444 """Returns a prototype proxy given a group and name. This is an
1445 SMProxy. This is a low-level method. You should not normally
1447 if not self.SMProxyManager:
1449 aProxy = self.SMProxyManager.GetPrototypeProxy(group, name)
1454 def GetProxiesOnConnection(self, connection):
1455 """Returns a map of proxies registered with the proxy manager
1456 on the particular connection."""
1458 iter = self.NewConnectionIterator(connection)
1460 if not proxy_groups.has_key(iter.GetGroup()):
1461 proxy_groups[iter.GetGroup()] = {}
1462 group = proxy_groups[iter.GetGroup()]
1463 group[(iter.GetKey(), proxy.GetSelfIDAsString())] = proxy
1466 def GetProxiesInGroup(self, groupname, connection=None):
1467 """Returns a map of proxies in a particular group.
1468 If connection is not None, then only those proxies
1469 in the group that are on the particular connection
1473 iter = self.NewGroupIterator(groupname)
1475 proxies[(iter.GetKey(), aProxy.GetSelfIDAsString())] = aProxy
1478 def UnRegisterProxy(self, groupname, proxyname, aProxy):
1479 """Unregisters a proxy."""
1480 if not self.SMProxyManager:
1482 if aProxy != None and isinstance(aProxy,Proxy):
1483 aProxy = aProxy.SMProxy
1485 self.SMProxyManager.UnRegisterProxy(groupname, proxyname, aProxy)
1487 def GetProxies(self, groupname, proxyname):
1488 """Returns all proxies registered under the given group with the
1489 given name. Note that it is possible to register more than one
1490 proxy with the same name in the same group. Because the proxies
1491 are different, there is no conflict. Use this method instead of
1492 GetProxy() if you know that there are more than one proxy registered
1494 if not self.SMProxyManager:
1496 collection = vtkCollection()
1498 self.SMProxyManager.GetProxies(groupname, proxyname, collection)
1499 for i in range(0, collection.GetNumberOfItems()):
1500 aProxy = _getPyProxy(collection.GetItemAsObject(i))
1502 result.append(aProxy)
1507 """Returns a new ProxyIterator."""
1508 iter = ProxyIterator()
1509 if ActiveConnection:
1510 iter.SetConnectionID(ActiveConnection.ID)
1514 def NewGroupIterator(self, group_name, connection=None):
1515 """Returns a ProxyIterator for a group. The resulting object
1516 can be used to traverse the proxies that are in the given
1518 iter = self.__iter__()
1520 connection = ActiveConnection
1522 iter.SetConnectionID(connection.ID)
1523 iter.SetModeToOneGroup()
1524 iter.Begin(group_name)
1527 def NewConnectionIterator(self, connection=None):
1528 """Returns a ProxyIterator for a given connection. This can be
1529 used to travers ALL proxies managed by the proxy manager."""
1530 iter = self.__iter__()
1532 connection = ActiveConnection
1534 iter.SetConnectionID(connection.ID)
1538 def NewDefinitionIterator(self, groupname=None):
1539 """Returns an iterator that can be used to iterate over
1540 all groups and types of proxies that the proxy manager
1542 iter = ProxyDefinitionIterator()
1543 if groupname != None:
1544 iter.SetModeToOneGroup()
1545 iter.Begin(groupname)
1548 def __ConvertArgumentsAndCall(self, *args):
1551 if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
1552 newArgs.append(arg.SMProxy)
1555 func = getattr(self.SMProxyManager, self.__LastAttrName)
1556 retVal = func(*newArgs)
1557 if type(retVal) is type(self.SMProxyManager) and retVal.IsA("vtkSMProxy"):
1558 return _getPyProxy(retVal)
1562 def __getattr__(self, name):
1563 """Returns attribute from the ProxyManager"""
1565 pmAttr = getattr(self.SMProxyManager, name)
1566 self.__LastAttrName = name
1567 return self.__ConvertArgumentsAndCall
1570 return getattr(self.SMProxyManager, name)
1573 class PropertyIterator(object):
1574 """Wrapper for a vtkSMPropertyIterator class to satisfy
1575 the python iterator protocol. Note that the list of
1576 properties can also be obtained from the class object's
1578 See the doxygen documentation for vtkSMPropertyIterator C++
1582 def __init__(self, aProxy):
1583 self.SMIterator = aProxy.NewPropertyIterator()
1585 self.SMIterator.UnRegister(None)
1586 self.SMIterator.Begin()
1588 self.PropertyLabel = None
1595 if not self.SMIterator:
1598 if self.SMIterator.IsAtEnd():
1601 self.Key = self.SMIterator.GetKey()
1602 self.PropertyLabel = self.SMIterator.GetPropertyLabel()
1603 self.SMIterator.Next()
1604 return self.Proxy.GetProperty(self.Key)
1607 """Returns the proxy for the property last returned by the call to
1612 """Returns the key for the property last returned by the call to
1616 def GetProperty(self):
1617 """Returns the property last returned by the call to 'next()' """
1618 return self.Proxy.GetProperty(self.Key)
1620 def __getattr__(self, name):
1621 """returns attributes from the vtkSMProxyIterator."""
1622 return getattr(self.SMIterator, name)
1624 class ProxyDefinitionIterator(object):
1625 """Wrapper for a vtkSMProxyDefinitionIterator class to satisfy
1626 the python iterator protocol.
1627 See the doxygen documentation of the vtkSMProxyDefinitionIterator
1628 C++ class for more information."""
1630 self.SMIterator = vtkSMProxyDefinitionIterator()
1638 if self.SMIterator.IsAtEnd():
1642 self.Group = self.SMIterator.GetGroup()
1643 self.Key = self.SMIterator.GetKey()
1644 self.SMIterator.Next()
1645 return {"group": self.Group, "key":self.Key }
1648 """Returns the key for the proxy definition last returned by the call
1653 """Returns the group for the proxy definition last returned by the
1654 call to 'next()' """
1657 def __getattr__(self, name):
1658 """returns attributes from the vtkSMProxyDefinitionIterator."""
1659 return getattr(self.SMIterator, name)
1662 class ProxyIterator(object):
1663 """Wrapper for a vtkSMProxyIterator class to satisfy the
1664 python iterator protocol.
1665 See the doxygen documentation of vtkSMProxyIterator C++ class for
1669 self.SMIterator = vtkSMProxyIterator()
1670 self.SMIterator.Begin()
1679 if self.SMIterator.IsAtEnd():
1685 self.AProxy = _getPyProxy(self.SMIterator.GetProxy())
1686 self.Group = self.SMIterator.GetGroup()
1687 self.Key = self.SMIterator.GetKey()
1688 self.SMIterator.Next()
1692 """Returns the proxy last returned by the call to 'next()'"""
1696 """Returns the key for the proxy last returned by the call to
1701 """Returns the group for the proxy last returned by the call to
1705 def __getattr__(self, name):
1706 """returns attributes from the vtkSMProxyIterator."""
1707 return getattr(self.SMIterator, name)
1709 class Connection(object):
1711 This is a python representation for a connection.
1713 def __init__(self, connectionId):
1714 """Default constructor. Creates a Connection with the given
1715 ID, all other data members initialized to None."""
1716 self.ID = connectionId
1717 self.Hostname = None
1719 self.RSHostname = None
1721 self.Reverse = False
1724 def __eq__(self, other):
1725 "Returns true if the connection ids are the same."
1726 return self.ID == other.ID
1728 def SetHost(self, ds_host=None, ds_port=None, rs_host=None, rs_port=None,
1731 Set the hostname of a given connection. Used by Connect().
1732 If all args are None, it's assumed to be a built-in connection i.e.
1733 connection scheme = builtin.
1735 self.Hostname = ds_host
1737 self.RSHostname = rs_host
1738 self.RSPort = rs_port
1739 self.Reversed = reverse
1743 """User friendly string representation"""
1744 if not self.Hostname:
1745 return "Connection (builtin[%d]:)" % self.ID
1746 if not self.RSHostname:
1747 return "Connection (%s:%d)" % (self.Hostname, self.Port)
1748 return "Connection data(%s:%d), render(%s:%d)" % \
1749 (self.Hostname, self.Port, self.RSHostname, self.RSPort)
1752 """Get URI of the connection"""
1753 if not self.Hostname or self.Hostname == "builtin":
1756 if not self.RSHostname:
1757 return "csrc://%s:%d" % (self.Hostname, self.Port)
1758 return "cdsrsrc://%s:%d//%s:%d" % (self.Hostname, self.Port,
1759 self.RSHostname, self.RSPort)
1760 if not self.RSHostname:
1761 return "cs://%s:%d" % (self.Hostname, self.Port)
1762 return "cdsrs://%s:%d//%s:%d" % (self.Hostname, self.Port,
1763 self.RSHostname, self.RSPort)
1766 """Returns True if the connection to a remote server, False if
1767 it is local (built-in)"""
1768 pm = vtkProcessModule.GetProcessModule()
1769 if pm.IsRemote(self.ID):
1773 def GetNumberOfDataPartitions(self):
1774 """Returns the number of partitions on the data server for this
1776 pm = vtkProcessModule.GetProcessModule()
1777 return pm.GetNumberOfPartitions(self.ID)
1780 ## These are methods to create a new connection.
1781 ## One can connect to a server, (data-server,render-server)
1782 ## or simply create a built-in connection.
1783 ## Note: these are internal methods. Use Connect() instead.
1784 def _connectServer(host, port, rc=False):
1785 """Connect to a host:port. Returns the connection object if successfully
1786 connected with the server. Internal method, use Connect() instead."""
1787 pm = vtkProcessModule.GetProcessModule()
1789 cid = pm.ConnectToRemote(host, port)
1792 conn = Connection(cid)
1794 pm.AcceptConnectionsOnPort(port)
1795 print "Waiting for connection..."
1797 cid = pm.MonitorConnections(10)
1799 conn = Connection(cid)
1801 pm.StopAcceptingAllConnections()
1802 conn.SetHost(host, port, None, None, rc)
1805 def _connectDsRs(ds_host, ds_port, rs_host, rs_port):
1806 """Connect to a dataserver at (ds_host:ds_port) and to a render server
1807 at (rs_host:rs_port).
1808 Returns the connection object if successfully connected
1809 with the server. Internal method, use Connect() instead."""
1810 pm = vtkProcessModule.GetProcessModule()
1811 cid = pm.ConnectToRemote(ds_host, ds_port, rs_host, rs_port)
1814 conn = Connection(cid)
1815 conn.SetHost(ds_host, ds_port, rs_host, rs_port)
1819 """Initialises self connection.Internal method, use Connect() instead."""
1820 print "Connect to self"
1821 pm = vtkProcessModule.GetProcessModule()
1822 pmOptions = pm.GetOptions()
1823 if pmOptions.GetProcessType() == 0x40: # PVBATCH
1824 return Connection(vtkProcessModuleConnectionManager.GetRootServerConnectionID())
1825 cid = pm.ConnectToSelf()
1828 conn = Connection(cid)
1829 conn.SetHost("builtin", cid)
1832 def SaveState(filename):
1833 """Given a state filename, saves the state of objects registered
1834 with the proxy manager."""
1836 pm.SaveState(filename)
1838 def LoadState(filename, connection=None):
1839 """Given a state filename and an optional connection, loads the server
1842 connection = ActiveConnection
1844 raise RuntimeError, "Cannot load state without a connection"
1845 loader = vtkSMPQStateLoader()
1847 pm.LoadState(filename, ActiveConnection.ID, loader)
1848 views = GetRenderViews()
1850 # Make sure that the client window size matches the
1851 # ViewSize property. In paraview, the GUI takes care
1853 if view.GetClassName() == "vtkSMIceTDesktopRenderViewProxy":
1854 view.GetRenderWindow().SetSize(view.ViewSize[0], \
1857 def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
1859 Use this function call to create a new connection. On success,
1860 it returns a Connection object that abstracts the connection.
1861 Otherwise, it returns None.
1862 There are several ways in which this function can be called:
1863 * When called with no arguments, it creates a new connection
1864 to the built-in server on the client itself.
1865 * When called with ds_host and ds_port arguments, it
1866 attempts to connect to a server(data and render server on the same server)
1867 on the indicated host:port.
1868 * When called with ds_host, ds_port, rs_host, rs_port, it
1869 creates a new connection to the data server on ds_host:ds_port and to the
1870 render server on rs_host: rs_port.
1872 global ActiveConnection
1875 raise RuntimeError, "Cannot create a connection through python. Use the GUI to setup the connection."
1877 connectionId = _connectSelf()
1878 elif rs_host == None:
1879 connectionId = _connectServer(ds_host, ds_port)
1881 connectionId = _connectDsRs(ds_host, ds_port, rs_host, rs_port)
1882 if not ActiveConnection:
1883 ActiveConnection = connectionId
1886 def ReverseConnect(port=11111):
1888 Use this function call to create a new connection. On success,
1889 it returns a Connection object that abstracts the connection.
1890 Otherwise, it returns None.
1891 In reverse connection mode, the client waits for a connection
1892 from the server (client has to be started first). The server
1893 then connects to the client (run pvserver with -rc and -ch
1895 The optional port specified the port to listen to.
1897 global ActiveConnection
1900 raise RuntimeError, "Cannot create a connection through python. Use the GUI to setup the connection."
1901 connectionId = _connectServer("Reverse connection", port, True)
1902 if not ActiveConnection:
1903 ActiveConnection = connectionId
1906 def Disconnect(connection=None):
1907 """Disconnects the connection. Make sure to clear the proxy manager
1909 global ActiveConnection
1912 raise RuntimeError, "Cannot disconnect through python. Use the GUI to disconnect."
1913 if not connection or connection == ActiveConnection:
1914 connection = ActiveConnection
1915 ActiveConnection = None
1917 pm = vtkProcessModule.GetProcessModule()
1918 pm.Disconnect(connection.ID)
1921 def CreateProxy(xml_group, xml_name, connection=None):
1922 """Creates a proxy. If connection is set, the proxy's connection ID is
1923 set accordingly. If connection is None, ActiveConnection is used, if
1924 present. You should not have to use method normally. Instantiate the
1925 appropriate class from the appropriate module, for example:
1926 sph = servermanager.sources.SphereSource()"""
1928 pxm = ProxyManager()
1929 aProxy = pxm.NewProxy(xml_group, xml_name)
1933 connection = ActiveConnection
1935 aProxy.SetConnectionID(connection.ID)
1938 def GetRenderView(connection=None):
1939 """Return the render view in use. If more than one render view is in
1940 use, return the first one."""
1943 connection = ActiveConnection
1944 render_module = None
1945 for aProxy in ProxyManager().NewConnectionIterator(connection):
1946 if aProxy.IsA("vtkSMRenderViewProxy"):
1947 render_module = aProxy
1949 return render_module
1951 def GetRenderViews(connection=None):
1952 """Returns the set of all render views."""
1955 connection = ActiveConnection
1957 for aProxy in ProxyManager().NewConnectionIterator(connection):
1958 if aProxy.IsA("vtkSMRenderViewProxy"):
1959 render_modules.append(aProxy)
1960 return render_modules
1962 def CreateRenderView(connection=None, **extraArgs):
1963 """Creates a render window on the particular connection. If connection
1964 is not specified, then the active connection is used, if available.
1966 This method can also be used to initialize properties by passing
1967 keyword arguments where the key is the name of the property.In addition
1968 registrationGroup and registrationName (optional) can be specified (as
1969 keyword arguments) to automatically register the proxy with the proxy
1973 connection = ActiveConnection
1975 raise RuntimeError, "Cannot create render window without connection."
1976 pxm = ProxyManager()
1977 prototype = pxm.GetPrototypeProxy("views", "RenderView")
1979 proxy_xml_name = prototype.GetSuggestedViewType(connection.ID)
1982 ren_module = CreateProxy("views", proxy_xml_name, connection)
1985 extraArgs['proxy'] = ren_module
1986 proxy = rendering.__dict__[ren_module.GetXMLName()](**extraArgs)
1989 def GetRepresentation(aProxy, view):
1990 for rep in view.Representations:
1992 try: isRep = rep.Input.IsSame(aProxy)
1993 except: isRep = False
1994 if isRep: return rep
1997 def CreateRepresentation(aProxy, view, **extraArgs):
1998 """Creates a representation for the proxy and adds it to the render
2001 This method can also be used to initialize properties by passing
2002 keyword arguments where the key is the name of the property.In addition
2003 registrationGroup and registrationName (optional) can be specified (as
2004 keyword arguments) to automatically register the proxy with the proxy
2007 This method tries to create the best possible representation for the given
2008 proxy in the given view. Additionally, the user can specify proxyName
2009 (optional) to create a representation of a particular type."""
2013 raise RuntimeError, "proxy argument cannot be None."
2015 raise RuntimeError, "render module argument cannot be None."
2016 if "proxyName" in extraArgs:
2017 display = CreateProxy("representations", extraArgs['proxyName'], None)
2018 del extraArgs['proxyName']
2020 display = view.SMProxy.CreateDefaultRepresentation(aProxy.SMProxy, 0)
2022 display.UnRegister(None)
2025 display.SetConnectionID(aProxy.GetConnectionID())
2026 extraArgs['proxy'] = display
2027 proxy = rendering.__dict__[display.GetXMLName()](**extraArgs)
2028 proxy.Input = aProxy
2029 proxy.UpdateVTKObjects()
2030 view.Representations.append(proxy)
2033 class _ModuleLoader(object):
2034 def find_module(self, fullname, path=None):
2035 if vtkPVPythonModule.HasModule(fullname):
2039 def load_module(self, fullname):
2041 moduleInfo = vtkPVPythonModule.GetModule(fullname)
2044 module = sys.modules.setdefault(fullname, imp.new_module(fullname))
2045 module.__file__ = "<%s>" % moduleInfo.GetFullName()
2046 module.__loader__ = self
2047 if moduleInfo.GetIsPackage:
2048 module.__path__ = moduleInfo.GetFullName()
2049 code = compile(moduleInfo.GetSource(), module.__file__, 'exec')
2050 exec code in module.__dict__
2053 def LoadXML(xmlstring):
2054 """Given a server manager XML as a string, parse and process it."""
2055 parser = vtkSMXMLParser()
2056 if not parser.Parse(xmlstring):
2057 raise RuntimeError, "Problem parsing XML string."
2058 parser.ProcessConfiguration(vtkSMObject.GetProxyManager())
2059 # Update the modules
2062 def LoadPlugin(filename, remote=True, connection=None):
2063 """ Given a filename and a connection (optional, otherwise uses
2064 ActiveConnection), loads a plugin. It then updates the sources,
2065 filters and rendering modules."""
2068 connection = ActiveConnection
2070 raise RuntimeError, "Cannot load a plugin without a connection."
2073 plm=pxm.GetApplication().GetPluginManager()
2075 """ Load the plugin on server. """
2077 serverURI = connection.GetURI()
2079 serverURI = "builtin:"
2081 plinfo = plm.LoadPlugin(filename, connection.ID, serverURI, remote)
2083 if not plinfo or not plinfo.GetLoaded():
2084 # Assume that it is an xml file
2085 f = open(filename, 'r')
2088 except RuntimeError:
2089 raise RuntimeError, "Problem loading plugin %s: %s" % (filename, pld.GetProperty("Error").GetElement(0))
2094 def Fetch(input, arg1=None, arg2=None, idx=0):
2096 A convenience method that moves data from the server to the client,
2097 optionally performing some operation on the data as it moves.
2098 The input argument is the name of the (proxy for a) source or filter
2099 whose output is needed on the client.
2101 You can use Fetch to do three things:
2103 If arg1 is None (the default) then all of the data is brought to the client.
2104 In parallel runs an appropriate append Filter merges the
2105 data on each processor into one data object. The filter chosen will be
2106 vtkAppendPolyData for vtkPolyData, vtkAppendRectilinearGrid for
2107 vtkRectilinearGrid, vtkMultiBlockDataGroupFilter for vtkCompositeData,
2108 and vtkAppendFilter for anything else.
2110 If arg1 is an integer then one particular processor's output is brought to
2111 the client. In serial runs the arg is ignored. If you have a filter that
2112 computes results in parallel and brings them to the root node, then set
2115 If arg1 and arg2 are a algorithms, for example vtkMinMax, the algorithm
2116 will be applied to the data to obtain some result. Here arg1 will be
2117 applied pre-gather and arg2 will be applied post-gather. In parallel
2118 runs the algorithm will be run on each processor to make intermediate
2119 results and then again on the root processor over all of the
2120 intermediate results to create a global result.
2122 Optional argument idx is used to specify the output port number to fetch the
2123 data from. Default is port 0.
2128 #create the pipeline that reduces and transmits the data
2129 gvd = rendering.ClientDeliveryRepresentationBase()
2130 gvd.AddInput(0, input, idx, "DONTCARE")
2133 print "getting appended"
2135 cdinfo = input.GetDataInformation(idx).GetCompositeDataInformation()
2136 if cdinfo.GetDataIsComposite():
2137 print "use composite data append"
2138 gvd.SetReductionType(5)
2140 elif input.GetDataInformation(idx).GetDataClassName() == "vtkPolyData":
2141 print "use append poly data filter"
2142 gvd.SetReductionType(1)
2144 elif input.GetDataInformation(idx).GetDataClassName() == "vtkRectilinearGrid":
2145 print "use append rectilinear grid filter"
2146 gvd.SetReductionType(4)
2148 elif input.GetDataInformation(idx).IsA("vtkDataSet"):
2149 print "use unstructured append filter"
2150 gvd.SetReductionType(2)
2153 elif type(arg1) is types.IntType:
2154 print "getting node %d" % arg1
2155 gvd.SetReductionType(3)
2156 gvd.SetPreGatherHelper(None)
2157 gvd.SetPostGatherHelper(None)
2158 gvd.SetPassThrough(arg1)
2161 print "applying operation"
2162 gvd.SetReductionType(6) # CUSTOM
2163 gvd.SetPreGatherHelper(arg1)
2164 gvd.SetPostGatherHelper(arg2)
2165 gvd.SetPassThrough(-1)
2168 gvd.UpdateVTKObjects()
2170 op = gvd.GetOutput()
2171 opc = gvd.GetOutput().NewInstance()
2173 opc.UnRegister(None)
2176 def AnimateReader(reader, view, filename=None):
2177 """This is a utility function that, given a reader and a view
2178 animates over all time steps of the reader. If the optional
2179 filename is provided, a movie is created (type depends on the
2180 extension of the filename."""
2182 raise RuntimeError, "No reader was specified, cannot animate."
2184 raise RuntimeError, "No view was specified, cannot animate."
2185 # Create an animation scene
2186 scene = animation.AnimationScene()
2188 # We need to have the reader and the view registered with
2189 # the time keeper. This is how the scene gets its time values.
2191 tk = ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
2192 scene.TimeKeeper = tk
2194 tk = misc.TimeKeeper()
2195 scene.TimeKeeper = tk
2197 if not reader in tk.TimeSources:
2198 tk.TimeSources.append(reader)
2199 if not view in tk.Views:
2200 tk.Views.append(view)
2204 scene.ViewModules = [view]
2205 # Update the reader to get the time information
2206 reader.UpdatePipelineInformation()
2207 # Animate from 1st time step to last
2208 scene.StartTime = reader.TimestepValues.GetData()[0]
2209 scene.EndTime = reader.TimestepValues.GetData()[-1]
2211 # Each frame will correspond to a time step
2212 scene.PlayMode = 2 #Snap To Timesteps
2214 # Create a special animation cue for time.
2215 cue = animation.TimeAnimationCue()
2216 cue.AnimatedProxy = view
2217 cue.AnimatedPropertyName = "ViewTime"
2221 writer = vtkSMAnimationSceneImageWriter()
2222 writer.SetFileName(filename)
2223 writer.SetFrameRate(1)
2224 writer.SetAnimationScene(scene.SMProxy)
2226 # Now save the animation.
2227 if not writer.Save():
2228 raise RuntimeError, "Saving of animation failed!"
2233 def ToggleProgressPrinting():
2234 """Turn on/off printing of progress (by default, it is on). You can
2235 always turn progress off and add your own observer to the process
2236 module to handle progress in a custom way. See _printProgress for
2237 an example event observer."""
2239 #vsv global progressObserverTag
2242 #vsv raise RuntimeError, "Printing progress in the GUI is not supported."
2243 #vsv if progressObserverTag:
2244 #vsv vtkProcessModule.GetProcessModule().RemoveObserver(progressObserverTag)
2245 #vsv progressObserverTag = None
2246 #VSV Observer is not supported
2248 # progressObserverTag = vtkProcessModule.GetProcessModule().AddObserver("ProgressEvent", _printProgress)
2251 """Although not required, this can be called at exit to cleanup."""
2252 global progressObserverTag
2253 # Make sure to remove the observer
2254 if progressObserverTag:
2255 ToggleProgressPrinting()
2256 vtkInitializationHelper.Finalize()
2260 def _getPyProxy(smproxy, outputPort=0):
2261 """Returns a python wrapper for a server manager proxy. This method
2262 first checks if there is already such an object by looking in the
2263 _pyproxies group and returns it if found. Otherwise, it creates a
2264 new one. Proxies register themselves in _pyproxies upon creation."""
2267 if (smproxy, outputPort) in _pyproxies:
2268 return _pyproxies[(smproxy, outputPort)]()
2270 xmlName = smproxy.GetXMLName()
2271 if smproxy.GetXMLLabel():
2272 xmlName = smproxy.GetXMLLabel()
2273 classForProxy = _findClassForProxy(_make_name_valid(xmlName), smproxy.GetXMLGroup())
2275 retVal = classForProxy(proxy=smproxy, port=outputPort)
2277 retVal = Proxy(proxy=smproxy, port=outputPort)
2280 def _makeUpdateCameraMethod(rv):
2281 """ This internal method is used to create observer methods """
2282 if not hasattr(rv(), "BlockUpdateCamera"):
2283 rv().add_attribute("BlockUpdateCamera", False)
2284 def UpdateCamera(obj, string):
2285 if not rv().BlockUpdateCamera:
2286 # used to avoid some nasty recursion that occurs when interacting in
2288 rv().BlockUpdateCamera = True
2289 rv().SynchronizeCameraProperties()
2290 rv().BlockUpdateCamera = False
2293 def _createInitialize(group, name):
2294 """Internal method to create an Initialize() method for the sub-classes
2298 def aInitialize(self, connection=None):
2300 connection = ActiveConnection
2302 raise RuntimeError,\
2303 'Cannot create a proxy without a connection.'
2304 self.InitializeFromProxy(\
2305 CreateProxy(pgroup, pname, connection))
2308 def _createGetProperty(pName):
2309 """Internal method to create a GetXXX() method where XXX == pName."""
2311 def getProperty(self):
2312 return self.GetPropertyValue(propName)
2315 def _createSetProperty(pName):
2316 """Internal method to create a SetXXX() method where XXX == pName."""
2318 def setProperty(self, value):
2319 return self.SetPropertyWithName(propName, value)
2322 def _findClassForProxy(xmlName, xmlGroup):
2323 """Given the xmlName for a proxy, returns a Proxy class. Note
2324 that if there are duplicates, the first one is returned."""
2325 global sources, filters, rendering, animation, implicit_functions, writers, extended_sources, misc
2328 if xmlGroup == "sources":
2329 return sources.__dict__[xmlName]
2330 elif xmlGroup == "filters":
2331 return filters.__dict__[xmlName]
2332 elif xmlGroup == "implicit_functions":
2333 return implicit_functions.__dict__[xmlName]
2334 elif xmlGroup == "writers":
2335 return writers.__dict__[xmlName]
2336 elif xmlGroup == "extended_sources":
2337 return extended_sources.__dict__[xmlName]
2338 elif xmlName in rendering.__dict__:
2339 return rendering.__dict__[xmlName]
2340 elif xmlName in animation.__dict__:
2341 return animation.__dict__[xmlName]
2342 elif xmlName in misc.__dict__:
2343 return misc.__dict__[xmlName]
2347 def _printProgress(caller, event):
2348 """The default event handler for progress. Prints algorithm
2349 name and 1 '.' per 10% progress."""
2350 global currentAlgorithm, currentProgress
2352 pm = vtkProcessModule.GetProcessModule()
2353 progress = pm.GetLastProgress() / 10
2354 # If we got a 100% as the first thing, ignore
2355 # This is to get around the fact that some vtk
2356 # algorithms report 100% more than once (which is
2358 if not currentAlgorithm and progress == 10:
2360 alg = pm.GetLastProgressName()
2361 if alg != currentAlgorithm and alg:
2362 if currentAlgorithm:
2363 while currentProgress <= 10:
2365 sys.stdout.write(".")
2366 currentProgress += 1
2370 currentAlgorithm = alg
2371 while currentProgress <= progress:
2373 sys.stdout.write(".")
2374 #sys.stdout.write("%d " % pm.GetLastProgress())
2375 currentProgress += 1
2378 currentAlgorithm = None
2381 def updateModules():
2382 """Called when a plugin is loaded, this method updates
2383 the proxy class object in all known modules."""
2384 global sources, filters, writers, rendering, animation, implicit_functions, extended_sources, misc
2386 createModule("sources", sources)
2387 createModule("filters", filters)
2388 createModule("writers", writers)
2389 createModule("representations", rendering)
2390 createModule("views", rendering)
2391 createModule("lookup_tables", rendering)
2392 createModule("textures", rendering)
2393 createModule("animation", animation)
2394 createModule("misc", misc)
2395 createModule('animation_keyframes', animation)
2396 createModule('implicit_functions', implicit_functions)
2397 createModule("extended_sources", extended_sources)
2399 def _createModules():
2400 """Called when the module is loaded, this creates sub-
2401 modules for all know proxy groups."""
2402 global sources, filters, writers, rendering, animation, implicit_functions, extended_sources, misc
2404 sources = createModule('sources')
2405 filters = createModule('filters')
2406 writers = createModule('writers')
2407 rendering = createModule('representations')
2408 createModule('views', rendering)
2409 createModule("lookup_tables", rendering)
2410 createModule("textures", rendering)
2411 animation = createModule('animation')
2412 createModule('animation_keyframes', animation)
2413 implicit_functions = createModule('implicit_functions')
2414 extended_sources = createModule("extended_sources")
2415 misc = createModule("misc")
2417 class PVModule(object):
2420 def _make_name_valid(name):
2421 "Make a string into a valid Python variable name"
2424 if name.find('(') >= 0 or name.find(')') >=0:
2426 name = name.replace(' ','')
2427 name = name.replace('-','')
2428 name = name.replace(':','')
2429 name = name.replace('.','')
2430 if not name[0].isalpha():
2434 def createModule(groupName, mdl=None):
2435 """Populates a module with proxy classes defined in the given group.
2436 If mdl is not specified, it also creates the module"""
2438 pxm = vtkSMObject.GetProxyManager()
2439 # Use prototypes to find all proxy types.
2440 pxm.InstantiateGroupPrototypes(groupName)
2446 numProxies = pxm.GetNumberOfXMLProxies(groupName)
2447 for i in range(numProxies):
2448 proxyName = pxm.GetXMLProxyName(groupName, i)
2449 proto = pxm.GetPrototypeProxy(groupName, proxyName)
2450 if proto.GetXMLLabel():
2451 pname = proto.GetXMLLabel()
2452 pname = _make_name_valid(pname)
2455 if pname in mdl.__dict__:
2457 print "Warning: %s is being overwritten. This may point to an issue in the ParaView configuration files" % pname
2459 # Create an Initialize() method for this sub-class.
2460 cdict['Initialize'] = _createInitialize(groupName, proxyName)
2461 iter = PropertyIterator(proto)
2462 # Add all properties as python properties.
2464 propName = iter.GetKey()
2465 if (prop.GetInformationOnly() and propName != "TimestepValues" ) or prop.GetIsInternal():
2468 names = [iter.PropertyLabel]
2471 if prop.GetDocumentation():
2472 propDoc = prop.GetDocumentation().GetDescription()
2474 name = _make_name_valid(name)
2476 cdict[name] = property(_createGetProperty(propName),
2477 _createSetProperty(propName),
2480 # Add the documentation as the class __doc__
2481 if proto.GetDocumentation() and proto.GetDocumentation().GetDescription():
2482 doc = proto.GetDocumentation().GetDescription()
2485 cdict['__doc__'] = doc
2486 # Create the new type
2487 if proto.GetXMLName() == "ExodusIIReader":
2488 superclasses = (ExodusIIReaderProxy,)
2489 elif proto.IsA("vtkSMSourceProxy"):
2490 superclasses = (SourceProxy,)
2492 superclasses = (Proxy,)
2494 cobj = type(pname, superclasses, cdict)
2495 # Add it to the modules dictionary
2496 mdl.__dict__[pname] = cobj
2500 def __determineGroup(proxy):
2501 """Internal method"""
2504 xmlgroup = proxy.GetXMLGroup()
2505 xmlname = proxy.GetXMLName()
2506 if xmlgroup == "sources":
2508 elif xmlgroup == "filters":
2510 elif xmlgroup == "views":
2512 elif xmlgroup == "representations":
2513 if xmlname == "ScalarBarWidgetRepresentation":
2514 return "scalar_bars"
2515 return "representations"
2516 elif xmlgroup == "lookup_tables":
2517 return "lookup_tables"
2518 elif xmlgroup == "implicit_functions":
2519 return "implicit_functions"
2523 def __determineName(proxy, group):
2524 global __nameCounter
2525 name = _make_name_valid(proxy.GetXMLLabel())
2528 if not __nameCounter.has_key(name):
2529 __nameCounter[name] = 1
2532 __nameCounter[name] += 1
2533 val = __nameCounter[name]
2534 return "%s%d" % (name, val)
2536 def __getName(proxy, group):
2537 pxm = ProxyManager()
2538 if isinstance(proxy, Proxy):
2539 proxy = proxy.SMProxy
2540 return pxm.GetProxyName(group, proxy)
2542 class MissingRegistrationInformation(Exception):
2543 """Exception for missing registration information. Raised when a name or group
2544 is not specified or when a group cannot be deduced."""
2547 def Register(proxy, **extraArgs):
2548 """Registers a proxy with the proxy manager. If no 'registrationGroup' is
2549 specified, then the group is inferred from the type of the proxy.
2550 'registrationName' may be specified to register with a particular name
2551 otherwise a default name will be created."""
2552 # TODO: handle duplicate registration
2553 if "registrationGroup" in extraArgs:
2554 registrationGroup = extraArgs["registrationGroup"]
2556 registrationGroup = __determineGroup(proxy)
2558 if "registrationName" in extraArgs:
2559 registrationName = extraArgs["registrationName"]
2561 registrationName = __determineName(proxy, registrationGroup)
2562 if registrationGroup and registrationName:
2563 pxm = ProxyManager()
2564 pxm.RegisterProxy(registrationGroup, registrationName, proxy)
2566 raise MissingRegistrationInformation, "Registration error %s %s." % (registrationGroup, registrationName)
2567 return (registrationGroup, registrationName)
2569 def UnRegister(proxy, **extraArgs):
2570 """UnRegisters proxies registered using Register()."""
2571 if "registrationGroup" in extraArgs:
2572 registrationGroup = extraArgs["registrationGroup"]
2574 registrationGroup = __determineGroup(proxy)
2576 if "registrationName" in extraArgs:
2577 registrationName = extraArgs["registrationName"]
2579 registrationName = __getName(proxy, registrationGroup)
2581 if registrationGroup and registrationName:
2582 pxm = ProxyManager()
2583 pxm.UnRegisterProxy(registrationGroup, registrationName, proxy)
2585 raise RuntimeError, "UnRegistration error."
2586 return (registrationGroup, registrationName)
2589 """This simple demonstration creates a sphere, renders it and delivers
2590 it to the client using Fetch. It returns a tuple of (data, render
2592 if not ActiveConnection:
2594 ss = sources.Sphere(Radius=2, ThetaResolution=32)
2595 shr = filters.Shrink(Input=OutputPort(ss,0))
2597 app = filters.AppendDatasets()
2598 app.Input = [shr, cs]
2599 rv = CreateRenderView()
2600 rep = CreateRepresentation(app, rv)
2607 def demo2(fname="/Users/berk/Work/ParaViewData/Data/disk_out_ref.ex2"):
2608 """This method demonstrates the user of a reader, representation and
2609 view. It also demonstrates how meta-data can be obtained using proxies.
2610 Make sure to pass the full path to an exodus file. Also note that certain
2611 parameters are hard-coded for disk_out_ref.ex2 which can be found
2612 in ParaViewData. This method returns the render view."""
2613 if not ActiveConnection:
2615 # Create the exodus reader and specify a file name
2616 reader = sources.ExodusIIReader(FileName=fname)
2617 # Get the list of point arrays.
2618 arraySelection = reader.PointVariables
2619 print arraySelection.Available
2621 arraySelection.SetData(arraySelection.Available)
2623 # Next create a default render view appropriate for the connection type.
2624 rv = CreateRenderView()
2625 # Create the matching representation
2626 rep = CreateRepresentation(reader, rv)
2627 rep.Representation = 1 # Wireframe
2628 # Black background is not pretty
2629 rv.Background = [0.4, 0.4, 0.6]
2631 # Reset the camera to include the whole thing
2634 # Change the elevation of the camera. See VTK documentation of vtkCamera
2635 # for camera parameters.
2636 c = rv.GetActiveCamera()
2639 # Now that the reader execute, let's get some information about it's
2641 pdi = reader[0].PointData
2642 # This prints a list of all read point data arrays as well as their
2644 print 'Number of point arrays:', len(pdi)
2645 for i in range(len(pdi)):
2647 print "----------------"
2648 print "Array:", i, ai.Name, ":"
2649 numComps = ai.GetNumberOfComponents()
2650 print "Number of components:", numComps
2651 for j in range(numComps):
2652 print "Range:", ai.GetRange(j)
2653 # White is boring. Let's color the geometry using a variable.
2654 # First create a lookup table. This object controls how scalar
2655 # values are mapped to colors. See VTK documentation for
2657 lt = rendering.PVLookupTable()
2658 # Assign it to the representation
2659 rep.LookupTable = lt
2660 # Color by point array called Pres
2661 rep.ColorAttributeType = 0 # point data
2662 rep.ColorArrayName = "Pres"
2663 # Add to RGB points. These are tuples of 4 values. First one is
2664 # the scalar values, the other 3 the RGB values. This list has
2665 # 2 points: Pres: 0.00678, color: blue, Pres: 0.0288, color: red
2666 lt.RGBPoints = [0.00678, 0, 0, 1, 0.0288, 1, 0, 0]
2667 lt.ColorSpace = 1 # HSV
2672 """This method demonstrates the use of servermanager with numpy as
2673 well as pylab for plotting. It creates an artificial data sources,
2674 probes it with a line, delivers the result to the client using Fetch
2675 and plots it using pylab. This demo requires numpy and pylab installed.
2676 It returns a tuple of (data, render view)."""
2677 import paraview.numpy_support
2680 if not ActiveConnection:
2682 # Create a synthetic data source
2683 source = sources.Wavelet()
2684 # Let's get some information about the data. First, for the
2686 source.UpdatePipeline()
2688 di = source.GetDataInformation()
2689 print "Data type:", di.GetPrettyDataTypeString()
2690 print "Extent:", di.GetExtent()
2691 print "Array name:", \
2692 source[0].PointData[0].Name
2694 rv = CreateRenderView()
2696 rep1 = CreateRepresentation(source, rv)
2697 rep1.Representation = 3 # outline
2699 # Let's apply a contour filter
2700 cf = filters.Contour(Input=source, ContourValues=[200])
2702 # Select the array to contour by
2703 #cf.SelectInputScalars = 'RTData'
2705 rep2 = CreateRepresentation(cf, rv)
2707 rv.Background = (0.4, 0.4, 0.6)
2708 # Reset the camera to include the whole thing
2713 # Now, let's probe the data
2714 probe = filters.ResampleWithDataset(Input=source)
2716 line = sources.Line(Resolution=60)
2717 # that spans the dataset
2718 bounds = di.GetBounds()
2719 print "Bounds: ", bounds
2720 line.Point1 = bounds[0:6:2]
2721 line.Point2 = bounds[1:6:2]
2725 # Render with the line
2726 rep3 = CreateRepresentation(line, rv)
2729 # Now deliver it to the client. Remember, this is for small data.
2731 # Convert it to a numpy array
2732 data = paraview.numpy_support.vtk_to_numpy(
2733 data.GetPointData().GetArray("RTData"))
2734 # Plot it using matplotlib
2738 return (data, rv, probe)
2740 def demo4(fname="/Users/berk/Work/ParaViewData/Data/can.ex2"):
2741 """This method demonstrates the user of AnimateReader for
2742 creating animations."""
2743 if not ActiveConnection:
2745 reader = sources.ExodusIIReader(FileName=fname)
2746 view = CreateRenderView()
2747 repr = CreateRepresentation(reader, view)
2751 c = view.GetActiveCamera()
2753 return AnimateReader(reader, view)
2757 """ Simple sphere animation"""
2758 if not ActiveConnection:
2760 sphere = sources.Sphere()
2761 view = CreateRenderView()
2762 repr = CreateRepresentation(sphere, view)
2768 # Create an animation scene
2769 scene = animation.AnimationScene()
2771 scene.ViewModules = [view]
2773 # Create a cue to animate the StartTheta property
2774 cue = animation.KeyFrameAnimationCue()
2775 cue.AnimatedProxy = sphere
2776 cue.AnimatedPropertyName = "StartTheta"
2777 # Add it to the scene's cues
2780 # Create 2 keyframes for the StartTheta track
2781 keyf0 = animation.CompositeKeyFrame()
2782 keyf0.Type = 2 # Set keyframe interpolation type to Ramp.
2783 # At time = 0, value = 0
2785 keyf0.KeyValues= [0]
2787 keyf1 = animation.CompositeKeyFrame()
2788 # At time = 1.0, value = 200
2790 keyf1.KeyValues= [200]
2793 cue.KeyFrames = [keyf0, keyf1]
2798 ASSOCIATIONS = { 'POINTS' : 0, 'CELLS' : 1, 'VERTICES' : 4, 'EDGES' : 5, 'ROWS' : 6}
2800 # Users can set the active connection which will be used by API
2801 # to create proxies etc when no connection argument is passed.
2802 # Connect() automatically sets this if it is not already set.
2803 ActiveConnection = None
2805 # Needs to be called when paraview module is loaded from python instead
2806 # of pvpython, pvbatch or GUI.
2807 if not vtkSMObject.GetProxyManager():
2808 vtkInitializationHelper.Initialize(sys.executable)
2810 # Initialize progress printing. Can be turned off by calling
2811 # ToggleProgressPrinting() again.
2812 progressObserverTag = None
2813 currentAlgorithm = False
2816 ToggleProgressPrinting()
2820 # Create needed sub-modules
2823 # Set up our custom importer (if possible)
2824 loader = _ModuleLoader()
2825 sys.meta_path.append(loader)
2827 # Definitions for working in SALOME GUI mode
2828 aParams = myParavis.GetConnectionParameters()
2829 ActiveConnection = Connection(aParams[0])
2830 ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5])
2831 ToggleProgressPrinting()
2834 print vtkSMProxyManager.GetParaViewSourceVersion();