#
IF(SALOME_PARAVIS_MINIMAL_CORBA)
- # Use another set of Python files
- SET(_PYFILES_TO_INSTALL)
- MESSAGE(WARNING "New Python scripts not impl !!!")
-ELSE()
+ # Use another set of Python files redirecting the API directly
+ # to the original ParaView modules.
SET(_PYFILES_TO_INSTALL
paravis.py
- paravisSM.py
pvsimple.py
presentations.py
+ paravisSM.py
+ )
+ELSE()
+ SET(_PYFILES_TO_INSTALL
+ VTKWrapping/paravis.py
+ VTKWrapping/paravisSM.py
+ VTKWrapping/pvsimple.py
+ VTKWrapping/presentations.py
)
ENDIF()
--- /dev/null
+# Copyright (C) 2010-2013 CEA/DEN, EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# File : paravis.py
+# Module : PARAVIS
+#
+
+import os, new
+
+import PARAVIS
+import SALOME
+import SALOME_Session_idl
+import SALOMEDS
+import SALOME_ModuleCatalog
+from omniORB import CORBA
+from time import sleep
+from salome import *
+
+myORB = None
+myNamingService = None
+myLifeCycleCORBA = None
+myNamingService = None
+myLocalStudyManager = None
+myLocalStudy = None
+myLocalParavis = None
+myDelay = None
+mySession = None
+
+## Initialization of paravis server
+def Initialize(theORB, theNamingService, theLifeCycleCORBA, theStudyManager, theStudy, theDelay) :
+ global myORB, myNamingService, myLifeCycleCORBA, myLocalStudyManager, myLocalStudy
+ global mySession, myDelay
+ myDelay = theDelay
+ myORB = theORB
+ myNamingService = theNamingService
+ myLifeCycleCORBA = theLifeCycleCORBA
+ myLocalStudyManager = theStudyManager
+ while mySession == None:
+ mySession = myNamingService.Resolve("/Kernel/Session")
+ mySession = mySession._narrow(SALOME.Session)
+ mySession.GetInterface()
+ myDelay = theDelay
+ sleep(myDelay)
+ myLocalParavis = myLifeCycleCORBA.FindOrLoadComponent("FactoryServer", "PARAVIS")
+ myLocalStudy = theStudy
+ myLocalParavis.SetCurrentStudy(myLocalStudy)
+ myLocalParavis.ActivateModule()
+ return myLocalParavis
+
+
+def ImportFile(theFileName):
+ "Import a file of any format supported by ParaView"
+ myParavis.ImportFile(theFileName)
+
+
+def createFunction(theName):
+ "Create function - constructor of Paravis object"
+ def MyFunction():
+ return myParavis.CreateClass(theName)
+ return MyFunction
+
+
+def createConstructors():
+ "Create constructor functions according to list of extracted classes"
+ g = globals()
+ aClassNames = myParavis.GetClassesList();
+ for aName in aClassNames:
+ g[aName] = createFunction(aName)
+
+## Initialize of a PARAVIS interface
+myParavis = Initialize(orb, naming_service,lcc,myStudyManager,myStudy, 2)
+
+## Initialize constructor functions
+createConstructors()
+
+## Initialize Paravis static objects
+vtkSMObject = vtkSMObject()
+vtkProcessModule = vtkProcessModule()
+vtkPVPythonModule = vtkPVPythonModule()
+vtkSMProxyManager = vtkSMProxyManager()
+
+
--- /dev/null
+# Copyright (C) 2010-2013 CEA/DEN, EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+r"""servermanager is a module for using paraview server manager in Python.
+One can always use the server manager API directly. However, this module
+provides an interface easier to use from Python by wrapping several VTK
+classes around Python classes.
+
+Note that, upon load, this module will create several sub-modules: sources,
+filters and rendering. These modules can be used to instantiate specific
+proxy types. For a list, try "dir(servermanager.sources)"
+
+A simple example:
+ from paraview.servermanager import *
+
+ # Creates a new built-in session and makes it the active session.
+ Connect()
+
+ # Creates a new render view on the active session.
+ renModule = CreateRenderView()
+
+ # Create a new sphere proxy on the active session and register it
+ # in the sources group.
+ sphere = sources.SphereSource(registrationGroup="sources", ThetaResolution=16, PhiResolution=32)
+
+ # Create a representation for the sphere proxy and adds it to the render
+ # module.
+ display = CreateRepresentation(sphere, renModule)
+
+ renModule.StillRender()
+"""
+
+
+
+import re, os, new, sys
+from paravis import *
+
+# VTN: Avoid paraview.* instructions in this file.
+# It leads to problems during execution.
+
+def _wrap_property(proxy, smproperty):
+ """ Internal function.
+ Given a server manager property and its domains, returns the
+ appropriate python object.
+ """
+ property = None
+ if smproperty.IsA("vtkSMStringVectorProperty"):
+ al = smproperty.GetDomain("array_list")
+ if al and al.IsA("vtkSMArraySelectionDomain") and \
+ smproperty.GetRepeatable():
+ property = ArrayListProperty(proxy, smproperty)
+ elif al and al.IsA("vtkSMArrayListDomain") and smproperty.GetNumberOfElements() == 5:
+ property = ArraySelectionProperty(proxy, smproperty)
+ else:
+ iter = smproperty.NewDomainIterator()
+ isFileName = False
+ while not iter.IsAtEnd():
+ # Refer to BUG #9710 to see why optional domains need to be
+ # ignored.
+ if iter.GetDomain().IsA("vtkSMFileListDomain") and \
+ iter.GetDomain().GetIsOptional() == 0 :
+ isFileName = True
+ break
+ iter.Next()
+ iter.UnRegister(None)
+ if isFileName:
+ property = FileNameProperty(proxy, smproperty)
+ elif _make_name_valid(smproperty.GetXMLLabel()) == 'ColorArrayName':
+ property = ColorArrayProperty(proxy, smproperty)
+ else:
+ property = VectorProperty(proxy, smproperty)
+ elif smproperty.IsA("vtkSMVectorProperty"):
+ if smproperty.IsA("vtkSMIntVectorProperty") and \
+ smproperty.GetDomain("enum"):
+ property = EnumerationProperty(proxy, smproperty)
+ else:
+ property = VectorProperty(proxy, smproperty)
+ elif smproperty.IsA("vtkSMInputProperty"):
+ property = InputProperty(proxy, smproperty)
+ elif smproperty.IsA("vtkSMProxyProperty"):
+ property = ProxyProperty(proxy, smproperty)
+ else:
+ property = Property(proxy, smproperty)
+ return property
+
+class Proxy(object):
+ """Proxy for a server side object. A proxy manages the lifetime of
+ one or more server manager objects. It also provides an interface
+ to set and get the properties of the server side objects. These
+ properties are presented as Python properties. For example,
+ you can set a property Foo using the following:
+ proxy.Foo = (1,2)
+ or
+ proxy.Foo.SetData((1,2))
+ or
+ proxy.Foo[0:2] = (1,2)
+ For more information, see the documentation of the property which
+ you can obtain with
+ help(proxy.Foo).
+
+ This class also provides an iterator which can be used to iterate
+ over all properties.
+ eg:
+ proxy = Proxy(proxy=smproxy)
+ for property in proxy:
+ print property
+
+ For advanced users:
+ This is a python class that wraps a vtkSMProxy.. Makes it easier to
+ set/get properties.
+ Instead of:
+ proxy.GetProperty("Foo").SetElement(0, 1)
+ proxy.GetProperty("Foo").SetElement(0, 2)
+ you can do:
+ proxy.Foo = (1,2)
+ or
+ proxy.Foo.SetData((1,2))
+ or
+ proxy.Foo[0:2] = (1,2)
+ Instead of:
+ proxy.GetProperty("Foo").GetElement(0)
+ you can do:
+ proxy.Foo.GetData()[0]
+ or
+ proxy.Foo[0]
+ For proxy properties, you can use append:
+ proxy.GetProperty("Bar").AddProxy(foo)
+ you can do:
+ proxy.Bar.append(foo)
+ Properties support most of the list API. See VectorProperty and
+ ProxyProperty documentation for details.
+
+ Please note that some of the methods accessible through the Proxy
+ class are not listed by help() because the Proxy objects forward
+ unresolved attributes to the underlying object. To get the full list,
+ see also dir(proxy.SMProxy). See also the doxygen based documentation
+ of the vtkSMProxy C++ class.
+ """
+
+ def __init__(self, **args):
+ """ Default constructor. It can be used to initialize properties
+ by passing keyword arguments where the key is the name of the
+ property. In addition registrationGroup and registrationName (optional)
+ can be specified (as keyword arguments) to automatically register
+ the proxy with the proxy manager. """
+ self.add_attribute('Observed', None)
+ self.add_attribute('ObserverTag', -1)
+ self.add_attribute('_Proxy__Properties', {})
+ self.add_attribute('_Proxy__LastAttrName', None)
+ self.add_attribute('SMProxy', None)
+ self.add_attribute('Port', 0)
+
+ if 'port' in args:
+ self.Port = args['port']
+ del args['port']
+
+ update = True
+ if 'no_update' in args:
+ if args['no_update']:
+ update = False
+ del args['no_update']
+
+ if 'proxy' in args:
+ self.InitializeFromProxy(args['proxy'])
+ del args['proxy']
+ else:
+ self.Initialize(None, update)
+ if 'registrationGroup' in args:
+ registrationGroup = args['registrationGroup']
+ del args['registrationGroup']
+ registrationName = self.SMProxy.GetGlobalIDAsString()
+ if 'registrationName' in args:
+ registrationName = args['registrationName']
+ del args['registrationName']
+ pxm = ProxyManager()
+ pxm.RegisterProxy(registrationGroup, registrationName, self.SMProxy)
+ if update:
+ self.UpdateVTKObjects()
+ for key in args.keys():
+ setattr(self, key, args[key])
+ # Visit all properties so that they are created
+ for prop in self:
+ pass
+
+ def __setattr__(self, name, value):
+ try:
+ setter = getattr(self.__class__, name)
+ setter = setter.__set__
+ except AttributeError:
+ if not hasattr(self, name):
+ raise AttributeError("Attribute %s does not exist. " % name +
+ " This class does not allow addition of new attributes to avoid " +
+ "mistakes due to typos. Use add_attribute() if you really want " +
+ "to add this attribute.")
+ self.__dict__[name] = value
+ else:
+ setter(self, value)
+
+ def add_attribute(self, name, value):
+ self.__dict__[name] = value
+
+ def __del__(self):
+ """Destructor. Cleans up all observers as well as remove
+ the proxy from the _pyproxies dictionary"""
+ # Make sure that we remove observers we added
+ if self.Observed:
+ observed = self.Observed
+ tag = self.ObserverTag
+ self.Observed = None
+ self.ObserverTag = -1
+ observed.RemoveObserver(tag)
+ if _pyproxies and self.SMProxy and (self.SMProxy, self.Port) in _pyproxies:
+ del _pyproxies[(self.SMProxy, self.Port)]
+
+ def InitializeFromProxy(self, aProxy, update=True):
+ """Constructor. Assigns proxy to self.SMProxy, updates the server
+ object as well as register the proxy in _pyproxies dictionary."""
+ import weakref
+ self.SMProxy = aProxy
+ if update:
+ self.SMProxy.UpdateVTKObjects()
+ _pyproxies[(self.SMProxy, self.Port)] = weakref.ref(self)
+
+ def Initialize(self):
+ "Overridden by the subclass created automatically"
+ pass
+
+ def __eq__(self, other):
+ "Returns true if the underlying SMProxies are the same."
+ if isinstance(other, Proxy):
+ try:
+ if self.Port != other.Port:
+ return False
+ except:
+ pass
+ ## VSV using IsSame instead ==
+ return self.SMProxy.IsSame(other.SMProxy)
+ return self.SMProxy.IsSame(other)
+
+ def __ne__(self, other):
+ "Returns false if the underlying SMProxies are the same."
+ return not self.__eq__(other)
+
+ def __iter__(self):
+ "Creates an iterator for the properties."
+ return PropertyIterator(self)
+
+ def SetPropertyWithName(self, pname, arg):
+ """Generic method for setting the value of a property."""
+ prop = self.GetProperty(pname)
+ if prop is None:
+ raise RuntimeError, "Property %s does not exist. Please check the property name for typos." % pname
+ prop.SetData(arg)
+
+ def GetPropertyValue(self, name):
+ """Returns a scalar for properties with 1 elements, the property
+ itself for vectors."""
+ p = self.GetProperty(name)
+ if isinstance(p, VectorProperty):
+ if p.GetNumberOfElements() == 1 and not p.GetRepeatable():
+ if p.SMProperty.IsA("vtkSMStringVectorProperty") or not p.GetArgumentIsArray():
+ return p[0]
+ elif isinstance(p, InputProperty):
+ if not p.GetMultipleInput():
+ if len(p) > 0:
+ return p[0]
+ else:
+ return None
+ elif isinstance(p, ProxyProperty):
+ if not p.GetRepeatable():
+ if len(p) > 0:
+ return p[0]
+ else:
+ return None
+ return p
+
+ def GetProperty(self, name):
+ """Given a property name, returns the property object."""
+ if name in self.__Properties and self.__Properties[name]():
+ return self.__Properties[name]()
+ smproperty = self.SMProxy.GetProperty(name)
+ # Maybe they are looking by the label. Try to match that.
+ if not smproperty:
+ iter = PropertyIterator(self)
+ for prop in iter:
+ if name == _make_name_valid(iter.PropertyLabel):
+ smproperty = prop.SMProperty
+ break
+ if smproperty:
+ property = _wrap_property(self, smproperty)
+ if property is not None:
+ import weakref
+ self.__Properties[name] = weakref.ref(property)
+ return property
+ return None
+
+ def ListProperties(self):
+ """Returns a list of all property names on this proxy."""
+ property_list = []
+ iter = self.__iter__()
+ for property in iter:
+ name = _make_name_valid(iter.PropertyLabel)
+ if name:
+ property_list.append(name)
+ return property_list
+
+ def __ConvertArgumentsAndCall(self, *args):
+ """ Internal function.
+ Used to call a function on SMProxy. Converts input and
+ output values as appropriate.
+ """
+ newArgs = []
+ for arg in args:
+ if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
+ newArgs.append(arg.SMProxy)
+ else:
+ newArgs.append(arg)
+ func = getattr(self.SMProxy, self.__LastAttrName)
+ retVal = func(*newArgs)
+ if type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProxy"):
+ return _getPyProxy(retVal)
+ elif type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProperty"):
+ return _wrap_property(self, retVal)
+ else:
+ return retVal
+
+ def __GetActiveCamera(self):
+ """ This method handles GetActiveCamera specially. It adds
+ an observer to the camera such that everytime it is modified
+ the render view updated"""
+ import weakref
+ c = self.SMProxy.GetActiveCamera()
+ # VSV: Observers are not supported
+## if not c.HasObserver("ModifiedEvent"):
+## self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self)))
+## self.Observed = c
+ return c
+
+ def __getattr__(self, name):
+ """With the exception of a few overloaded methods,
+ returns the SMProxy method"""
+ if not self.SMProxy:
+ raise AttributeError("class %s has no attribute %s" % ("None", name))
+ return None
+ # Handle GetActiveCamera specially.
+ if name == "GetActiveCamera" and \
+ hasattr(self.SMProxy, "GetActiveCamera"):
+ return self.__GetActiveCamera
+ if name == "SaveDefinition" and hasattr(self.SMProxy, "SaveDefinition"):
+ return self.__SaveDefinition
+ # If not a property, see if SMProxy has the method
+ try:
+ proxyAttr = getattr(self.SMProxy, name)
+ self.__LastAttrName = name
+ return self.__ConvertArgumentsAndCall
+ except:
+ pass
+ return getattr(self.SMProxy, name)
+
+class SourceProxy(Proxy):
+ """Proxy for a source object. This class adds a few methods to Proxy
+ that are specific to sources. It also provides access to the output
+ ports. Output ports can be accessed by name or index:
+ > op = source[0]
+ or
+ > op = source['some name'].
+ """
+ def UpdatePipeline(self, time=None):
+ """This method updates the server-side VTK pipeline and the associated
+ data information. Make sure to update a source to validate the output
+ meta-data."""
+ if time != None:
+ self.SMProxy.UpdatePipeline(time)
+ else:
+ self.SMProxy.UpdatePipeline()
+ # This is here to cause a receive
+ # on the client side so that progress works properly.
+ if ActiveConnection and ActiveConnection.IsRemote():
+ self.SMProxy.GetDataInformation()
+
+ def FileNameChanged(self):
+ "Called when the filename of a source proxy is changed."
+ self.UpdatePipelineInformation()
+
+ def UpdatePipelineInformation(self):
+ """This method updates the meta-data of the server-side VTK pipeline and
+ the associated information properties"""
+ self.SMProxy.UpdatePipelineInformation()
+
+ def GetDataInformation(self, idx=None):
+ """This method returns a DataInformation wrapper around a
+ vtkPVDataInformation"""
+ if idx == None:
+ idx = self.Port
+ if self.SMProxy:
+ return DataInformation( \
+ self.SMProxy.GetDataInformation(idx), \
+ self.SMProxy, idx)
+
+ def __getitem__(self, idx):
+ """Given a slice, int or string, returns the corresponding
+ output port"""
+ if isinstance(idx, slice):
+ indices = idx.indices(self.SMProxy.GetNumberOfOutputPorts())
+ retVal = []
+ for i in range(*indices):
+ retVal.append(OutputPort(self, i))
+ return retVal
+ elif isinstance(idx, int):
+ if idx >= self.SMProxy.GetNumberOfOutputPorts() or idx < 0:
+ raise IndexError
+ return OutputPort(self, idx)
+ else:
+ return OutputPort(self, self.SMProxy.GetOutputPortIndex(idx))
+
+ def GetPointDataInformation(self):
+ """Returns the associated point data information."""
+ self.UpdatePipeline()
+ return FieldDataInformation(self.SMProxy, self.Port, "PointData")
+
+ def GetCellDataInformation(self):
+ """Returns the associated cell data information."""
+ self.UpdatePipeline()
+ return FieldDataInformation(self.SMProxy, self.Port, "CellData")
+
+ def GetFieldDataInformation(self):
+ """Returns the associated cell data information."""
+ self.UpdatePipeline()
+ return FieldDataInformation(self.SMProxy, self.Port, "FieldData")
+
+ PointData = property(GetPointDataInformation, None, None, "Returns point data information")
+ CellData = property(GetCellDataInformation, None, None, "Returns cell data information")
+ FieldData = property(GetFieldDataInformation, None, None, "Returns field data information")
+
+
+class ExodusIIReaderProxy(SourceProxy):
+ """Special class to define convenience functions for array
+ selection."""
+
+ def FileNameChanged(self):
+ "Called when the filename changes. Selects all variables."
+ SourceProxy.FileNameChanged(self)
+ self.SelectAllVariables()
+
+ def SelectAllVariables(self):
+ "Select all available variables for reading."
+ for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+ 'ElementVariables', 'GlobalVariables'):
+ f = getattr(self, prop)
+ f.SelectAll()
+
+ def DeselectAllVariables(self):
+ "Deselects all variables."
+ for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+ 'ElementVariables', 'GlobalVariables'):
+ f = getattr(self, prop)
+ f.DeselectAll()
+
+class ViewLayoutProxy(Proxy):
+ """Special class to define convenience methods for View Layout"""
+
+ def SplitViewHorizontal(self, view, fraction=0.5):
+ """Split the cell containing the specified view horizontally.
+ If no fraction is specified, the frame is split into equal parts.
+ On success returns a positve number that identifying the new cell
+ location that can be used to assign view to, or split further.
+ Return -1 on failure."""
+ location = self.GetViewLocation(view)
+ if location == -1:
+ raise RuntimeError, "View is not present in this layout."
+ if fraction < 0.0 or fraction > 1.0:
+ raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]"
+ return self.SMProxy.SplitHorizontal(location, fraction)
+
+ def SplitViewVertical(self, view=None, fraction=0.5):
+ """Split the cell containing the specified view horizontally.
+ If no view is specified, active view is used.
+ If no fraction is specified, the frame is split into equal parts.
+ On success returns a positve number that identifying the new cell
+ location that can be used to assign view to, or split further.
+ Return -1 on failure."""
+ location = self.GetViewLocation(view)
+ if location == -1:
+ raise RuntimeError, "View is not present in this layout."
+ if fraction < 0.0 or fraction > 1.0:
+ raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]"
+ return self.SMProxy.SplitVertical(location, fraction)
+
+ def AssignView(self, location, view):
+ """Assign a view at a particular location. Note that the view's position may
+ be changed by subsequent Split() calls. Returns true on success."""
+ viewproxy = None
+ if isinstance(view, Proxy):
+ view = view.SMProxy
+ return self.SMProxy.AssignView(location, view)
+
+ def GetViewLocation(self, view):
+ if isinstance(view, Proxy):
+ view = view.SMProxy
+ return self.SMProxy.GetViewLocation(view)
+
+class Property(object):
+ """Generic property object that provides access to one of the properties of
+ a server object. This class does not allow setting/getting any values but
+ provides an interface to update a property using __call__. This can be used
+ for command properties that correspond to function calls without arguments.
+ For example,
+ > proxy.Foo()
+ would push a Foo property which may cause the proxy to call a Foo method
+ on the actual VTK object.
+
+ For advanced users:
+ Python wrapper around a vtkSMProperty with a simple interface.
+ In addition to all method provided by vtkSMProperty (obtained by
+ forwarding unknown attributes requests to the underlying SMProxy),
+ Property and sub-class provide a list API.
+
+ Please note that some of the methods accessible through the Property
+ class are not listed by help() because the Property objects forward
+ unresolved attributes to the underlying object. To get the full list,
+ see also dir(proxy.SMProperty). See also the doxygen based documentation
+ of the vtkSMProperty C++ class.
+ """
+ def __init__(self, proxy, smproperty):
+ """Default constructor. Stores a reference to the proxy."""
+ import weakref
+ self.SMProperty = smproperty
+ self.Proxy = proxy
+
+ def __repr__(self):
+ """Returns a string representation containing property name
+ and value"""
+ if not type(self) is Property:
+ if self.GetData() is not None:
+ repr = self.GetData().__repr__()
+ else:
+ repr = "None"
+ else:
+ repr = "Property name= "
+ name = self.Proxy.GetPropertyName(self.SMProperty)
+ if name:
+ repr += name
+ else:
+ repr += "Unknown"
+
+ return repr
+
+ def __call__(self):
+ """Forces a property update using InvokeCommand."""
+ if type(self) is Property:
+ self.Proxy.SMProxy.InvokeCommand(self._FindPropertyName())
+ else:
+ raise RuntimeError, "Cannot invoke this property"
+
+ def _FindPropertyName(self):
+ "Returns the name of this property."
+ return self.Proxy.GetPropertyName(self.SMProperty)
+
+ def _UpdateProperty(self):
+ "Pushes the value of this property to the server."
+ # For now, we are updating all properties. This is due to an
+ # issue with the representations. Their VTK objects are not
+ # created until Input is set therefore, updating a property
+ # has no effect. Updating all properties everytime one is
+ # updated has the effect of pushing values set before Input
+ # when Input is updated.
+ # self.Proxy.SMProxy.UpdateProperty(self._FindPropertyName())
+ self.Proxy.SMProxy.UpdateVTKObjects()
+
+ def __getattr__(self, name):
+ "Unknown attribute requests get forwarded to SMProperty."
+ return getattr(self.SMProperty, name)
+
+ Name = property(_FindPropertyName, None, None,
+ "Returns the name for the property")
+
+class GenericIterator(object):
+ """Iterator for container type objects"""
+
+ def __init__(self, obj):
+ self.Object = obj
+ self.index = 0
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if self.index >= len(self.Object):
+ raise StopIteration
+
+ idx = self.index
+ self.index += 1
+ return self.Object[idx]
+
+class VectorProperty(Property):
+ """A VectorProperty provides access to one or more values. You can use
+ a slice to get one or more property values:
+ > val = property[2]
+ or
+ > vals = property[0:5:2]
+ You can use a slice to set one or more property values:
+ > property[2] = val
+ or
+ > property[1:3] = (1,2)
+ """
+ def ConvertValue(self, value):
+ return value
+
+ def __len__(self):
+ """Returns the number of elements."""
+ return self.SMProperty.GetNumberOfElements()
+
+ def __iter__(self):
+ """Implementation of the sequence API"""
+ return GenericIterator(self)
+
+ def __setitem__(self, idx, value):
+ """Given a list or tuple of values, sets a slice of values [min, max)"""
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ for i, j in zip(range(*indices), value):
+ self.SMProperty.SetElement(i, self.ConvertValue(j))
+ self._UpdateProperty()
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ else:
+ self.SMProperty.SetElement(idx, self.ConvertValue(value))
+ self._UpdateProperty()
+
+ def GetElement(self, index):
+ return self.SMProperty.GetElement(index)
+
+ def __getitem__(self, idx):
+ """Returns the range [min, max) of elements. Raises an IndexError
+ exception if an argument is out of bounds."""
+ ls = len(self)
+ if isinstance(idx, slice):
+ indices = idx.indices(ls)
+ retVal = []
+ for i in range(*indices):
+ retVal.append(self.GetElement(i))
+ return retVal
+ elif idx >= ls:
+ raise IndexError
+ elif idx < 0:
+ idx = ls + idx
+ if idx < 0:
+ raise IndexError
+
+ return self.GetElement(idx)
+
+ def GetData(self):
+ "Returns all elements as either a list or a single value."
+ property = self.SMProperty
+ if property.GetRepeatable() or \
+ property.GetNumberOfElements() > 1:
+ return self[0:len(self)]
+ elif property.GetNumberOfElements() == 1:
+ return self.GetElement(0)
+
+ def SetData(self, values):
+ """Allows setting of all values at once. Requires a single value or
+ a iterable object."""
+ if not hasattr(values, "__iter__"):
+ values = (values,)
+ if not self.GetRepeatable() and len(values) != self.GetNumberOfElements():
+ raise RuntimeError("This property requires %d values." % self.GetNumberOfElements())
+ if self.GetRepeatable():
+ # Clean up first
+ self.SMProperty.SetNumberOfElements(0)
+ idx = 0
+ for val in values:
+ self.SMProperty.SetElement(idx, self.ConvertValue(val))
+ idx += 1
+ self._UpdateProperty()
+
+ def Clear(self):
+ "Removes all elements."
+ self.SMProperty().SetNumberOfElements(0)
+ self._UpdateProperty()
+
+class ColorArrayProperty(VectorProperty):
+ """This subclass of VectorProperty handles setting of the array to
+ color by. It handles attribute type as well as well array name."""
+
+ def GetAvailable(self):
+ """Returns the list of available arrays as (attribute type, array name
+ tuples."""
+ arrays = []
+ for a in self.Proxy.Input.PointData:
+ arrays.append(('POINT_DATA', a.GetName()))
+ for a in self.Proxy.Input.CellData:
+ arrays.append(('CELL_DATA', a.GetName()))
+ return arrays
+
+ def SetData(self, value):
+ """Overwritten to enable setting attribute type (the ColorAttributeType
+ property and the array name. The argument should be the array name
+ (in which case the first appropriate attribute type is picked) or
+ a tuple of attribute type and array name."""
+ if isinstance(value, tuple) and len(value) == 2:
+ att = value[0]
+ arr = value[1]
+ elif isinstance(value, str):
+ att = None
+ arr = value
+ else:
+ raise ValueError("Expected a tuple of 2 values or a string.")
+
+ if not arr:
+ self.SMProperty.SetElement(0, '')
+ self._UpdateProperty()
+ return
+
+ found = False
+ for a in self.Available:
+ if a[1] == arr and (not att or att == a[0]):
+ att = a[0]
+ found = True
+ break
+
+ if not found:
+ pvoptions = vtkProcessModule.GetProcessModule().GetOptions()
+ # if this process is from a parallel batch run in symmetric mpi mode
+ # then we may not have any points or cells on some processes in which
+ # case we'll probably be missing the point and cell data too. the
+ # check below makes sure that we avoid this situation.
+ if pvoptions.GetProcessType() != 0x40 or pvoptions.GetSymmetricMPIMode() == False \
+ or len(self.Available) != 0:
+ raise ValueError("Could not locate array %s in the input." % arr)
+
+ catt = self.Proxy.GetProperty("ColorAttributeType")
+ if att != None:
+ catt.SetData(att)
+ self.SMProperty.SetElement(0, arr)
+ self._UpdateProperty()
+
+ Available = property(GetAvailable, None, None, \
+ "This read-only property returns the list of arrays that can be colored by.")
+
+
+class EnumerationProperty(VectorProperty):
+ """Subclass of VectorProperty that is applicable for enumeration type
+ properties."""
+
+ def GetElement(self, index):
+ """Returns the text for the given element if available. Returns
+ the numerical values otherwise."""
+ val = self.SMProperty.GetElement(index)
+ domain = self.SMProperty.GetDomain("enum")
+ for i in range(domain.GetNumberOfEntries()):
+ if domain.GetEntryValue(i) == val:
+ return domain.GetEntryText(i)
+ return val
+
+ def ConvertValue(self, value):
+ """Converts value to type suitable for vtSMProperty::SetElement()"""
+ if type(value) == str:
+ domain = self.SMProperty.GetDomain("enum")
+ if domain.HasEntryText(value):
+ return domain.GetEntryValueForText(value)
+ else:
+ raise ValueError("%s is not a valid value." % value)
+ return VectorProperty.ConvertValue(self, value)
+
+ def GetAvailable(self):
+ "Returns the list of available values for the property."
+ retVal = []
+ domain = self.SMProperty.GetDomain("enum")
+ for i in range(domain.GetNumberOfEntries()):
+ retVal.append(domain.GetEntryText(i))
+ return retVal
+
+ Available = property(GetAvailable, None, None, \
+ "This read-only property contains the list of values that can be applied to this property.")
+
+
+class FileNameProperty(VectorProperty):
+ """Property to set/get one or more file names.
+ This property updates the pipeline information everytime its value changes.
+ This is used to keep the array lists up to date."""
+
+ def _UpdateProperty(self):
+ "Pushes the value of this property to the server."
+ VectorProperty._UpdateProperty(self)
+ self.Proxy.FileNameChanged()
+
+class ArraySelectionProperty(VectorProperty):
+ "Property to select an array to be processed by a filter."
+
+ def GetAssociation(self):
+ val = self.GetElement(3)
+ if val == "":
+ return None
+ for key, value in ASSOCIATIONS.iteritems():
+ if value == int(val):
+ return key
+
+ return None
+
+ def GetArrayName(self):
+ return self.GetElement(4)
+
+ def __len__(self):
+ """Returns the number of elements."""
+ return 2
+
+ def __setitem__(self, idx, value):
+ raise RuntimeError, "This property cannot be accessed using __setitem__"
+
+ def __getitem__(self, idx):
+ """Returns attribute type for index 0, array name for index 1"""
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ retVal = []
+ for i in range(*indices):
+ if i >= 2 or i < 0:
+ raise IndexError
+ if i == 0:
+ retVal.append(self.GetAssociation())
+ else:
+ retVal.append(self.GetArrayName())
+ return retVal
+ elif idx >= 2 or idx < 0:
+ raise IndexError
+
+ if i == 0:
+ return self.GetAssociation()
+ else:
+ return self.GetArrayName()
+
+ def SetData(self, values):
+ """Allows setting of all values at once. Requires a single value,
+ a tuple or list."""
+ if not isinstance(values, tuple) and \
+ not isinstance(values, list):
+ values = (values,)
+ if len(values) == 1:
+ self.SMProperty.SetElement(4, values[0])
+ elif len(values) == 2:
+ if isinstance(values[0], str):
+ val = str(ASSOCIATIONS[values[0]])
+ else:
+ # In case user didn't specify valid association,
+ # just pick POINTS.
+ val = str(ASSOCIATIONS['POINTS'])
+ self.SMProperty.SetElement(3, str(val))
+ self.SMProperty.SetElement(4, values[1])
+ else:
+ raise RuntimeError, "Expected 1 or 2 values."
+ self._UpdateProperty()
+
+ def UpdateDefault(self):
+ "Helper method to set default values."
+ if self.SMProperty.GetNumberOfElements() != 5:
+ return
+ if self.GetElement(4) != '' or \
+ self.GetElement(3) != '':
+ return
+
+ for i in range(0,3):
+ if self.GetElement(i) == '':
+ self.SMProperty.SetElement(i, '0')
+ al = self.SMProperty.GetDomain("array_list")
+ al.Update(self.SMProperty)
+ al.SetDefaultValues(self.SMProperty)
+
+class ArrayListProperty(VectorProperty):
+ """This property provides a simpler interface for selecting arrays.
+ Simply assign a list of arrays that should be loaded by the reader.
+ Use the Available property to get a list of available arrays."""
+
+ def __init__(self, proxy, smproperty):
+ VectorProperty.__init__(self, proxy, smproperty)
+ self.__arrays = []
+
+ def GetAvailable(self):
+ "Returns the list of available arrays"
+ dm = self.GetDomain("array_list")
+ retVal = []
+ for i in range(dm.GetNumberOfStrings()):
+ retVal.append(dm.GetString(i))
+ return retVal
+
+ Available = property(GetAvailable, None, None, \
+ "This read-only property contains the list of items that can be read by a reader.")
+
+ def SelectAll(self):
+ "Selects all arrays."
+ self.SetData(self.Available)
+
+ def DeselectAll(self):
+ "Deselects all arrays."
+ self.SetData([])
+
+ def __iter__(self):
+ """Implementation of the sequence API"""
+ return GenericIterator(self)
+
+ def __len__(self):
+ """Returns the number of elements."""
+ return len(self.GetData())
+
+ def __setitem__(self, idx, value):
+ """Given a list or tuple of values, sets a slice of values [min, max)"""
+ self.GetData()
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ for i, j in zip(range(*indices), value):
+ self.__arrays[i] = j
+ self.SetData(self.__arrays)
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ else:
+ self.__arrays[idx] = self.ConvertValue(value)
+ self.SetData(self.__arrays)
+
+ def __getitem__(self, idx):
+ """Returns the range [min, max) of elements. Raises an IndexError
+ exception if an argument is out of bounds."""
+ self.GetData()
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ retVal = []
+ for i in range(*indices):
+ retVal.append(self.__arrays[i])
+ return retVal
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ return self.__arrays[idx]
+
+ def SetData(self, values):
+ """Allows setting of all values at once. Requires a single value,
+ a tuple or list."""
+ # Clean up first
+ iup = self.SMProperty.GetImmediateUpdate()
+ self.SMProperty.SetImmediateUpdate(False)
+ # Clean up first
+ self.SMProperty.SetNumberOfElements(0)
+ if not isinstance(values, tuple) and \
+ not isinstance(values, list):
+ values = (values,)
+ fullvalues = []
+
+ # WARNING:
+ # The order of the two loops below are delibrately set in this way
+ # so that values passed in will take precedence.
+ # This is needed for backward compatibility of the
+ # property ElementBlocks for vtkExodusIIReader.
+ # If you attemp to change this, please verify that
+ # python state files for opening old .ex2 file (<=3.14) still works.
+ for array in self.Available:
+ if not values.__contains__(array):
+ fullvalues.append(array)
+ fullvalues.append('0')
+
+ for i in range(len(values)):
+ val = self.ConvertValue(values[i])
+ fullvalues.append(val)
+ fullvalues.append('1')
+
+
+ i = 0
+ for value in fullvalues:
+ self.SMProperty.SetElement(i, value)
+ i += 1
+
+ self._UpdateProperty()
+ self.SMProperty.SetImmediateUpdate(iup)
+
+ def GetData(self):
+ "Returns all elements as a list."
+ property = self.SMProperty
+ nElems = property.GetNumberOfElements()
+ if nElems%2 != 0:
+ raise ValueError, "The SMProperty with XML label '%s' has a size that is not a multiple of 2." % property.GetXMLLabel()
+ self.__arrays = []
+ for i in range(0, nElems, 2):
+ if self.GetElement(i+1) != '0':
+ self.__arrays.append(self.GetElement(i))
+ return list(self.__arrays)
+
+class ProxyProperty(Property):
+ """A ProxyProperty provides access to one or more proxies. You can use
+ a slice to get one or more property values:
+ > proxy = property[2]
+ or
+ > proxies = property[0:5:2]
+ You can use a slice to set one or more property values:
+ > property[2] = proxy
+ or
+ > property[1:3] = (proxy1, proxy2)
+ You can also append and delete:
+ > property.append(proxy)
+ and
+ > del property[1:2]
+
+ You can also remove all elements with Clear().
+
+ Note that some properties expect only 1 proxy and will complain if
+ you set the number of values to be something else.
+ """
+ def __init__(self, proxy, smproperty):
+ """Default constructor. Stores a reference to the proxy. Also looks
+ at domains to find valid values."""
+ Property.__init__(self, proxy, smproperty)
+ # Check to see if there is a proxy list domain and, if so,
+ # initialize ourself. (Should this go in ProxyProperty?)
+ listdomain = self.GetDomain('proxy_list')
+ if listdomain:
+ if listdomain.GetClassName() != 'vtkSMProxyListDomain':
+ raise ValueError, "Found a 'proxy_list' domain on an InputProperty that is not a ProxyListDomain."
+ pm = ProxyManager()
+ group = "pq_helper_proxies." + proxy.GetGlobalIDAsString()
+ if listdomain.GetNumberOfProxies() == 0:
+ for i in xrange(listdomain.GetNumberOfProxyTypes()):
+ igroup = listdomain.GetProxyGroup(i)
+ name = listdomain.GetProxyName(i)
+ iproxy = CreateProxy(igroup, name)
+ listdomain.AddProxy(iproxy)
+ pm.RegisterProxy(group, proxy.GetPropertyName(smproperty), iproxy)
+ listdomain.SetDefaultValues(self.SMProperty)
+
+ def GetAvailable(self):
+ """If this proxy has a list domain, then this function returns the
+ strings you can use to select from the domain. If there is no such
+ list domain, the returned list is empty."""
+ listdomain = self.GetDomain('proxy_list')
+ retval = []
+ if listdomain:
+ for i in xrange(listdomain.GetNumberOfProxies()):
+ proxy = listdomain.GetProxy(i)
+ retval.append(proxy.GetXMLLabel())
+ return retval
+
+ Available = property(GetAvailable, None, None,
+ """This read only property is a list of strings you can
+ use to select from the list domain. If there is no
+ such list domain, the array is empty.""")
+
+ def __iter__(self):
+ """Implementation of the sequence API"""
+ return GenericIterator(self)
+
+ def __len__(self):
+ """Returns the number of elements."""
+ return self.SMProperty.GetNumberOfProxies()
+
+ def remove(self, proxy):
+ """Removes the first occurence of the proxy from the property."""
+ self.SMProperty.RemoveProxy(proxy.SMProxy)
+ self._UpdateProperty()
+
+ def __setitem__(self, idx, value):
+ """Given a list or tuple of values, sets a slice of values [min, max)"""
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ for i, j in zip(range(*indices), value):
+ self.SMProperty.SetProxy(i, j.SMProxy)
+ self._UpdateProperty()
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ else:
+ self.SMProperty.SetProxy(idx, value.SMProxy)
+ self._UpdateProperty()
+
+ def __delitem__(self,idx):
+ """Removes the element idx"""
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ # Collect the elements to delete to a new list first.
+ # Otherwise indices are screwed up during the actual
+ # remove loop.
+ toremove = []
+ for i in range(*indices):
+ toremove.append(self[i])
+ for i in toremove:
+ self.SMProperty.RemoveProxy(i.SMProxy)
+ self._UpdateProperty()
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ else:
+ self.SMProperty.RemoveProxy(self[idx].SMProxy)
+ self._UpdateProperty()
+
+ def __getitem__(self, idx):
+ """Returns the range [min, max) of elements. Raises an IndexError
+ exception if an argument is out of bounds."""
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ retVal = []
+ for i in range(*indices):
+ retVal.append(_getPyProxy(self.SMProperty.GetProxy(i)))
+ return retVal
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ return _getPyProxy(self.SMProperty.GetProxy(idx))
+
+ def __getattr__(self, name):
+ "Unknown attribute requests get forwarded to SMProperty."
+ return getattr(self.SMProperty, name)
+
+ def index(self, proxy):
+ idx = 0
+ for px in self:
+ ## VSV: ==
+ if proxy.IsSame(px):
+ return idx
+ idx += 1
+ raise ValueError("proxy is not in the list.")
+
+ def append(self, proxy):
+ "Appends the given proxy to the property values."
+ self.SMProperty.AddProxy(proxy.SMProxy)
+ self._UpdateProperty()
+
+ def GetData(self):
+ "Returns all elements as either a list or a single value."
+ property = self.SMProperty
+ if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
+ return self[0:len(self)]
+ else:
+ if property.GetNumberOfProxies() > 0:
+ return _getPyProxy(property.GetProxy(0))
+ return None
+
+ def SetData(self, values):
+ """Allows setting of all values at once. Requires a single value,
+ a tuple or list."""
+ if isinstance(values, str):
+ position = -1
+ try:
+ position = self.Available.index(values)
+ except:
+ raise ValueError, values + " is not a valid object in the domain."
+ values = self.GetDomain('proxy_list').GetProxy(position)
+ if not isinstance(values, tuple) and \
+ not isinstance(values, list):
+ values = (values,)
+ self.SMProperty.RemoveAllProxies()
+ for value in values:
+ if isinstance(value, Proxy):
+ value_proxy = value.SMProxy
+ else:
+ value_proxy = value
+ self.SMProperty.AddProxy(value_proxy)
+ self._UpdateProperty()
+
+ def Clear(self):
+ "Removes all elements."
+ self.SMProperty.RemoveAllProxies()
+ self._UpdateProperty()
+
+class InputProperty(ProxyProperty):
+ """An InputProperty allows making pipeline connections. You can set either
+ a source proxy or an OutputProperty to an input property:
+
+ > property[0] = proxy
+ or
+ > property[0] = OuputPort(proxy, 1)
+
+ > property.append(proxy)
+ or
+ > property.append(OutputPort(proxy, 0))
+ """
+ def __setitem__(self, idx, value):
+ """Given a list or tuple of values, sets a slice of values [min, max)"""
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ for i, j in zip(range(*indices), value):
+ op = value[i-min]
+ self.SMProperty.SetInputConnection(i, op.SMProxy, op.Port)
+ self._UpdateProperty()
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ else:
+ self.SMProperty.SetInputConnection(idx, value.SMProxy, value.Port)
+ self._UpdateProperty()
+
+ def __getitem__(self, idx):
+ """Returns the range [min, max) of elements. Raises an IndexError
+ exception if an argument is out of bounds."""
+ if isinstance(idx, slice):
+ indices = idx.indices(len(self))
+ retVal = []
+ for i in range(*indices):
+ port = None
+ if self.SMProperty.GetProxy(i):
+ port = OutputPort(_getPyProxy(self.SMProperty.GetProxy(i)),\
+ self.SMProperty.GetOutputPortForConnection(i))
+ retVal.append(port)
+ return retVal
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\
+ self.SMProperty.GetOutputPortForConnection(idx))
+
+ def append(self, value):
+ """Appends the given proxy to the property values.
+ Accepts Proxy or OutputPort objects."""
+ self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
+ self._UpdateProperty()
+
+ def GetData(self):
+ """Returns all elements as either a list of OutputPort objects or
+ a single OutputPort object."""
+ property = self.SMProperty
+ if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
+ return self[0:len(self)]
+ else:
+ if property.GetNumberOfProxies() > 0:
+ return OutputPort(_getPyProxy(property.GetProxy(0)),\
+ self.SMProperty.GetOutputPortForConnection(0))
+ return None
+
+ def SetData(self, values):
+ """Allows setting of all values at once. Requires a single value,
+ a tuple or list. Accepts Proxy or OutputPort objects."""
+ if isinstance(values, str):
+ ProxyProperty.SetData(self, values)
+ return
+ if not isinstance(values, tuple) and \
+ not isinstance(values, list):
+ values = (values,)
+ self.SMProperty.RemoveAllProxies()
+ for value in values:
+ if value:
+ self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
+ self._UpdateProperty()
+
+ def _UpdateProperty(self):
+ "Pushes the value of this property to the server."
+ ProxyProperty._UpdateProperty(self)
+ iter = PropertyIterator(self.Proxy)
+ for prop in iter:
+ if isinstance(prop, ArraySelectionProperty):
+ prop.UpdateDefault()
+
+
+class DataInformation(object):
+ """DataInformation is a contained for meta-data associated with an
+ output data.
+
+ DataInformation is a python wrapper around a vtkPVDataInformation.
+ In addition to proving all methods of a vtkPVDataInformation, it provides
+ a few convenience methods.
+
+ Please note that some of the methods accessible through the DataInformation
+ class are not listed by help() because the DataInformation objects forward
+ unresolved attributes to the underlying object. To get the full list,
+ see also dir(proxy.DataInformation).
+ See also the doxygen based documentation of the vtkPVDataInformation C++
+ class.
+ """
+ def __init__(self, dataInformation, proxy, idx):
+ """Default constructor. Requires a vtkPVDataInformation, a source proxy
+ and an output port id."""
+ self.DataInformation = dataInformation
+ self.Proxy = proxy
+ self.Idx = idx
+
+ def Update(self):
+ """****Deprecated**** There is no reason anymore to use this method
+ explicitly, it is called automatically when one gets any value from the
+ data information object.
+ Update the data information if necessary. Note that this
+ does not cause execution of the underlying object. In certain
+ cases, you may have to call UpdatePipeline() on the proxy."""
+ if self.Proxy:
+ self.Proxy.GetDataInformation(self.Idx)
+
+ def GetDataSetType(self):
+ """Returns the dataset type as defined in vtkDataObjectTypes."""
+ self.Update()
+ if not self.DataInformation:
+ raise RuntimeError, "No data information is available"
+ if self.DataInformation.GetCompositeDataSetType() > -1:
+ return self.DataInformation.GetCompositeDataSetType()
+ return self.DataInformation.GetDataSetType()
+
+ def GetDataSetTypeAsString(self):
+ """Returns the dataset type as a user-friendly string. This is
+ not the same as the enumaration used by VTK"""
+ return vtk.vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType())
+
+ def __getattr__(self, name):
+ """Forwards unknown attribute requests to the underlying
+ vtkPVInformation."""
+ if not self.DataInformation:
+ raise AttributeError("class has no attribute %s" % name)
+ return None
+ self.Update()
+ return getattr(self.DataInformation, name)
+
+class ArrayInformation(object):
+ """Meta-information associated with an array. Use the Name
+ attribute to get the array name.
+
+ Please note that some of the methods accessible through the ArrayInformation
+ class are not listed by help() because the ArrayInformation objects forward
+ unresolved attributes to the underlying object.
+ See the doxygen based documentation of the vtkPVArrayInformation C++
+ class for a full list.
+ """
+ def __init__(self, proxy, field, name):
+ self.Proxy = proxy
+ self.FieldData = field
+ self.Name = name
+
+ def __getattr__(self, name):
+ """Forward unknown methods to vtkPVArrayInformation"""
+ array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
+ if not array: return None
+ return getattr(array, name)
+
+ def __repr__(self):
+ """Returns a user-friendly representation string."""
+ return "Array: " + self.Name
+
+ def GetRange(self, component=0):
+ """Given a component, returns its value range as a tuple of 2 values."""
+ array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
+ range = array.GetComponentRange(component)
+ return (range[0], range[1])
+
+class FieldDataInformationIterator(object):
+ """Iterator for FieldDataInformation"""
+
+ def __init__(self, info, items=False):
+ self.FieldDataInformation = info
+ self.index = 0
+ self.items = items
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if self.index >= self.FieldDataInformation.GetNumberOfArrays():
+ raise StopIteration
+
+ self.index += 1
+ ai = self.FieldDataInformation[self.index-1]
+ if self.items:
+ return (ai.GetName(), ai)
+ else:
+ return ai
+
+
+class FieldDataInformation(object):
+ """Meta-data for a field of an output object (point data, cell data etc...).
+ Provides easy access to the arrays using the slice interface:
+ > narrays = len(field_info)
+ > for i in range(narrays):
+ > array_info = field_info[i]
+
+ Full slice interface is supported:
+ > arrays = field_info[0:5:3]
+ where arrays is a list.
+
+ Array access by name is also possible:
+ > array_info = field_info['Temperature']
+
+ The number of arrays can also be accessed using the NumberOfArrays
+ property.
+ """
+ def __init__(self, proxy, idx, field):
+ self.Proxy = proxy
+ self.OutputPort = idx
+ self.FieldData = field
+
+ def GetFieldData(self):
+ """Convenience method to get the underlying
+ vtkPVDataSetAttributesInformation"""
+ return getattr(self.Proxy.GetDataInformation(self.OutputPort), "Get%sInformation" % self.FieldData)()
+
+ def GetNumberOfArrays(self):
+ """Returns the number of arrays."""
+ self.Proxy.UpdatePipeline()
+ return self.GetFieldData().GetNumberOfArrays()
+
+ def GetArray(self, idx):
+ """Given an index or a string, returns an array information.
+ Raises IndexError if the index is out of bounds."""
+ self.Proxy.UpdatePipeline()
+ if not self.GetFieldData().GetArrayInformation(idx):
+ return None
+ if isinstance(idx, str):
+ return ArrayInformation(self.Proxy, self, idx)
+ elif idx >= len(self) or idx < 0:
+ raise IndexError
+ return ArrayInformation(self.Proxy, self, self.GetFieldData().GetArrayInformation(idx).GetName())
+
+ def __len__(self):
+ """Returns the number of arrays."""
+ return self.GetNumberOfArrays()
+
+ def __getitem__(self, idx):
+ """Implements the [] operator. Accepts an array name."""
+ if isinstance(idx, slice):
+ indices = idx.indices(self.GetNumberOfArrays())
+ retVal = []
+ for i in range(*indices):
+ retVal.append(self.GetArray(i))
+ return retVal
+ return self.GetArray(idx)
+
+ def keys(self):
+ """Implementation of the dictionary API"""
+ kys = []
+ narrays = self.GetNumberOfArrays()
+ for i in range(narrays):
+ kys.append(self.GetArray(i).GetName())
+ return kys
+
+ def values(self):
+ """Implementation of the dictionary API"""
+ vals = []
+ narrays = self.GetNumberOfArrays()
+ for i in range(narrays):
+ vals.append(self.GetArray(i))
+ return vals
+
+ def iteritems(self):
+ """Implementation of the dictionary API"""
+ return FieldDataInformationIterator(self, True)
+
+ def items(self):
+ """Implementation of the dictionary API"""
+ itms = []
+ narrays = self.GetNumberOfArrays()
+ for i in range(narrays):
+ ai = self.GetArray(i)
+ itms.append((ai.GetName(), ai))
+ return itms
+
+ def has_key(self, key):
+ """Implementation of the dictionary API"""
+ if self.GetArray(key):
+ return True
+ return False
+
+ def __iter__(self):
+ """Implementation of the dictionary API"""
+ return FieldDataInformationIterator(self)
+
+ def __getattr__(self, name):
+ """Forwards unknown attributes to the underlying
+ vtkPVDataSetAttributesInformation"""
+ array = self.GetArray(name)
+ if array: return array
+ raise AttributeError("class has no attribute %s" % name)
+ return None
+
+ NumberOfArrays = property(GetNumberOfArrays, None, None, "Returns the number of arrays.")
+
+def OutputPort(proxy, outputPort=0):
+ if not Proxy:
+ return None
+ if isinstance(outputPort, str):
+ outputPort = proxy.GetOutputPortIndex(outputPort)
+ if outputPort >= proxy.GetNumberOfOutputPorts():
+ return None
+ if proxy.Port == outputPort:
+ return proxy
+ newinstance = _getPyProxy(proxy.SMProxy, outputPort)
+ newinstance.Port = outputPort
+ newinstance._Proxy__Properties = proxy._Proxy__Properties
+ return newinstance
+
+class ProxyManager(object):
+ """When running scripts from the python shell in the ParaView application,
+ registering proxies with the proxy manager is the only mechanism to
+ notify the graphical user interface (GUI) that a proxy
+ exists. Therefore, unless a proxy is registered, it will not show up in
+ the user interface. Also, the proxy manager is the only way to get
+ access to proxies created using the GUI. Proxies created using the GUI
+ are automatically registered under an appropriate group (sources,
+ filters, representations and views). To get access to these objects,
+ you can use proxyManager.GetProxy(group, name). The name is the same
+ as the name shown in the pipeline browser.
+
+ This class is a python wrapper for vtkSMProxyManager. Note that the
+ underlying vtkSMProxyManager is a singleton. All instances of this
+ class will refer to the same object. In addition to all methods provided by
+ vtkSMProxyManager (all unknown attribute requests are forwarded
+ to the vtkSMProxyManager), this class provides several convenience
+ methods.
+
+ Please note that some of the methods accessible through the ProxyManager
+ class are not listed by help() because the ProxyManager objects forwards
+ unresolved attributes to the underlying object. To get the full list,
+ see also dir(proxy.SMProxyManager). See also the doxygen based documentation
+ of the vtkSMProxyManager C++ class.
+ """
+
+ def __init__(self, session=None):
+ """Constructor. Assigned self.SMProxyManager to
+ vtkSMProxyManager.GetProxyManager()."""
+ global ActiveConnection
+ if not session:
+ session = ActiveConnection.Session
+ self.SMProxyManager = session.GetSessionProxyManager()
+
+ def RegisterProxy(self, group, name, aProxy):
+ """Registers a proxy (either SMProxy or proxy) with the
+ server manager"""
+ if isinstance(aProxy, Proxy):
+ self.SMProxyManager.RegisterProxy(group, name, aProxy.SMProxy)
+ else:
+ self.SMProxyManager.RegisterProxy(group, name, aProxy)
+
+ def NewProxy(self, group, name):
+ """Creates a new proxy of given group and name and returns an SMProxy.
+ Note that this is a server manager object. You should normally create
+ proxies using the class objects. For example:
+ obj = servermanager.sources.SphereSource()"""
+ if not self.SMProxyManager:
+ return None
+ aProxy = self.SMProxyManager.NewProxy(group, name, "NULL")
+ if not aProxy:
+ return None
+ aProxy.UnRegister(None)
+ return aProxy
+
+ def GetProxy(self, group, name):
+ """Returns a Proxy registered under a group and name"""
+ if not self.SMProxyManager:
+ return None
+ aProxy = self.SMProxyManager.GetProxy(group, name)
+ if not aProxy:
+ return None
+ return _getPyProxy(aProxy)
+
+ def GetPrototypeProxy(self, group, name):
+ """Returns a prototype proxy given a group and name. This is an
+ SMProxy. This is a low-level method. You should not normally
+ have to call it."""
+ if not self.SMProxyManager:
+ return None
+ aProxy = self.SMProxyManager.GetPrototypeProxy(group, name)
+ if not aProxy:
+ return None
+ return aProxy
+
+ def GetProxiesInGroup(self, groupname):
+ """Returns a map of proxies in a particular group."""
+ proxies = {}
+ iter = self.NewGroupIterator(groupname)
+ for aProxy in iter:
+ proxies[(iter.GetKey(), aProxy.GetGlobalIDAsString())] = aProxy
+ return proxies
+
+ def UnRegisterProxy(self, groupname, proxyname, aProxy):
+ """Unregisters a proxy."""
+ if not self.SMProxyManager:
+ return
+ if aProxy != None and isinstance(aProxy,Proxy):
+ aProxy = aProxy.SMProxy
+ if aProxy:
+ self.SMProxyManager.UnRegisterProxy(groupname, proxyname, aProxy)
+
+ def GetProxies(self, groupname, proxyname):
+ """Returns all proxies registered under the given group with the
+ given name. Note that it is possible to register more than one
+ proxy with the same name in the same group. Because the proxies
+ are different, there is no conflict. Use this method instead of
+ GetProxy() if you know that there are more than one proxy registered
+ with this name."""
+ if not self.SMProxyManager:
+ return []
+ collection = vtk.vtkCollection()
+ result = []
+ self.SMProxyManager.GetProxies(groupname, proxyname, collection)
+ for i in range(0, collection.GetNumberOfItems()):
+ aProxy = _getPyProxy(collection.GetItemAsObject(i))
+ if aProxy:
+ result.append(aProxy)
+
+ return result
+
+ def __iter__(self):
+ """Returns a new ProxyIterator."""
+ iter = ProxyIterator()
+ iter.Begin()
+ return iter
+
+ def NewGroupIterator(self, group_name):
+ """Returns a ProxyIterator for a group. The resulting object
+ can be used to traverse the proxies that are in the given
+ group."""
+ iter = self.__iter__()
+ iter.SetModeToOneGroup()
+ iter.Begin(group_name)
+ return iter
+
+ def NewDefinitionIterator(self, groupname=None):
+ """Returns an iterator that can be used to iterate over
+ all groups and types of proxies that the proxy manager
+ can create."""
+ iter = None
+ if groupname != None:
+ iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewSingleGroupIterator(groupname,0))
+ else:
+ iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewIterator(0))
+
+ return iter
+
+ def __ConvertArgumentsAndCall(self, *args):
+ newArgs = []
+ for arg in args:
+ if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
+ newArgs.append(arg.SMProxy)
+ else:
+ newArgs.append(arg)
+ func = getattr(self.SMProxyManager, self.__LastAttrName)
+ retVal = func(*newArgs)
+ if type(retVal) is type(self.SMProxyManager) and retVal.IsA("vtkSMProxy"):
+ return _getPyProxy(retVal)
+ else:
+ return retVal
+
+ def __getattr__(self, name):
+ """Returns attribute from the ProxyManager"""
+ try:
+ pmAttr = getattr(self.SMProxyManager, name)
+ self.__LastAttrName = name
+ return self.__ConvertArgumentsAndCall
+ except:
+ pass
+ return getattr(self.SMProxyManager, name)
+
+ def LoadState(self, filename, loader = None):
+ self.SMProxyManager.LoadXMLState(filename, loader)
+
+ def SaveState(self, filename):
+ self.SMProxyManager.SaveXMLState(filename)
+
+class PropertyIterator(object):
+ """Wrapper for a vtkSMPropertyIterator class to satisfy
+ the python iterator protocol. Note that the list of
+ properties can also be obtained from the class object's
+ dictionary.
+ See the doxygen documentation for vtkSMPropertyIterator C++
+ class for details.
+ """
+
+ def __init__(self, aProxy):
+ self.SMIterator = aProxy.NewPropertyIterator()
+ if self.SMIterator:
+ self.SMIterator.UnRegister(None)
+ self.SMIterator.Begin()
+ self.Key = None
+ self.PropertyLabel = None
+ self.Proxy = aProxy
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if not self.SMIterator:
+ raise StopIteration
+
+ if self.SMIterator.IsAtEnd():
+ self.Key = None
+ raise StopIteration
+ self.Key = self.SMIterator.GetKey()
+ self.PropertyLabel = self.SMIterator.GetPropertyLabel()
+ self.SMIterator.Next()
+ return self.Proxy.GetProperty(self.Key)
+
+ def GetProxy(self):
+ """Returns the proxy for the property last returned by the call to
+ 'next()'"""
+ return self.Proxy
+
+ def GetKey(self):
+ """Returns the key for the property last returned by the call to
+ 'next()' """
+ return self.Key
+
+ def GetProperty(self):
+ """Returns the property last returned by the call to 'next()' """
+ return self.Proxy.GetProperty(self.Key)
+
+ def __getattr__(self, name):
+ """returns attributes from the vtkSMPropertyIterator."""
+ return getattr(self.SMIterator, name)
+
+class ProxyDefinitionIterator(object):
+ """Wrapper for a vtkPVProxyDefinitionIterator class to satisfy
+ the python iterator protocol.
+ See the doxygen documentation of the vtkPVProxyDefinitionIterator
+ C++ class for more information."""
+ def __init__(self, iter):
+ self.SMIterator = iter
+ if self.SMIterator:
+ self.SMIterator.UnRegister(None)
+ self.SMIterator.InitTraversal()
+ self.Group = None
+ self.Key = None
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if self.SMIterator.IsDoneWithTraversal():
+ self.Group = None
+ self.Key = None
+ raise StopIteration
+ self.Group = self.SMIterator.GetGroupName()
+ self.Key = self.SMIterator.GetProxyName()
+ self.SMIterator.GoToNextItem()
+ return {"group": self.Group, "key":self.Key }
+
+ def GetProxyName(self):
+ """Returns the key for the proxy definition last returned by the call
+ to 'next()' """
+ return self.Key
+
+ def GetGroup(self):
+ """Returns the group for the proxy definition last returned by the
+ call to 'next()' """
+ return self.Group
+
+ def __getattr__(self, name):
+ """returns attributes from the vtkPVProxyDefinitionIterator."""
+ return getattr(self.SMIterator, name)
+
+
+class ProxyIterator(object):
+ """Wrapper for a vtkSMProxyIterator class to satisfy the
+ python iterator protocol.
+ See the doxygen documentation of vtkSMProxyIterator C++ class for
+ more information.
+ """
+ def __init__(self):
+ self.SMIterator = vtkSMProxyIterator()
+ self.SMIterator.SetSession(ActiveConnection.Session)
+ self.SMIterator.Begin()
+ self.AProxy = None
+ self.Group = None
+ self.Key = None
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if self.SMIterator.IsAtEnd():
+ self.AProxy = None
+ self.Group = None
+ self.Key = None
+ raise StopIteration
+ return None
+ self.AProxy = _getPyProxy(self.SMIterator.GetProxy())
+ self.Group = self.SMIterator.GetGroup()
+ self.Key = self.SMIterator.GetKey()
+ self.SMIterator.Next()
+ return self.AProxy
+
+ def GetProxy(self):
+ """Returns the proxy last returned by the call to 'next()'"""
+ return self.AProxy
+
+ def GetKey(self):
+ """Returns the key for the proxy last returned by the call to
+ 'next()' """
+ return self.Key
+
+ def GetGroup(self):
+ """Returns the group for the proxy last returned by the call to
+ 'next()' """
+ return self.Group
+
+ def __getattr__(self, name):
+ """returns attributes from the vtkSMProxyIterator."""
+ return getattr(self.SMIterator, name)
+
+# Caution: Observers must be global methods otherwise we run into memory
+# leak when the interpreter get reset from the C++ layer.
+def _update_definitions(caller, event):
+ updateModules(ActiveConnection.Modules)
+
+class Connection(object):
+ """
+ This is a python representation for a session/connection.
+ """
+ def __init__(self, connectionId, session):
+ """Default constructor. Creates a Connection with the given
+ ID, all other data members initialized to None."""
+ global MultiServerConnections
+ global ActiveConnection
+ self.ID = connectionId
+ self.Session = session
+ self.Modules = PVModule()
+ self.Alive = True
+ self.DefinitionObserverTag = 0
+ self.CustomDefinitionObserverTag = 0
+ if MultiServerConnections == None and ActiveConnection:
+ raise RuntimeError, "Concurrent connections not supported!"
+ if MultiServerConnections != None and not self in MultiServerConnections:
+ MultiServerConnections.append(self)
+ ActiveConnection = self
+ __InitAfterConnect__(self)
+ __exposeActiveModules__()
+
+ def __eq__(self, other):
+ "Returns true if the connection ids are the same."
+ return (self.ID == other.ID)
+
+ def __repr__(self):
+ """User friendly string representation"""
+ return "Connection (%s) [%d]" % (self.Session.GetURI(), self.ID)
+
+ def GetURI(self):
+ """Get URI of the connection"""
+ return self.Session.GetURI()
+
+ def IsRemote(self):
+ """Returns True if the connection to a remote server, False if
+ it is local (built-in)"""
+ if self.Session.IsA("vtkSMSessionClient"):
+ return True
+ return False
+
+ def GetNumberOfDataPartitions(self):
+ """Returns the number of partitions on the data server for this
+ connection"""
+ return self.Session.GetServerInformation().GetNumberOfProcesses()
+
+ def AttachDefinitionUpdater(self):
+ """Attach observer to automatically update modules when needed."""
+ # VTN: Observers are not supported
+ # ProxyDefinitionsUpdated = 2000
+## self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions)
+ # CompoundProxyDefinitionsUpdated = 2001
+## self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions)
+ pass
+
+ def close(self):
+ if self.DefinitionObserverTag:
+ self.Session.GetProxyDefinitionManager().RemoveObserver(self.DefinitionObserverTag)
+ self.Session.GetProxyDefinitionManager().RemoveObserver(self.CustomDefinitionObserverTag)
+ self.Session = None
+ self.Modules = None
+ self.Alive = False
+
+ def __del__(self):
+ if self.Alive:
+ self.close()
+
+def SaveState(filename):
+ """Given a state filename, saves the state of objects registered
+ with the proxy manager."""
+ pm = ProxyManager()
+ pm.SaveState(filename)
+
+def LoadState(filename, connection=None):
+ """Given a state filename and an optional connection, loads the server
+ manager state."""
+ if not connection:
+ connection = ActiveConnection
+ if not connection:
+ raise RuntimeError, "Cannot load state without a connection"
+ pm = ProxyManager()
+ pm.LoadState(filename, None)
+ views = GetRenderViews()
+ for view in views:
+ # Make sure that the client window size matches the
+ # ViewSize property. In paraview, the GUI takes care
+ # of this.
+ if view.GetClassName() == "vtkSMIceTDesktopRenderViewProxy":
+ view.GetRenderWindow().SetSize(view.ViewSize[0], \
+ view.ViewSize[1])
+
+def InitFromGUI():
+ """
+ Method used to initialize the Python Shell from the ParaView GUI.
+ """
+ global fromGUI, ActiveConnection
+ if not fromGUI:
+ print "from paraview.simple import *"
+ fromGUI = True
+ # ToggleProgressPrinting() ### FIXME COLLABORATION
+ enableMultiServer(vtkProcessModule.GetProcessModule().GetMultipleSessionsSupport())
+ iter = vtkProcessModule.GetProcessModule().NewSessionIterator();
+ iter.InitTraversal()
+ ActiveConnection = None
+ activeSession = vtkSMProxyManager.GetProxyManager().GetActiveSession()
+ tmpActiveConnection = None
+ while not iter.IsDoneWithTraversal():
+ c = Connection(iter.GetCurrentSessionId(), iter.GetCurrentSession())
+ if c.Session == activeSession:
+ tmpActiveConnection = c
+ iter.GoToNextItem()
+ iter.UnRegister(None)
+ if tmpActiveConnection:
+ ActiveConnection = tmpActiveConnection
+
+def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=22221):
+ """
+ Use this function call to create a new session. On success,
+ it returns a vtkSMSession object that abstracts the connection.
+ Otherwise, it returns None.
+ There are several ways in which this function can be called:
+ * When called with no arguments, it creates a new session
+ to the built-in server on the client itself.
+ * When called with ds_host and ds_port arguments, it
+ attempts to connect to a server(data and render server on the same server)
+ on the indicated host:port.
+ * When called with ds_host, ds_port, rs_host, rs_port, it
+ creates a new connection to the data server on ds_host:ds_port and to the
+ render server on rs_host: rs_port.
+ """
+ if ds_host == None:
+ session = vtkSMSession()
+ elif rs_host == None:
+ session = vtkSMSessionClient()
+ session.Connect("cs://%s:%d" % (ds_host, ds_port))
+ else:
+ session = vtkSMSessionClient()
+ session.Connect("cdsrs://%s:%d/%s:%d" % (ds_host, ds_port, rs_host, rs_port))
+ id = vtkProcessModule.GetProcessModule().RegisterSession(session)
+ connection = Connection(id, session)
+ return connection
+
+def ReverseConnect(port=11111):
+ """
+ Use this function call to create a new session. On success,
+ it returns a Session object that abstracts the connection.
+ Otherwise, it returns None.
+ In reverse connection mode, the client waits for a connection
+ from the server (client has to be started first). The server
+ then connects to the client (run pvserver with -rc and -ch
+ option).
+ The optional port specified the port to listen to.
+ """
+ session = vtkSMSessionClient()
+ session.Connect("csrc://hostname:" + port)
+ id = vtkProcessModule.GetProcessModule().RegisterSession(session)
+ connection = Connection(id, session)
+ return connection
+
+def Disconnect(session=None):
+ """Disconnects the connection. Make sure to clear the proxy manager
+ first."""
+ global ActiveConnection
+ global MultiServerConnections
+ global fromGUI
+ if fromGUI:
+ # Let the UI know that we want to disconnect
+ ActiveConnection.Session.InvokeEvent('ExitEvent')
+ return
+ if ActiveConnection and (not session or session == ActiveConnection.Session):
+ session = ActiveConnection.Session
+ if MultiServerConnections:
+ MultiServerConnections.remove(ActiveConnection)
+ ActiveConnection.close()
+ ActiveConnection = None
+ switchActiveConnection()
+ else:
+ ActiveConnection.close()
+ ActiveConnection = None
+ elif MultiServerConnections:
+ for connection in MultiServerConnections:
+ if connection.Session == session:
+ connection.close()
+ MultiServerConnections.remove(connection)
+ if session:
+ vtkProcessModule.GetProcessModule().UnRegisterSession(session)
+ return
+
+def CreateProxy(xml_group, xml_name, session=None):
+ """Creates a proxy. If session is set, the proxy's session is
+ set accordingly. If session is None, the current Session is used, if
+ present. You should not have to use method normally. Instantiate the
+ appropriate class from the appropriate module, for example:
+ sph = servermanager.sources.SphereSource()"""
+ global ActiveConnection
+ if not session:
+ session = ActiveConnection.Session
+ if not session:
+ raise RuntimeError, "Cannot create objects without a session."
+ pxm = ProxyManager(session)
+ return pxm.NewProxy(xml_group, xml_name)
+
+def GetRenderView(connection=None):
+ """Return the render view in use. If more than one render view is in
+ use, return the first one."""
+
+ render_module = None
+ for aProxy in ProxyManager():
+ if aProxy.IsA("vtkSMRenderViewProxy"):
+ render_module = aProxy
+ break
+ return render_module
+
+def GetRenderViews(connection=None):
+ """Returns the set of all render views."""
+ render_modules = []
+ for aProxy in ProxyManager():
+ if aProxy.IsA("vtkSMRenderViewProxy"):
+ render_modules.append(aProxy)
+ return render_modules
+
+def GetContextViews(connection=None):
+ """Returns the set of all context views."""
+ context_modules = []
+ for aProxy in ProxyManager():
+ if aProxy.IsA("vtkSMContextViewProxy"):
+ context_modules.append(aProxy)
+ return context_modules
+
+def CreateRenderView(session=None, **extraArgs):
+ """Creates a render window on the particular session. If session
+ is not specified, then the active session is used, if available.
+
+ This method can also be used to initialize properties by passing
+ keyword arguments where the key is the name of the property. In addition
+ registrationGroup and registrationName (optional) can be specified (as
+ keyword arguments) to automatically register the proxy with the proxy
+ manager."""
+ return _create_view("RenderView", session, **extraArgs)
+
+def _create_view(view_xml_name, session=None, **extraArgs):
+ """Creates a view on the particular session. If session
+ is not specified, then the active session is used, if available.
+ This method can also be used to initialize properties by passing
+ keyword arguments where the key is the name of the property."""
+ if not session:
+ session = ActiveConnection.Session
+ if not session:
+ raise RuntimeError, "Cannot create view without session."
+ pxm = ProxyManager()
+ view_module = None
+ if view_xml_name:
+ view_module = CreateProxy("views", view_xml_name, session)
+ if not view_module:
+ return None
+ extraArgs['proxy'] = view_module
+ python_proxy_name = _make_name_valid(view_module.GetXMLName())
+ proxy = rendering.__dict__[python_proxy_name](**extraArgs)
+ return proxy
+
+def GetRepresentation(aProxy, view):
+ for rep in view.Representations:
+ #VSV: ==
+ try: isRep = rep.Input.IsSame(aProxy)
+ except: isRep = False
+ if isRep: return rep
+ return None
+
+def CreateRepresentation(aProxy, view, **extraArgs):
+ """Creates a representation for the proxy and adds it to the render
+ module.
+
+ This method can also be used to initialize properties by passing
+ keyword arguments where the key is the name of the property.In addition
+ registrationGroup and registrationName (optional) can be specified (as
+ keyword arguments) to automatically register the proxy with the proxy
+ manager.
+
+ This method tries to create the best possible representation for the given
+ proxy in the given view. Additionally, the user can specify proxyName
+ (optional) to create a representation of a particular type."""
+
+ global rendering
+ if not aProxy:
+ raise RuntimeError, "proxy argument cannot be None."
+ if not view:
+ raise RuntimeError, "view argument cannot be None."
+ if "proxyName" in extraArgs:
+ display = CreateProxy("representations", extraArgs['proxyName'], None)
+ del extraArgs['proxyName']
+ else:
+ display = view.SMProxy.CreateDefaultRepresentation(aProxy.SMProxy, 0)
+ if display:
+ display.UnRegister(None)
+ if not display:
+ return None
+ extraArgs['proxy'] = display
+ proxy = rendering.__dict__[display.GetXMLName()](**extraArgs)
+ proxy.Input = aProxy
+ proxy.UpdateVTKObjects()
+ view.Representations.append(proxy)
+ return proxy
+
+class _ModuleLoader(object):
+ def find_module(self, fullname, path=None):
+ if vtkPVPythonModule.HasModule(fullname):
+ return self
+ else:
+ return None
+ def load_module(self, fullname):
+ import imp
+ moduleInfo = vtkPVPythonModule.GetModule(fullname)
+ if not moduleInfo:
+ raise ImportError
+ module = sys.modules.setdefault(fullname, imp.new_module(fullname))
+ module.__file__ = "<%s>" % moduleInfo.GetFullName()
+ module.__loader__ = self
+ if moduleInfo.GetIsPackage:
+ module.__path__ = moduleInfo.GetFullName()
+ code = compile(moduleInfo.GetSource(), module.__file__, 'exec')
+ exec code in module.__dict__
+ return module
+
+def LoadXML(xmlstring):
+ """DEPRECATED. Given a server manager XML as a string, parse and process it."""
+ raise RuntimeError, "Deprecated. Use LoadPlugin(...) instead."
+
+
+def LoadPlugin(filename, remote=True, connection=None):
+ """ Given a filename and a session (optional, otherwise uses
+ ActiveConnection), loads a plugin. It then updates the sources,
+ filters and rendering modules."""
+
+ if not connection:
+ connection = ActiveConnection
+ if not connection:
+ raise RuntimeError, "Cannot load a plugin without a connection."
+ plm = vtkSMProxyManager.GetProxyManager().GetPluginManager()
+
+ if remote:
+ status = plm.LoadRemotePlugin(filename, connection.Session)
+ else:
+ status = plm.LoadLocalPlugin(filename)
+
+ # shouldn't the extension check happend before attempting to load the plugin?
+ if not status:
+ raise RuntimeError, "Problem loading plugin %s" % (filename)
+ else:
+ # we should never have to call this. The modules should update automatically.
+ updateModules(connection.Modules)
+
+
+def Fetch(input, arg1=None, arg2=None, idx=0):
+ """
+ A convenience method that moves data from the server to the client,
+ optionally performing some operation on the data as it moves.
+ The input argument is the name of the (proxy for a) source or filter
+ whose output is needed on the client.
+
+ You can use Fetch to do three things:
+
+ If arg1 is None (the default) then all of the data is brought to the client.
+ In parallel runs an appropriate append Filter merges the
+ data on each processor into one data object. The filter chosen will be
+ vtkAppendPolyData for vtkPolyData, vtkAppendRectilinearGrid for
+ vtkRectilinearGrid, vtkMultiBlockDataGroupFilter for vtkCompositeData,
+ and vtkAppendFilter for anything else.
+
+ If arg1 is an integer then one particular processor's output is brought to
+ the client. In serial runs the arg is ignored. If you have a filter that
+ computes results in parallel and brings them to the root node, then set
+ arg to be 0.
+
+ If arg1 and arg2 are a algorithms, for example vtkMinMax, the algorithm
+ will be applied to the data to obtain some result. Here arg1 will be
+ applied pre-gather and arg2 will be applied post-gather. In parallel
+ runs the algorithm will be run on each processor to make intermediate
+ results and then again on the root processor over all of the
+ intermediate results to create a global result.
+
+ Optional argument idx is used to specify the output port number to fetch the
+ data from. Default is port 0.
+ """
+
+ import types
+
+ reducer = filters.ReductionFilter(Input=OutputPort(input,idx))
+
+ #create the pipeline that reduces and transmits the data
+ if arg1 == None:
+ cdinfo = input.GetDataInformation(idx).GetCompositeDataInformation()
+ if cdinfo.GetDataIsComposite():
+ print "use composite data append"
+ reducer.PostGatherHelperName = "vtkMultiBlockDataGroupFilter"
+
+ elif input.GetDataInformation(idx).GetDataClassName() == "vtkPolyData":
+ print "use append poly data filter"
+ reducer.PostGatherHelperName = "vtkAppendPolyData"
+
+ elif input.GetDataInformation(idx).GetDataClassName() == "vtkRectilinearGrid":
+ print "use append rectilinear grid filter"
+ reducer.PostGatherHelperName = "vtkAppendRectilinearGrid"
+
+ elif input.GetDataInformation(idx).IsA("vtkDataSet"):
+ print "use unstructured append filter"
+ reducer.PostGatherHelperName = "vtkAppendFilter"
+
+ elif type(arg1) is types.IntType:
+ reducer.PassThrough = arg1
+
+ else:
+ reducer.PreGatherHelper = arg1
+ reducer.PostGatherHelper = arg2
+
+ # reduce
+ reducer.UpdatePipeline()
+ dataInfo = reducer.GetDataInformation(0)
+ dataType = dataInfo.GetDataSetType()
+ if dataInfo.GetCompositeDataSetType() > 0:
+ dataType = dataInfo.GetCompositeDataSetType()
+
+ fetcher = filters.ClientServerMoveData(Input=reducer)
+ fetcher.OutputDataType = dataType
+ fetcher.WholeExtent = dataInfo.GetExtent()[:]
+ #fetch
+ fetcher.UpdatePipeline()
+
+ op = fetcher.GetClientSideObject().GetOutputDataObject(0)
+ opc = op.NewInstance()
+ opc.ShallowCopy(op)
+ opc.UnRegister(None)
+ return opc
+
+def AnimateReader(reader, view, filename=None):
+ """This is a utility function that, given a reader and a view
+ animates over all time steps of the reader. If the optional
+ filename is provided, a movie is created (type depends on the
+ extension of the filename."""
+ if not reader:
+ raise RuntimeError, "No reader was specified, cannot animate."
+ if not view:
+ raise RuntimeError, "No view was specified, cannot animate."
+ # Create an animation scene
+ scene = animation.AnimationScene()
+
+ # We need to have the reader and the view registered with
+ # the time keeper. This is how the scene gets its time values.
+ try:
+ tk = ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+ scene.TimeKeeper = tk
+ except IndexError:
+ tk = misc.TimeKeeper()
+ scene.TimeKeeper = tk
+
+ if not reader in tk.TimeSources:
+ tk.TimeSources.append(reader)
+ if not view in tk.Views:
+ tk.Views.append(view)
+
+
+ # with 1 view
+ scene.ViewModules = [view]
+ # Update the reader to get the time information
+ reader.UpdatePipelineInformation()
+ # Animate from 1st time step to last
+ scene.StartTime = reader.TimestepValues.GetData()[0]
+ scene.EndTime = reader.TimestepValues.GetData()[-1]
+
+ # Each frame will correspond to a time step
+ scene.PlayMode = 2 #Snap To Timesteps
+
+ # Create a special animation cue for time.
+ cue = animation.TimeAnimationCue()
+ cue.AnimatedProxy = view
+ cue.AnimatedPropertyName = "ViewTime"
+ scene.Cues = [cue]
+
+ if filename:
+ writer = vtkSMAnimationSceneImageWriter()
+ writer.SetFileName(filename)
+ writer.SetFrameRate(1)
+ writer.SetAnimationScene(scene.SMProxy)
+
+ # Now save the animation.
+ if not writer.Save():
+ raise RuntimeError, "Saving of animation failed!"
+ else:
+ scene.Play()
+ return scene
+
+def GetProgressPrintingIsEnabled():
+ return progressObserverTag is not None
+
+def SetProgressPrintingEnabled(value):
+ """Is not supported because of not supported observers"""
+ pass
+
+def ToggleProgressPrinting():
+ """Turn on/off printing of progress. See SetProgressPrintingEnabled."""
+ SetProgressPrintingEnabled(not GetProgressPrintingIsEnabled())
+
+def Finalize():
+ """Although not required, this can be called at exit to cleanup."""
+ global progressObserverTag
+ # Make sure to remove the observer
+ if progressObserverTag:
+ ToggleProgressPrinting()
+ vtkInitializationHelper.Finalize()
+
+# Internal methods
+
+def _getPyProxy(smproxy, outputPort=0):
+ """Returns a python wrapper for a server manager proxy. This method
+ first checks if there is already such an object by looking in the
+ _pyproxies group and returns it if found. Otherwise, it creates a
+ new one. Proxies register themselves in _pyproxies upon creation."""
+ if not smproxy:
+ return None
+ if (smproxy, outputPort) in _pyproxies:
+ return _pyproxies[(smproxy, outputPort)]()
+
+ xmlName = smproxy.GetXMLName()
+ if smproxy.GetXMLLabel():
+ xmlName = smproxy.GetXMLLabel()
+ classForProxy = _findClassForProxy(_make_name_valid(xmlName), smproxy.GetXMLGroup())
+ if classForProxy:
+ retVal = classForProxy(proxy=smproxy, port=outputPort)
+ else:
+ retVal = Proxy(proxy=smproxy, port=outputPort)
+ return retVal
+
+def _makeUpdateCameraMethod(rv):
+ """ This internal method is used to create observer methods """
+ if not hasattr(rv(), "BlockUpdateCamera"):
+ rv().add_attribute("BlockUpdateCamera", False)
+ def UpdateCamera(obj, string):
+ if not rv().BlockUpdateCamera:
+ # used to avoid some nasty recursion that occurs when interacting in
+ # the GUI.
+ rv().BlockUpdateCamera = True
+ rv().SynchronizeCameraProperties()
+ rv().BlockUpdateCamera = False
+ return UpdateCamera
+
+def _createInitialize(group, name):
+ """Internal method to create an Initialize() method for the sub-classes
+ of Proxy"""
+ pgroup = group
+ pname = name
+ def aInitialize(self, connection=None, update=True):
+ if not connection:
+ connection = ActiveConnection
+ if not connection:
+ raise RuntimeError,\
+ 'Cannot create a proxy without a session.'
+ if not connection.Session.GetProxyDefinitionManager().HasDefinition(pgroup, pname):
+ error_msg = "The connection does not provide any definition for %s." % pname
+ raise RuntimeError, error_msg
+ self.InitializeFromProxy(\
+ CreateProxy(pgroup, pname, connection.Session), update)
+ return aInitialize
+
+def _createGetProperty(pName):
+ """Internal method to create a GetXXX() method where XXX == pName."""
+ propName = pName
+ def getProperty(self):
+ return self.GetPropertyValue(propName)
+ return getProperty
+
+def _createSetProperty(pName):
+ """Internal method to create a SetXXX() method where XXX == pName."""
+ propName = pName
+ def setProperty(self, value):
+ return self.SetPropertyWithName(propName, value)
+ return setProperty
+
+def _findClassForProxy(xmlName, xmlGroup):
+ """Given the xmlName for a proxy, returns a Proxy class. Note
+ that if there are duplicates, the first one is returned."""
+ global sources, filters, writers, rendering, animation, implicit_functions,\
+ piecewise_functions, extended_sources, misc
+ if not xmlName:
+ return None
+ if xmlGroup == "sources":
+ return sources.__dict__[xmlName]
+ elif xmlGroup == "filters":
+ return filters.__dict__[xmlName]
+ elif xmlGroup == "implicit_functions":
+ return implicit_functions.__dict__[xmlName]
+ elif xmlGroup == "piecewise_functions":
+ return piecewise_functions.__dict__[xmlName]
+ elif xmlGroup == "writers":
+ return writers.__dict__[xmlName]
+ elif xmlGroup == "extended_sources":
+ return extended_sources.__dict__[xmlName]
+ elif xmlName in rendering.__dict__:
+ return rendering.__dict__[xmlName]
+ elif xmlName in animation.__dict__:
+ return animation.__dict__[xmlName]
+ elif xmlName in misc.__dict__:
+ return misc.__dict__[xmlName]
+ else:
+ return None
+
+def _printProgress(caller, event):
+ """The default event handler for progress. Prints algorithm
+ name and 1 '.' per 10% progress."""
+ global currentAlgorithm, currentProgress
+
+ pm = vtkProcessModule.GetProcessModule()
+ progress = pm.GetLastProgress() / 10
+ # If we got a 100% as the first thing, ignore
+ # This is to get around the fact that some vtk
+ # algorithms report 100% more than once (which is
+ # a bug)
+ if not currentAlgorithm and progress == 10:
+ return
+ alg = pm.GetLastProgressName()
+ if alg != currentAlgorithm and alg:
+ if currentAlgorithm:
+ while currentProgress <= 10:
+ import sys
+ sys.stdout.write(".")
+ currentProgress += 1
+ print "]"
+ currentProgress = 0
+ print alg, ": [ ",
+ currentAlgorithm = alg
+ while currentProgress <= progress:
+ import sys
+ sys.stdout.write(".")
+ #sys.stdout.write("%d " % pm.GetLastProgress())
+ currentProgress += 1
+ if progress == 10:
+ print "]"
+ currentAlgorithm = None
+ currentProgress = 0
+
+def updateModules(m):
+ """Called when a plugin is loaded, this method updates
+ the proxy class object in all known modules."""
+
+ createModule("sources", m.sources)
+ createModule("filters", m.filters)
+ createModule("writers", m.writers)
+ createModule("representations", m.rendering)
+ createModule("views", m.rendering)
+ createModule("lookup_tables", m.rendering)
+ createModule("textures", m.rendering)
+ createModule('cameramanipulators', m.rendering)
+ createModule("animation", m.animation)
+ createModule("misc", m.misc)
+ createModule('animation_keyframes', m.animation)
+ createModule('implicit_functions', m.implicit_functions)
+ createModule('piecewise_functions', m.piecewise_functions)
+ createModule("extended_sources", m.extended_sources)
+ createModule("incremental_point_locators", m.misc)
+
+def _createModules(m):
+ """Called when the module is loaded, this creates sub-
+ modules for all know proxy groups."""
+
+ m.sources = createModule('sources')
+ m.filters = createModule('filters')
+ m.writers = createModule('writers')
+ m.rendering = createModule('representations')
+ createModule('views', m.rendering)
+ createModule("lookup_tables", m.rendering)
+ createModule("textures", m.rendering)
+ createModule('cameramanipulators', m.rendering)
+ m.animation = createModule('animation')
+ createModule('animation_keyframes', m.animation)
+ m.implicit_functions = createModule('implicit_functions')
+ m.piecewise_functions = createModule('piecewise_functions')
+ m.extended_sources = createModule("extended_sources")
+ m.misc = createModule("misc")
+ createModule("incremental_point_locators", m.misc)
+
+class PVModule(object):
+ pass
+
+def _make_name_valid(name):
+ """Make a string into a valid Python variable name."""
+ if not name:
+ return None
+ import string
+ valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
+ name = str().join([c for c in name if c in valid_chars])
+ if not name[0].isalpha():
+ name = 'a' + name
+ return name
+
+def createModule(groupName, mdl=None):
+ """Populates a module with proxy classes defined in the given group.
+ If mdl is not specified, it also creates the module"""
+ global ActiveConnection
+
+ if not ActiveConnection:
+ raise RuntimeError, "Please connect to a server using \"Connect\""
+
+ pxm = ProxyManager()
+ # Use prototypes to find all proxy types.
+ pxm.InstantiateGroupPrototypes(groupName)
+
+ debug = False
+ if not mdl:
+ debug = True
+ mdl = PVModule()
+ definitionIter = pxm.NewDefinitionIterator(groupName)
+ for i in definitionIter:
+ proxyName = i['key']
+ proto = pxm.GetPrototypeProxy(groupName, proxyName)
+ if not proto:
+ print "Error while loading %s/%s %s"%(groupName, i['group'], proxyName)
+ continue
+ pname = proxyName
+ if proto.GetXMLLabel():
+ pname = proto.GetXMLLabel()
+ pname = _make_name_valid(pname)
+ if not pname:
+ continue
+ if pname in mdl.__dict__:
+ if debug:
+ print "Warning: %s is being overwritten. This may point to an issue in the ParaView configuration files" % pname
+ cdict = {}
+ # Create an Initialize() method for this sub-class.
+ cdict['Initialize'] = _createInitialize(groupName, proxyName)
+ iter = PropertyIterator(proto)
+ # Add all properties as python properties.
+ for prop in iter:
+ propName = iter.GetKey()
+ if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
+ or prop.GetIsInternal():
+ continue
+ names = [propName]
+ names = [iter.PropertyLabel]
+
+ propDoc = None
+ if prop.GetDocumentation():
+ propDoc = prop.GetDocumentation().GetDescription()
+ for name in names:
+ name = _make_name_valid(name)
+ if name:
+ cdict[name] = property(_createGetProperty(propName),
+ _createSetProperty(propName),
+ None,
+ propDoc)
+ # Add the documentation as the class __doc__
+ if proto.GetDocumentation() and \
+ proto.GetDocumentation().GetDescription():
+ doc = proto.GetDocumentation().GetDescription()
+ else:
+ doc = Proxy.__doc__
+ cdict['__doc__'] = doc
+ # Create the new type
+ if proto.GetXMLName() == "ExodusIIReader":
+ superclasses = (ExodusIIReaderProxy,)
+ elif proto.IsA("vtkSMSourceProxy"):
+ superclasses = (SourceProxy,)
+ elif proto.IsA("vtkSMViewLayoutProxy"):
+ superclasses = (ViewLayoutProxy,)
+ else:
+ superclasses = (Proxy,)
+
+ cobj = type(pname, superclasses, cdict)
+ # Add it to the modules dictionary
+ mdl.__dict__[pname] = cobj
+ return mdl
+
+
+def __determineGroup(proxy):
+ """Internal method"""
+ if not proxy:
+ return None
+ xmlgroup = proxy.GetXMLGroup()
+ xmlname = proxy.GetXMLName()
+ if xmlgroup == "sources":
+ if xmlname in ["BlockSelectionSource",
+ "FrustumSelectionSource",
+ "GlobalIDSelectionSource",
+ "PedigreeIDSelectionSource",
+ "IDSelectionSource",
+ "CompositeDataIDSelectionSource",
+ "HierarchicalDataIDSelectionSource",
+ "ThresholdSelectionSource",
+ "LocationSelectionSource"]:
+ return "selection_sources"
+ return "sources"
+ elif xmlgroup == "filters":
+ return "sources"
+ elif xmlgroup == "representations":
+ if xmlname == "ScalarBarWidgetRepresentation":
+ return "scalar_bars"
+ return "representations"
+ elif xmlgroup == "animation_keyframes":
+ return "animation"
+ return xmlgroup
+
+__nameCounter = {}
+def __determineName(proxy, group):
+ global __nameCounter
+ name = _make_name_valid(proxy.GetXMLLabel())
+ if not name:
+ return None
+ if not __nameCounter.has_key(name):
+ __nameCounter[name] = 1
+ val = 1
+ else:
+ __nameCounter[name] += 1
+ val = __nameCounter[name]
+ return "%s%d" % (name, val)
+
+def __getName(proxy, group):
+ pxm = ProxyManager(proxy.GetSession())
+ if isinstance(proxy, Proxy):
+ proxy = proxy.SMProxy
+ return pxm.GetProxyName(group, proxy)
+
+class MissingRegistrationInformation(Exception):
+ """Exception for missing registration information. Raised when a name or group
+ is not specified or when a group cannot be deduced."""
+ pass
+
+class MissingProxy(Exception):
+ """Exception fired when the requested proxy is missing."""
+ pass
+
+def Register(proxy, **extraArgs):
+ """Registers a proxy with the proxy manager. If no 'registrationGroup' is
+ specified, then the group is inferred from the type of the proxy.
+ 'registrationName' may be specified to register with a particular name
+ otherwise a default name will be created."""
+ # TODO: handle duplicate registration
+ if "registrationGroup" in extraArgs:
+ registrationGroup = extraArgs["registrationGroup"]
+ else:
+ registrationGroup = __determineGroup(proxy)
+
+ if "registrationName" in extraArgs:
+ registrationName = extraArgs["registrationName"]
+ else:
+ registrationName = __determineName(proxy, registrationGroup)
+ if registrationGroup and registrationName:
+ pxm = ProxyManager()
+ pxm.RegisterProxy(registrationGroup, registrationName, proxy)
+ else:
+ raise MissingRegistrationInformation, "Registration error %s %s." % (registrationGroup, registrationName)
+ return (registrationGroup, registrationName)
+
+def UnRegister(proxy, **extraArgs):
+ """UnRegisters proxies registered using Register()."""
+ if "registrationGroup" in extraArgs:
+ registrationGroup = extraArgs["registrationGroup"]
+ else:
+ registrationGroup = __determineGroup(proxy)
+
+ if "registrationName" in extraArgs:
+ registrationName = extraArgs["registrationName"]
+ else:
+ registrationName = __getName(proxy, registrationGroup)
+
+ if registrationGroup and registrationName:
+ pxm = ProxyManager()
+ pxm.UnRegisterProxy(registrationGroup, registrationName, proxy)
+ else:
+ raise RuntimeError, "UnRegistration error."
+ return (registrationGroup, registrationName)
+
+def demo1():
+ """This simple demonstration creates a sphere, renders it and delivers
+ it to the client using Fetch. It returns a tuple of (data, render
+ view)"""
+ if not ActiveConnection:
+ Connect()
+ ss = sources.Sphere(Radius=2, ThetaResolution=32)
+ shr = filters.Shrink(Input=OutputPort(ss,0))
+ cs = sources.Cone()
+ app = filters.AppendDatasets()
+ app.Input = [shr, cs]
+ rv = CreateRenderView()
+ rep = CreateRepresentation(app, rv)
+ rv.ResetCamera()
+ rv.StillRender()
+ data = Fetch(ss)
+
+ return (data, rv)
+
+def demo2(fname="/Users/berk/Work/ParaViewData/Data/disk_out_ref.ex2"):
+ """This method demonstrates the user of a reader, representation and
+ view. It also demonstrates how meta-data can be obtained using proxies.
+ Make sure to pass the full path to an exodus file. Also note that certain
+ parameters are hard-coded for disk_out_ref.ex2 which can be found
+ in ParaViewData. This method returns the render view."""
+ if not ActiveConnection:
+ Connect()
+ # Create the exodus reader and specify a file name
+ reader = sources.ExodusIIReader(FileName=fname)
+ # Get the list of point arrays.
+ arraySelection = reader.PointVariables
+ print arraySelection.Available
+ # Select all arrays
+ arraySelection.SetData(arraySelection.Available)
+
+ # Next create a default render view appropriate for the session type.
+ rv = CreateRenderView()
+ # Create the matching representation
+ rep = CreateRepresentation(reader, rv)
+ rep.Representation = 1 # Wireframe
+ # Black background is not pretty
+ rv.Background = [0.4, 0.4, 0.6]
+ rv.StillRender()
+ # Reset the camera to include the whole thing
+ rv.ResetCamera()
+ rv.StillRender()
+ # Change the elevation of the camera. See VTK documentation of vtkCamera
+ # for camera parameters.
+ c = rv.GetActiveCamera()
+ c.Elevation(45)
+ rv.StillRender()
+ # Now that the reader execute, let's get some information about it's
+ # output.
+ pdi = reader[0].PointData
+ # This prints a list of all read point data arrays as well as their
+ # value ranges.
+ print 'Number of point arrays:', len(pdi)
+ for i in range(len(pdi)):
+ ai = pdi[i]
+ print "----------------"
+ print "Array:", i, ai.Name, ":"
+ numComps = ai.GetNumberOfComponents()
+ print "Number of components:", numComps
+ for j in range(numComps):
+ print "Range:", ai.GetRange(j)
+ # White is boring. Let's color the geometry using a variable.
+ # First create a lookup table. This object controls how scalar
+ # values are mapped to colors. See VTK documentation for
+ # details.
+ lt = rendering.PVLookupTable()
+ # Assign it to the representation
+ rep.LookupTable = lt
+ # Color by point array called Pres
+ rep.ColorAttributeType = 0 # point data
+ rep.ColorArrayName = "Pres"
+ # Add to RGB points. These are tuples of 4 values. First one is
+ # the scalar values, the other 3 the RGB values. This list has
+ # 2 points: Pres: 0.00678, color: blue, Pres: 0.0288, color: red
+ lt.RGBPoints = [0.00678, 0, 0, 1, 0.0288, 1, 0, 0]
+ lt.ColorSpace = 1 # HSV
+ rv.StillRender()
+ return rv
+
+def demo3():
+ """This method demonstrates the use of servermanager with numpy as
+ well as pylab for plotting. It creates an artificial data sources,
+ probes it with a line, delivers the result to the client using Fetch
+ and plots it using pylab. This demo requires numpy and pylab installed.
+ It returns a tuple of (data, render view)."""
+ import paraview.numpy_support
+ import pylab
+
+ if not ActiveConnection:
+ Connect()
+ # Create a synthetic data source
+ source = sources.Wavelet()
+ # Let's get some information about the data. First, for the
+ # source to execute
+ source.UpdatePipeline()
+
+ di = source.GetDataInformation()
+ print "Data type:", di.GetPrettyDataTypeString()
+ print "Extent:", di.GetExtent()
+ print "Array name:", \
+ source[0].PointData[0].Name
+
+ rv = CreateRenderView()
+
+ rep1 = CreateRepresentation(source, rv)
+ rep1.Representation = 3 # outline
+
+ # Let's apply a contour filter
+ cf = filters.Contour(Input=source, ContourValues=[200])
+
+ # Select the array to contour by
+ #cf.SelectInputScalars = 'RTData'
+
+ rep2 = CreateRepresentation(cf, rv)
+
+ rv.Background = (0.4, 0.4, 0.6)
+ # Reset the camera to include the whole thing
+ rv.StillRender()
+ rv.ResetCamera()
+ rv.StillRender()
+
+ # Now, let's probe the data
+ probe = filters.ResampleWithDataset(Input=source)
+ # with a line
+ line = sources.Line(Resolution=60)
+ # that spans the dataset
+ bounds = di.GetBounds()
+ print "Bounds: ", bounds
+ line.Point1 = bounds[0:6:2]
+ line.Point2 = bounds[1:6:2]
+
+ probe.Source = line
+
+ # Render with the line
+ rep3 = CreateRepresentation(line, rv)
+ rv.StillRender()
+
+ # Now deliver it to the client. Remember, this is for small data.
+ data = Fetch(probe)
+ # Convert it to a numpy array
+ data = paraview.numpy_support.vtk_to_numpy(
+ data.GetPointData().GetArray("RTData"))
+ # Plot it using matplotlib
+ pylab.plot(data)
+ pylab.show()
+
+ return (data, rv, probe)
+
+def demo4(fname="/Users/berk/Work/ParaViewData/Data/can.ex2"):
+ """This method demonstrates the user of AnimateReader for
+ creating animations."""
+ if not ActiveConnection:
+ Connect()
+ reader = sources.ExodusIIReader(FileName=fname)
+ view = CreateRenderView()
+ repr = CreateRepresentation(reader, view)
+ view.StillRender()
+ view.ResetCamera()
+ view.StillRender()
+ c = view.GetActiveCamera()
+ c.Elevation(95)
+ return AnimateReader(reader, view)
+
+
+def demo5():
+ """ Simple sphere animation"""
+ if not ActiveConnection:
+ Connect()
+ sphere = sources.Sphere()
+ view = CreateRenderView()
+ repr = CreateRepresentation(sphere, view)
+
+ view.StillRender()
+ view.ResetCamera()
+ view.StillRender()
+
+ # Create an animation scene
+ scene = animation.AnimationScene()
+ # Add 1 view
+ scene.ViewModules = [view]
+
+ # Create a cue to animate the StartTheta property
+ cue = animation.KeyFrameAnimationCue()
+ cue.AnimatedProxy = sphere
+ cue.AnimatedPropertyName = "StartTheta"
+ # Add it to the scene's cues
+ scene.Cues = [cue]
+
+ # Create 2 keyframes for the StartTheta track
+ keyf0 = animation.CompositeKeyFrame()
+ keyf0.Type = 2 # Set keyframe interpolation type to Ramp.
+ # At time = 0, value = 0
+ keyf0.KeyTime = 0
+ keyf0.KeyValues= [0]
+
+ keyf1 = animation.CompositeKeyFrame()
+ # At time = 1.0, value = 200
+ keyf1.KeyTime = 1.0
+ keyf1.KeyValues= [200]
+
+ # Add keyframes.
+ cue.KeyFrames = [keyf0, keyf1]
+
+ scene.Play()
+ return scene
+
+ASSOCIATIONS = { 'POINTS' : 0, 'CELLS' : 1, 'VERTICES' : 4, 'EDGES' : 5, 'ROWS' : 6}
+
+# Users can set the active connection which will be used by API
+# to create proxies etc when no connection argument is passed.
+# Connect() automatically sets this if it is not already set.
+ActiveConnection = None
+
+# Fields for multi-server support
+MultiServerConnections = None
+
+# API for multi-server support
+def enableMultiServer(multiServer=True):
+ """This method enable the current servermanager to support several
+ connections. Once we enable the multi-server support, the user can create
+ as many connection as he want and switch from one to another in order to
+ create and manage proxy."""
+ global MultiServerConnections, ActiveConnection
+ if not multiServer and MultiServerConnections:
+ raise RuntimeError, "Once we enable Multi-Server support we can not get back"
+ MultiServerConnections = []
+ if ActiveConnection:
+ MultiServerConnections.append(ActiveConnection)
+
+def switchActiveConnection(newActiveConnection=None):
+ """Switch active connection to be the provided one or if none just pick the
+ other one"""
+ global MultiServerConnections, ActiveConnection
+ if MultiServerConnections == None:
+ raise RuntimeError, "enableMultiServer() must be called before"
+
+ # Manage the case when no connection is provided
+ if newActiveConnection:
+ ActiveConnection = newActiveConnection
+ __exposeActiveModules__()
+ # Update active session for ParaView
+ if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session:
+ vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session)
+ return ActiveConnection
+ else:
+ for connection in MultiServerConnections:
+ if connection != ActiveConnection:
+ ActiveConnection = connection
+ __exposeActiveModules__()
+ # Update active session for ParaView
+ if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session:
+ vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session)
+ return ActiveConnection
+ return None
+
+# Needs to be called when paraview module is loaded from python instead
+# of pvpython, pvbatch or GUI.
+if not vtkProcessModule.GetProcessModule():
+# pvoptions = None Not applicable for SALOME Python console
+# if paraview.options.batch:
+# pvoptions = vtkPVOptions();
+# pvoptions.SetProcessType(0x40)
+# if paraview.options.symmetric:
+# pvoptions.SetSymmetricMPIMode(True)
+ vtkInitializationHelper.Initialize(sys.executable,
+ vtkProcessModule.PROCESS_CLIENT, pvoptions)
+
+# Initialize progress printing. Can be turned off by calling
+# ToggleProgressPrinting() again.
+progressObserverTag = None
+currentAlgorithm = False
+currentProgress = 0
+fromGUI = False
+ToggleProgressPrinting()
+
+_pyproxies = {}
+
+# Create needed sub-modules
+# We can no longer create modules, unless we have connected to a server.
+# _createModules()
+
+# Set up our custom importer (if possible)
+loader = _ModuleLoader()
+sys.meta_path.append(loader)
+
+def __InitAfterConnect__(connection):
+ """
+ This function is called everytime after a server connection is made.
+ Since the ProxyManager and all proxy definitions are changed every time a
+ new connection is made, we re-create all the modules
+ """
+ _createModules(connection.Modules)
+ ## VSV fromFilter is alwais False for SALOME because it can't be changed from ParaView code
+ #if not paraview.fromFilter:
+ # fromFilter is set when this module is imported from the programmable
+ # filter
+# global _defUpdater
+# _defUpdater = __DefinitionUpdater()
+ connection.AttachDefinitionUpdater()
+ pass
+
+def __exposeActiveModules__():
+ """Update servermanager submodules to point to the current
+ ActiveConnection.Modules.*"""
+ # Expose all active module to the current servermanager module
+ if ActiveConnection:
+ for m in [mName for mName in dir(ActiveConnection.Modules) if mName[0] != '_' ]:
+ exec "global %s;%s = ActiveConnection.Modules.%s" % (m,m,m)
+
+# Definitions for working in SALOME GUI mode
+#aParams = myParavis.GetConnectionParameters()
+#ActiveConnection = Connect()
+##Connection(aParams[0])
+#ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5])
+#ToggleProgressPrinting()
+#fromGUI = True
+
+InitFromGUI()
+
+if hasattr(sys, "ps1"):
+ # session is interactive.
+ print vtkSMProxyManager.GetParaViewSourceVersion();
+
+def GetConnectionFromId(id):
+ for connection in MultiServerConnections:
+ if connection.ID == id:
+ return connection
+ return None
+
+def GetConnectionFromSession(session):
+ for connection in MultiServerConnections:
+ if connection.Session == session:
+ return connection
+ return None
+
+def GetConnectionAt(index):
+ return MultiServerConnections[index]
+
+def GetNumberOfConnections():
+ return len(MultiServerConnections)
+
+#VTN: Problem during execution
+#atexit.register(vtkPythonProgrammableFilter.DeleteGlobalPythonInterpretor)
--- /dev/null
+# Copyright (C) 2010-2013 CEA/DEN, EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+"""
+This module is intended to provide Python API for building presentations
+typical for Post-Pro module (Scalar Map, Deformed Shape, Vectors, etc.)
+"""
+
+
+from __future__ import division
+##from __future__ import print_function
+
+import os
+import re
+import warnings
+from math import sqrt, sin, cos, radians
+from string import upper
+
+import pvsimple as pv
+#try:
+# # TODO(MZN): to be removed (issue with Point Sprite texture)
+# #import paravisSM as sm
+#except:
+# import paraview.simple as pv
+# import paraview.servermanager as sm
+
+
+# Constants
+EPS = 1E-3
+FLT_MIN = 1E-37
+VTK_LARGE_FLOAT = 1E+38
+GAP_COEFFICIENT = 0.0001
+
+
+# Globals
+_current_bar = None
+
+
+# Enumerations
+class PrsTypeEnum:
+ """
+ Post-Pro presentation types.
+ """
+ MESH = 0
+ SCALARMAP = 1
+ ISOSURFACES = 2
+ CUTPLANES = 3
+ CUTLINES = 4
+ DEFORMEDSHAPE = 5
+ DEFORMEDSHAPESCALARMAP = 6
+ VECTORS = 7
+ PLOT3D = 8
+ STREAMLINES = 9
+ GAUSSPOINTS = 10
+
+ _type2name = {MESH: 'Mesh',
+ SCALARMAP: 'Scalar Map',
+ ISOSURFACES: 'Iso Surfaces',
+ CUTPLANES: 'Cut Planes',
+ CUTLINES: 'Cut Lines',
+ DEFORMEDSHAPE: 'Deformed Shape',
+ DEFORMEDSHAPESCALARMAP: 'Deformed Shape And Scalar Map',
+ VECTORS: 'Vectors',
+ PLOT3D: 'Plot3D',
+ STREAMLINES: 'Stream Lines',
+ GAUSSPOINTS: 'Gauss Points'}
+
+ @classmethod
+ def get_name(cls, type):
+ """Return presentaion name by its type."""
+ return cls._type2name[type]
+
+
+class EntityType:
+ """
+ Entity types.
+ """
+ NODE = 0
+ CELL = 1
+
+ _type2name = {NODE: 'OnPoint',
+ CELL: 'OnCell'}
+
+ _name2type = {'OnPoint': NODE,
+ 'OnCell': CELL}
+
+ _type2pvtype = {NODE: 'POINT_DATA',
+ CELL: 'CELL_DATA'}
+
+ @classmethod
+ def get_name(cls, type):
+ """Return entity name (used in full group names) by its type."""
+ return cls._type2name[type]
+
+ @classmethod
+ def get_type(cls, name):
+ """Return entity type by its name (used in full group names)."""
+ return cls._name2type[name]
+
+ @classmethod
+ def get_pvtype(cls, type):
+ """Return entity type from ['CELL_DATA', 'POINT_DATA']"""
+ return cls._type2pvtype[type]
+
+
+class Orientation:
+ """Orientation types.
+
+ Defines a set of plane orientation possibilities:
+ AUTO: plane orientation should be calculated.
+ XY: plane formed by X and Y axis.
+ YZ: plane formed by Y and Z axis.
+ ZX: plane formed by Z and X axis
+
+ """
+ AUTO = 0
+ XY = 1
+ YZ = 2
+ ZX = 3
+
+
+class GlyphPos:
+ """Glyph positions.
+
+ Set of elements defining the position of the vector head:
+ CENTER: in the center of the vector
+ TAIL: in the tail of the vector
+ HEAD: in the head of the vector
+
+ """
+ CENTER = 0
+ TAIL = 1
+ HEAD = 2
+
+
+class GaussType:
+ """
+ Gauss Points primitive types.
+ """
+ SPRITE = 0
+ POINT = 1
+ SPHERE = 2
+
+ _type2mode = {SPRITE: 'Texture',
+ POINT: 'SimplePoint',
+ SPHERE: 'Sphere (Texture)'}
+
+ @classmethod
+ def get_mode(cls, type):
+ """Return paraview point sprite mode by the primitive type."""
+ return cls._type2mode[type]
+
+
+# Auxiliary functions
+def process_prs_for_test(prs, view, picture_name, show_bar=True):
+ """Show presentation and record snapshot image.
+
+ Arguments:
+ prs: the presentation to show
+ view: the render view
+ picture_name: the full name of the graphics file to save
+ show_bar: to show scalar bar or not
+
+ """
+ # Show the presentation only
+ display_only(prs, view)
+
+ # Show scalar bar
+ if show_bar and _current_bar:
+ _current_bar.Visibility = 1
+
+ # Reset the view
+ reset_view(view)
+
+ # Create a directory for screenshot if necessary
+ file_name = re.sub("\s+", "_", picture_name)
+ pic_dir = os.path.dirname(picture_name)
+ if not os.path.exists(pic_dir):
+ os.makedirs(pic_dir)
+
+ # Save picture
+ pv.WriteImage(file_name, view=view, Magnification=1)
+
+
+def reset_view(view=None):
+ """Reset the view.
+
+ Set predefined (taken from Post-Pro) camera settings.
+ If the view is not passed, the active view is used.
+
+ """
+ if not view:
+ view = pv.GetRenderView()
+
+ # Camera preferences
+ view.CameraFocalPoint = [0.0, 0.0, 0.0]
+ view.CameraViewUp = [0.0, 0.0, 1.0]
+ view.CameraPosition = [738.946, -738.946, 738.946]
+
+ # Turn on the headligth
+ view.LightSwitch = 1
+ view.LightIntensity = 0.5
+
+ # Use parallel projection
+ view.CameraParallelProjection = 1
+
+ view.ResetCamera()
+ pv.Render(view=view)
+
+
+def hide_all(view, to_remove=False):
+ """Hide all representations in the view."""
+ if not view:
+ view = pv.GetRenderView()
+
+ rep_list = view.Representations
+ for rep in rep_list:
+ if hasattr(rep, 'Visibility') and rep.Visibility != 0:
+ rep.Visibility = 0
+ if to_remove:
+ view.Representations.remove(rep)
+ pv.Render(view=view)
+
+
+def display_only(prs, view=None):
+ """Display only the given presentation in the view."""
+ hide_all(view)
+ if (hasattr(prs, 'Visibility') and prs.Visibility != 1):
+ prs.Visibility = 1
+ pv.Render(view=view)
+
+
+def set_visible_lines(xy_prs, lines):
+ """Set visible only the given lines for XYChartRepresentation."""
+ sv = xy_prs.GetProperty("SeriesVisibilityInfo").GetData()
+ visible = '0'
+
+ for i in xrange(0, len(sv)):
+ if i % 2 == 0:
+ line_name = sv[i]
+ if line_name in lines:
+ visible = '1'
+ else:
+ visible = '0'
+ else:
+ sv[i] = visible
+
+ xy_prs.SeriesVisibility = sv
+
+
+def check_vector_mode(vector_mode, nb_components):
+ """Check vector mode.
+
+ Check if vector mode is correct for the data array with the
+ given number of components.
+
+ Arguments:
+ vector_mode: 'Magnitude', 'X', 'Y' or 'Z'
+ nb_components: number of component in the data array
+
+ Raises:
+ ValueError: in case of the vector mode is unexistent
+ or nonapplicable.
+
+ """
+ if vector_mode not in ('Magnitude', 'X', 'Y', 'Z'):
+ raise ValueError("Unexistent vector mode: " + vector_mode)
+
+ if ((nb_components == 1 and (vector_mode == 'Y' or vector_mode == 'Z')) or
+ (nb_components == 2 and vector_mode == 'Z')):
+ raise ValueError("Incorrect vector mode " + vector_mode + " for " +
+ nb_components + "-component field")
+
+
+def get_vector_component(vector_mode):
+ """Get vector component as ineger.
+
+ Translate vector component notation from string
+ to integer:
+ 'Magnitude': -1
+ 'X': 0
+ 'Y': 1
+ 'Z': 2
+
+ """
+ vcomponent = -1
+
+ if vector_mode == 'X':
+ vcomponent = 0
+ elif vector_mode == 'Y':
+ vcomponent = 1
+ elif vector_mode == 'Z':
+ vcomponent = 2
+
+ return vcomponent
+
+
+def get_data_range(proxy, entity, field_name, vector_mode='Magnitude',
+ cut_off=False):
+ """Get data range for the field.
+
+ Arguments:
+ proxy: the pipeline object, containig data array for the field
+ entity: the field entity
+ field_name: the field name
+ vector_mode: the vector mode ('Magnitude', 'X', 'Y' or 'Z')
+
+ Returns:
+ Data range as [min, max]
+
+ """
+ entity_data_info = None
+ field_data = proxy.GetFieldDataInformation()
+
+ if field_name in field_data.keys():
+ entity_data_info = field_data
+ elif entity == EntityType.CELL:
+ entity_data_info = proxy.GetCellDataInformation()
+ elif entity == EntityType.NODE:
+ entity_data_info = proxy.GetPointDataInformation()
+
+ data_range = []
+
+ if field_name in entity_data_info.keys():
+ vcomp = get_vector_component(vector_mode)
+ data_range = entity_data_info[field_name].GetComponentRange(vcomp)
+ else:
+ pv_entity = EntityType.get_pvtype(entity)
+ warnings.warn("Field " + field_name +
+ " is unknown for " + pv_entity + "!")
+
+ # Cut off the range
+ if cut_off and (data_range[0] <= data_range[1]):
+ data_range = list(data_range)
+ delta = abs(data_range[1] - data_range[0]) * GAP_COEFFICIENT
+ data_range[0] += delta
+ data_range[1] -= delta
+
+ return data_range
+
+
+def get_bounds(proxy):
+ """Get bounds of the proxy in 3D."""
+ dataInfo = proxy.GetDataInformation()
+ bounds_info = dataInfo.GetBounds()
+ return bounds_info
+
+
+def get_x_range(proxy):
+ """Get X range of the proxy bounds in 3D."""
+ bounds_info = get_bounds(proxy)
+ return bounds_info[0:2]
+
+
+def get_y_range(proxy):
+ """Get Y range of the proxy bounds in 3D."""
+ bounds_info = get_bounds(proxy)
+ return bounds_info[2:4]
+
+
+def get_z_range(proxy):
+ """Get Z range of the proxy bounds in 3D."""
+ bounds_info = get_bounds(proxy)
+ return bounds_info[4:6]
+
+
+def is_planar_input(proxy):
+ """Check if the given input is planar."""
+ bounds_info = get_bounds(proxy)
+
+ if (abs(bounds_info[0] - bounds_info[1]) <= FLT_MIN or
+ abs(bounds_info[2] - bounds_info[3]) <= FLT_MIN or
+ abs(bounds_info[4] - bounds_info[5]) <= FLT_MIN):
+ return True
+
+ return False
+
+
+def is_data_on_cells(proxy, field_name):
+ """Check the existence of a field on cells with the given name."""
+ cell_data_info = proxy.GetCellDataInformation()
+ return (field_name in cell_data_info.keys())
+
+
+def is_empty(proxy):
+ """Check if the object contains any points or cells.
+
+ Returns:
+ True: if the given proxy doesn't contain any points or cells
+ False: otherwise
+
+ """
+ data_info = proxy.GetDataInformation()
+
+ nb_cells = data_info.GetNumberOfCells()
+ nb_points = data_info.GetNumberOfPoints()
+
+ return not(nb_cells + nb_points)
+
+
+def get_orientation(proxy):
+ """Get the optimum cutting plane orientation for Plot 3D."""
+ orientation = Orientation.XY
+
+ bounds = get_bounds(proxy)
+ delta = [bounds[1] - bounds[0],
+ bounds[3] - bounds[2],
+ bounds[5] - bounds[4]]
+
+ if (delta[0] >= delta[1] and delta[0] >= delta[2]):
+ if (delta[1] >= delta[2]):
+ orientation = Orientation.XY
+ else:
+ orientation = Orientation.ZX
+ elif (delta[1] >= delta[0] and delta[1] >= delta[2]):
+ if (delta[0] >= delta[2]):
+ orientation = Orientation.XY
+ else:
+ orientation = Orientation.YZ
+ elif (delta[2] >= delta[0] and delta[2] >= delta[1]):
+ if (delta[0] >= delta[1]):
+ orientation = Orientation.ZX
+ else:
+ orientation = Orientation.YZ
+
+ return orientation
+
+
+def dot_product(a, b):
+ """Dot product of two 3-vectors."""
+ dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+ return dot
+
+
+def multiply3x3(a, b):
+ """Mutltiply one 3x3 matrix by another."""
+ c = [[0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0]]
+
+ for i in xrange(3):
+ c[0][i] = a[0][0] * b[0][i] + a[0][1] * b[1][i] + a[0][2] * b[2][i]
+ c[1][i] = a[1][0] * b[0][i] + a[1][1] * b[1][i] + a[1][2] * b[2][i]
+ c[2][i] = a[2][0] * b[0][i] + a[2][1] * b[1][i] + a[2][2] * b[2][i]
+
+ return c
+
+
+def get_rx(ang):
+ """Get X rotation matrix by angle."""
+ rx = [[1.0, 0.0, 0.0],
+ [0.0, cos(ang), -sin(ang)],
+ [0.0, sin(ang), cos(ang)]]
+
+ return rx
+
+
+def get_ry(ang):
+ """Get Y rotation matrix by angle."""
+ ry = [[cos(ang), 0.0, sin(ang)],
+ [0.0, 1.0, 0.0],
+ [-sin(ang), 0.0, cos(ang)]]
+
+ return ry
+
+
+def get_rz(ang):
+ """Get Z rotation matrix by angle."""
+ rz = [[cos(ang), -sin(ang), 0.0],
+ [sin(ang), cos(ang), 0.0],
+ [0.0, 0.0, 1.0]]
+
+ return rz
+
+
+def get_normal_by_orientation(orientation, ang1=0, ang2=0):
+ """Get normal for the plane by its orientation."""
+ i_plane = 0
+ rotation = [[], [], []]
+ rx = ry = rz = [[1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0]]
+
+ normal = [0.0, 0.0, 0.0]
+ if orientation == Orientation.XY:
+ if abs(ang1) > EPS:
+ rx = get_rx(ang1)
+ if abs(ang2) > EPS:
+ ry = get_ry(ang2)
+ rotation = multiply3x3(rx, ry)
+ i_plane = 2
+ elif orientation == Orientation.ZX:
+ if abs(ang1) > EPS:
+ rz = get_rz(ang1)
+ if abs(ang2) > EPS:
+ rx = get_rx(ang2)
+ rotation = multiply3x3(rz, rx)
+ i_plane = 1
+ elif orientation == Orientation.YZ:
+ if abs(ang1) > EPS:
+ ry = get_ry(ang1)
+ if abs(ang2) > EPS:
+ rz = get_rz(ang2)
+ rotation = multiply3x3(ry, rz)
+ i_plane = 0
+
+ for i in xrange(0, 3):
+ normal[i] = rotation[i][i_plane]
+
+ return normal
+
+
+def get_bound_project(bound_box, dir):
+ """Get bounds projection"""
+ bound_points = [[bound_box[0], bound_box[2], bound_box[4]],
+ [bound_box[1], bound_box[2], bound_box[4]],
+ [bound_box[0], bound_box[3], bound_box[4]],
+ [bound_box[1], bound_box[3], bound_box[4]],
+ [bound_box[0], bound_box[2], bound_box[5]],
+ [bound_box[1], bound_box[2], bound_box[5]],
+ [bound_box[0], bound_box[3], bound_box[5]],
+ [bound_box[1], bound_box[3], bound_box[5]]]
+
+ bound_prj = [0, 0, 0]
+ bound_prj[0] = dot_product(dir, bound_points[0])
+ bound_prj[1] = bound_prj[0]
+
+ for i in xrange(1, 8):
+ tmp = dot_product(dir, bound_points[i])
+ if bound_prj[1] < tmp:
+ bound_prj[1] = tmp
+ if bound_prj[0] > tmp:
+ bound_prj[0] = tmp
+
+ bound_prj[2] = bound_prj[1] - bound_prj[0]
+ bound_prj[1] = bound_prj[0] + (1.0 - EPS) * bound_prj[2]
+ bound_prj[0] = bound_prj[0] + EPS * bound_prj[2]
+ bound_prj[2] = bound_prj[1] - bound_prj[0]
+
+ return bound_prj
+
+
+def get_positions(nb_planes, dir, bounds, displacement):
+ """Compute plane positions."""
+ positions = []
+ bound_prj = get_bound_project(bounds, dir)
+ if nb_planes > 1:
+ step = bound_prj[2] / (nb_planes - 1)
+ abs_displacement = step * displacement
+ start_pos = bound_prj[0] - 0.5 * step + abs_displacement
+ for i in xrange(nb_planes):
+ pos = start_pos + i * step
+ positions.append(pos)
+ else:
+ pos = bound_prj[0] + bound_prj[2] * displacement
+ positions.append(pos)
+
+ return positions
+
+
+def get_contours(scalar_range, nb_contours):
+ """Generate contour values."""
+ contours = []
+ for i in xrange(nb_contours):
+ pos = scalar_range[0] + i * (
+ scalar_range[1] - scalar_range[0]) / (nb_contours - 1)
+ contours.append(pos)
+
+ return contours
+
+
+def get_nb_components(proxy, entity, field_name):
+ """Return number of components for the field."""
+ entity_data_info = None
+ field_data = proxy.GetFieldDataInformation()
+
+ if field_name in field_data.keys():
+ entity_data_info = field_data
+ elif entity == EntityType.CELL:
+ entity_data_info = proxy.GetCellDataInformation()
+ elif entity == EntityType.NODE:
+ entity_data_info = proxy.GetPointDataInformation()
+
+ nb_comp = None
+ if field_name in entity_data_info.keys():
+ nb_comp = entity_data_info[field_name].GetNumberOfComponents()
+ else:
+ pv_entity = EntityType.get_pvtype(entity)
+ raise ValueError("Field " + field_name +
+ " is unknown for " + pv_entity + "!")
+
+ return nb_comp
+
+
+def get_scale_factor(proxy):
+ """Compute scale factor."""
+ if not proxy:
+ return 0.0
+
+ proxy.UpdatePipeline()
+ data_info = proxy.GetDataInformation()
+
+ nb_cells = data_info.GetNumberOfCells()
+ nb_points = data_info.GetNumberOfPoints()
+ nb_elements = nb_cells if nb_cells > 0 else nb_points
+ bounds = get_bounds(proxy)
+
+ volume = 1
+ vol = dim = 0
+
+ for i in xrange(0, 6, 2):
+ vol = abs(bounds[i + 1] - bounds[i])
+ if vol > 0:
+ dim += 1
+ volume *= vol
+
+ if nb_elements == 0 or dim < 1 / VTK_LARGE_FLOAT:
+ return 0
+
+ volume /= nb_elements
+
+ return pow(volume, 1 / dim)
+
+
+def get_default_scale(prs_type, proxy, entity, field_name):
+ """Get default scale factor."""
+ data_range = get_data_range(proxy, entity, field_name)
+
+ if prs_type == PrsTypeEnum.DEFORMEDSHAPE:
+ EPS = 1.0 / VTK_LARGE_FLOAT
+ if abs(data_range[1]) > EPS:
+ scale_factor = get_scale_factor(proxy)
+ return scale_factor / data_range[1]
+ elif prs_type == PrsTypeEnum.PLOT3D:
+ bounds = get_bounds(proxy)
+ length = sqrt((bounds[1] - bounds[0]) ** 2 +
+ (bounds[3] - bounds[2]) ** 2 +
+ (bounds[5] - bounds[4]) ** 2)
+
+ EPS = 0.3
+ if data_range[1] > 0:
+ return length / data_range[1] * EPS
+
+ return 0
+
+
+def get_calc_magnitude(proxy, array_entity, array_name):
+ """Compute magnitude for the given vector array via Calculator.
+
+ Returns:
+ the calculator object.
+
+ """
+ calculator = None
+
+ # Transform vector array to scalar array if possible
+ nb_components = get_nb_components(proxy, array_entity, array_name)
+ if (nb_components > 1):
+ calculator = pv.Calculator(proxy)
+ attribute_mode = "Point Data"
+ if array_entity != EntityType.NODE:
+ attribute_mode = "Cell Data"
+ calculator.AttributeMode = attribute_mode
+ if (nb_components == 2):
+ # Workaroud: calculator unable to compute magnitude
+ # if number of components equal to 2
+ func = "sqrt(" + array_name + "_X^2+" + array_name + "_Y^2)"
+ calculator.Function = func
+ else:
+ calculator.Function = "mag(" + array_name + ")"
+ calculator.ResultArrayName = array_name + "_magnitude"
+ calculator.UpdatePipeline()
+
+ return calculator
+
+
+def get_add_component_calc(proxy, array_entity, array_name):
+ """Creates 3-component array from 2-component.
+
+ The first two components is from the original array. The 3rd component
+ is zero.
+ If the number of components is not equal to 2 - return original array name.
+
+ Returns:
+ the calculator object.
+
+ """
+ calculator = None
+
+ nb_components = get_nb_components(proxy, array_entity, array_name)
+ if nb_components == 2:
+ calculator = pv.Calculator(proxy)
+ attribute_mode = "Point Data"
+ if array_entity != EntityType.NODE:
+ attribute_mode = "Cell Data"
+ calculator.AttributeMode = attribute_mode
+ expression = "iHat * " + array_name + "_X + jHat * " + array_name + "_Y + kHat * 0"
+ calculator.Function = expression
+ calculator.ResultArrayName = array_name + "_3c"
+ calculator.UpdatePipeline()
+
+ return calculator
+
+
+def select_all_cells(proxy):
+ """Select all cell types.
+
+ Used in creation of mesh/submesh presentation.
+
+ """
+ ### Old API all_cell_types = proxy.CellTypes.Available
+ all_cell_types = proxy.Entity.Available
+ ### Old API proxy.CellTypes = all_cell_types
+ proxy.Entity = all_cell_types
+ proxy.UpdatePipeline()
+
+
+def select_cells_with_data(proxy, on_points=None, on_cells=None):
+ """Select cell types with data.
+
+ Only cell types with data for the given fields will be selected.
+ If no fields defined (neither on points nor on cells) only cell
+ types with data for even one field (from available) will be selected.
+
+ """
+ if not hasattr(proxy, 'Entity'):
+ return
+
+ #all_cell_types = proxy.CellTypes.Available
+ all_cell_types = proxy.Entity.Available
+ all_arrays = list(proxy.CellArrays.GetData())
+ all_arrays.extend(proxy.PointArrays.GetData())
+
+ if not all_arrays:
+ file_name = proxy.FileName.split(os.sep)[-1]
+ print "Warning: " + file_name + " doesn't contain any data array."
+
+ # List of cell types to be selected
+ cell_types_on = []
+
+ for cell_type in all_cell_types:
+ #proxy.CellTypes = [cell_type]
+ proxy.Entity = [cell_type]
+ proxy.UpdatePipeline()
+
+ cell_arrays = proxy.GetCellDataInformation().keys()
+ point_arrays = proxy.GetPointDataInformation().keys()
+
+ if on_points or on_cells:
+ if on_points is None:
+ on_points = []
+ if on_cells is None:
+ on_cells = []
+
+ if (all(array in cell_arrays for array in on_cells) and
+ all(array in point_arrays for array in on_points)):
+ # Add cell type to the list
+ cell_types_on.append(cell_type)
+ else:
+ in_arrays = lambda array: ((array in cell_arrays) or
+ (array in point_arrays))
+ if any(in_arrays(array) for array in all_arrays):
+ cell_types_on.append(cell_type)
+
+ # Select cell types
+ #proxy.CellTypes = cell_types_on
+ proxy.Entity = cell_types_on
+ proxy.UpdatePipeline()
+
+
+def extract_groups_for_field(proxy, field_name, field_entity, force=False):
+ """Exctract only groups which have the field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ field_name: the field name
+ field_entity: the field entity
+ force: if True - ExtractGroup object will be created in any case
+
+ Returns:
+ ExtractGroup object: if not all groups have the field or
+ the force argument is true
+ The initial proxy: if no groups had been filtered.
+
+ """
+ source = proxy
+
+ # Remember the state
+ initial_groups = list(proxy.Groups)
+
+ # Get data information for the field entity
+ entity_data_info = None
+ field_data = proxy.GetFieldDataInformation()
+
+ if field_name in field_data.keys():
+ entity_data_info = field_data
+ elif field_entity == EntityType.CELL:
+ entity_data_info = proxy.GetCellDataInformation()
+ elif field_entity == EntityType.NODE:
+ entity_data_info = proxy.GetPointDataInformation()
+
+ # Collect groups for extraction
+ groups_to_extract = []
+
+ for group in initial_groups:
+ proxy.Groups = [group]
+ proxy.UpdatePipeline()
+ if field_name in entity_data_info.keys():
+ groups_to_extract.append(group)
+
+ # Restore state
+ proxy.Groups = initial_groups
+ proxy.UpdatePipeline()
+
+ # Extract groups if necessary
+ if force or (len(groups_to_extract) < len(initial_groups)):
+ extract_group = pv.ExtractGroup(proxy)
+ extract_group.Groups = groups_to_extract
+ extract_group.UpdatePipeline()
+ source = extract_group
+
+ return source
+
+
+def if_possible(proxy, field_name, entity, prs_type):
+ """Check if the presentation creation is possible on the given field."""
+ result = True
+ if (prs_type == PrsTypeEnum.DEFORMEDSHAPE or
+ prs_type == PrsTypeEnum.DEFORMEDSHAPESCALARMAP or
+ prs_type == PrsTypeEnum.VECTORS or
+ prs_type == PrsTypeEnum.STREAMLINES):
+ nb_comp = get_nb_components(proxy, entity, field_name)
+ result = (nb_comp > 1)
+ elif (prs_type == PrsTypeEnum.GAUSSPOINTS):
+ result = (entity == EntityType.CELL or
+ field_name in proxy.QuadraturePointArrays.Available)
+ elif (prs_type == PrsTypeEnum.MESH):
+ result = len(get_group_names(proxy, field_name, entity)) > 0
+
+ return result
+
+
+def add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value):
+ """Add scalar bar with predefined properties."""
+ global _current_bar
+
+ # Construct bar title
+ title = "\n".join([field_name, str(time_value)])
+ if nb_components > 1:
+ title = "\n".join([title, vector_mode])
+
+ # Create scalar bar
+ scalar_bar = pv.CreateScalarBar(Enabled=1)
+ scalar_bar.Orientation = 'Vertical'
+ scalar_bar.Title = title
+ scalar_bar.LookupTable = lookup_table
+
+ # Set default properties same as in Post-Pro
+ scalar_bar.NumberOfLabels = 5
+ scalar_bar.AutomaticLabelFormat = 0
+ scalar_bar.LabelFormat = '%-#6.6g'
+ # Title
+ scalar_bar.TitleFontFamily = 'Arial'
+ scalar_bar.TitleFontSize = 8
+ scalar_bar.TitleBold = 1
+ scalar_bar.TitleItalic = 1
+ scalar_bar.TitleShadow = 1
+ # Labels
+ scalar_bar.LabelFontFamily = 'Arial'
+ scalar_bar.LabelFontSize = 8
+ scalar_bar.LabelBold = 1
+ scalar_bar.LabelItalic = 1
+ scalar_bar.LabelShadow = 1
+
+ # Add the scalar bar to the view
+ pv.GetRenderView().Representations.append(scalar_bar)
+
+ # Reassign the current bar
+ _current_bar = scalar_bar
+
+ return scalar_bar
+
+
+def get_bar():
+ """Get current scalar bar."""
+ global _current_bar
+
+ return _current_bar
+
+
+def get_lookup_table(field_name, nb_components, vector_mode='Magnitude'):
+ """Get lookup table for the given field."""
+ lookup_table = pv.GetLookupTableForArray(field_name, nb_components)
+
+ if vector_mode == 'Magnitude':
+ lookup_table.VectorMode = vector_mode
+ elif vector_mode == 'X':
+ lookup_table.VectorMode = 'Component'
+ lookup_table.VectorComponent = 0
+ elif vector_mode == 'Y':
+ lookup_table.VectorMode = 'Component'
+ lookup_table.VectorComponent = 1
+ elif vector_mode == 'Z':
+ lookup_table.VectorMode = 'Component'
+ lookup_table.VectorComponent = 2
+ else:
+ raise ValueError("Incorrect vector mode: " + vector_mode)
+
+ lookup_table.Discretize = 0
+ lookup_table.ColorSpace = 'HSV'
+ lookup_table.LockScalarRange = 0
+
+ return lookup_table
+
+
+def get_group_mesh_name(full_group_name):
+ """Return mesh name of the group by its full name."""
+ aList = full_group_name.split('/')
+ if len(aList) >= 2 :
+ group_name = full_group_name.split('/')[1]
+ return group_name
+
+
+def get_group_entity(full_group_name):
+ """Return entity type of the group by its full name."""
+ aList = full_group_name.split('/')
+ if len(aList) >= 3 :
+ entity_name = full_group_name.split('/')[2]
+ entity = EntityType.get_type(entity_name)
+ return entity
+
+
+def get_group_short_name(full_group_name):
+ """Return short name of the group by its full name."""
+ aList = full_group_name.split('/')
+ if len(aList) >= 4 :
+ short_name = full_group_name.split('/')[3]
+ return short_name
+
+
+def get_mesh_names(proxy):
+ """Return all mesh names in the given proxy as a set."""
+ groups = proxy.Groups.Available
+ mesh_names = set([get_group_mesh_name(item) for item in groups])
+
+ return mesh_names
+
+
+def get_group_names(proxy, mesh_name, entity, wo_nogroups=False):
+ """Return full names of all groups of the given entity type
+ from the mesh with the given name as a list.
+ """
+ groups = proxy.Groups.Available
+
+ condition = lambda item: (get_group_mesh_name(item) == mesh_name and
+ get_group_entity(item) == entity)
+ group_names = [item for item in groups if condition(item)]
+
+ if wo_nogroups:
+ # Remove "No_Group" group
+ not_no_group = lambda item: get_group_short_name(item) != "No_Group"
+ group_names = filter(not_no_group, group_names)
+
+ return group_names
+
+
+def get_time(proxy, timestamp_nb):
+ """Get time value by timestamp number."""
+ # Check timestamp number
+ timestamps = []
+
+ if (hasattr(proxy, 'TimestepValues')):
+ timestamps = proxy.TimestepValues.GetData()
+ elif (hasattr(proxy.Input, 'TimestepValues')):
+ timestamps = proxy.Input.TimestepValues.GetData()
+
+ if ((timestamp_nb - 1) not in xrange(len(timestamps))):
+ raise ValueError("Timestamp number is out of range: " + str(timestamp_nb))
+
+ # Return time value
+ return timestamps[timestamp_nb - 1]
+
+
+def create_prs(prs_type, proxy, field_entity, field_name, timestamp_nb):
+ """Auxiliary function.
+
+ Build presentation of the given type on the given field and
+ timestamp number.
+ Set the presentation properties like visu.CreatePrsForResult() do.
+
+ """
+ prs = None
+
+ if prs_type == PrsTypeEnum.SCALARMAP:
+ prs = ScalarMapOnField(proxy, field_entity, field_name, timestamp_nb)
+ elif prs_type == PrsTypeEnum.CUTPLANES:
+ prs = CutPlanesOnField(proxy, field_entity, field_name, timestamp_nb,
+ orientation=Orientation.ZX)
+ elif prs_type == PrsTypeEnum.CUTLINES:
+ prs = CutLinesOnField(proxy, field_entity, field_name, timestamp_nb,
+ orientation1=Orientation.XY,
+ orientation2=Orientation.ZX)
+ elif prs_type == PrsTypeEnum.DEFORMEDSHAPE:
+ prs = DeformedShapeOnField(proxy, field_entity,
+ field_name, timestamp_nb)
+ elif prs_type == PrsTypeEnum.DEFORMEDSHAPESCALARMAP:
+ prs = DeformedShapeAndScalarMapOnField(proxy, field_entity,
+ field_name, timestamp_nb)
+ elif prs_type == PrsTypeEnum.VECTORS:
+ prs = VectorsOnField(proxy, field_entity, field_name, timestamp_nb)
+ elif prs_type == PrsTypeEnum.PLOT3D:
+ prs = Plot3DOnField(proxy, field_entity, field_name, timestamp_nb)
+ elif prs_type == PrsTypeEnum.ISOSURFACES:
+ prs = IsoSurfacesOnField(proxy, field_entity, field_name, timestamp_nb)
+ elif prs_type == PrsTypeEnum.GAUSSPOINTS:
+ prs = GaussPointsOnField(proxy, field_entity, field_name, timestamp_nb)
+ elif prs_type == PrsTypeEnum.STREAMLINES:
+ prs = StreamLinesOnField(proxy, field_entity, field_name, timestamp_nb)
+ else:
+ raise ValueError("Unexistent presentation type.")
+
+ return prs
+
+
+# Functions for building Post-Pro presentations
+def ScalarMapOnField(proxy, entity, field_name, timestamp_nb,
+ vector_mode='Magnitude'):
+ """Creates Scalar Map presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Scalar Map as representation object.
+
+ """
+ # We don't need mesh parts with no data on them
+ if entity == EntityType.NODE:
+ select_cells_with_data(proxy, on_points=[field_name])
+ else:
+ select_cells_with_data(proxy, on_cells=[field_name])
+
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Extract only groups with data for the field
+ new_proxy = extract_groups_for_field(proxy, field_name, entity,
+ force=True)
+
+ # Get Scalar Map representation object
+ scalarmap = pv.GetRepresentation(new_proxy)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+ # Set properties
+ scalarmap.ColorAttributeType = EntityType.get_pvtype(entity)
+ scalarmap.ColorArrayName = field_name
+ scalarmap.LookupTable = lookup_table
+
+ # Add scalar bar
+ bar_title = field_name + ", " + str(time_value)
+ if (nb_components > 1):
+ bar_title += "\n" + vector_mode
+ add_scalar_bar(field_name, nb_components, vector_mode,
+ lookup_table, time_value)
+
+ return scalarmap
+
+
+def CutPlanesOnField(proxy, entity, field_name, timestamp_nb,
+ nb_planes=10, orientation=Orientation.YZ,
+ angle1=0, angle2=0,
+ displacement=0.5, vector_mode='Magnitude'):
+ """Creates Cut Planes presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ nb_planes: number of cutting planes
+ orientation: cutting planes orientation in 3D space
+ angle1: rotation of the planes in 3d space around the first axis of the
+ selected orientation (X axis for XY, Y axis for YZ, Z axis for ZX).
+ The angle of rotation is set in degrees. Acceptable range: [-45, 45].
+ angle2: rotation of the planes in 3d space around the second axis of the
+ selected orientation. Acceptable range: [-45, 45].
+ displacement: the displacement of the planes into one or another side
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Cut Planes as representation object.
+
+ """
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Create slice filter
+ slice_filter = pv.Slice(proxy)
+ slice_filter.SliceType = "Plane"
+
+ # Set cut planes normal
+ normal = get_normal_by_orientation(orientation,
+ radians(angle1), radians(angle2))
+ slice_filter.SliceType.Normal = normal
+
+ # Set cut planes positions
+ positions = get_positions(nb_planes, normal,
+ get_bounds(proxy), displacement)
+ slice_filter.SliceOffsetValues = positions
+
+ # Get Cut Planes representation object
+ cut_planes = pv.GetRepresentation(slice_filter)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ cut_planes.ColorAttributeType = EntityType.get_pvtype(entity)
+ cut_planes.ColorArrayName = field_name
+ cut_planes.LookupTable = lookup_table
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return cut_planes
+
+
+def CutLinesOnField(proxy, entity, field_name, timestamp_nb,
+ nb_lines=10,
+ orientation1=Orientation.XY,
+ base_angle1=0, base_angle2=0,
+ orientation2=Orientation.YZ,
+ cut_angle1=0, cut_angle2=0,
+ displacement1=0.5, displacement2=0.5,
+ generate_curves=False,
+ vector_mode='Magnitude'):
+ """Creates Cut Lines presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ nb_lines: number of lines
+ orientation1: base plane orientation in 3D space
+ base_angle1: rotation of the base plane in 3d space around the first
+ axis of the orientation1 (X axis for XY, Y axis for YZ, Z axis for ZX).
+ The angle of rotation is set in degrees. Acceptable range: [-45, 45].
+ base_angle2: rotation of the base plane in 3d space around the second
+ axis of the orientation1. Acceptable range: [-45, 45].
+ orientation2: cutting planes orientation in 3D space
+ cut_angle1: rotation of the cut planes in 3d space around the first
+ axis of the orientation2. Acceptable range: [-45, 45].
+ cut_angle2: rotation of the cuting planes in 3d space around the second
+ axis of the orientation2. Acceptable range: [-45, 45].
+ displacement1: base plane displacement
+ displacement2: cutting planes displacement
+ generate_curves: if true, 'PlotOverLine' filter will be created
+ for each cut line
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Cut Lines as representation object if generate_curves == False,
+ (Cut Lines as representation object, list of 'PlotOverLine') otherwise
+
+ """
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Create base plane
+ base_plane = pv.Slice(proxy)
+ base_plane.SliceType = "Plane"
+
+ # Set base plane normal
+ base_normal = get_normal_by_orientation(orientation1,
+ radians(base_angle1),
+ radians(base_angle2))
+ base_plane.SliceType.Normal = base_normal
+
+ # Set base plane position
+ base_position = get_positions(1, base_normal,
+ get_bounds(proxy), displacement1)
+ base_plane.SliceOffsetValues = base_position
+
+ # Check base plane
+ base_plane.UpdatePipeline()
+ if (base_plane.GetDataInformation().GetNumberOfCells() == 0):
+ base_plane = proxy
+
+ # Create cutting planes
+ cut_planes = pv.Slice(base_plane)
+ cut_planes.SliceType = "Plane"
+
+ # Set cutting planes normal and get positions
+ cut_normal = get_normal_by_orientation(orientation2,
+ radians(cut_angle1),
+ radians(cut_angle2))
+ cut_planes.SliceType.Normal = cut_normal
+
+ # Set cutting planes position
+ cut_positions = get_positions(nb_lines, cut_normal,
+ get_bounds(base_plane), displacement2)
+
+ # Generate curves
+ curves = []
+ if generate_curves:
+ index = 0
+ for pos in cut_positions:
+ # Get points for plot over line objects
+ cut_planes.SliceOffsetValues = pos
+ cut_planes.UpdatePipeline()
+ bounds = get_bounds(cut_planes)
+ point1 = [bounds[0], bounds[2], bounds[4]]
+ point2 = [bounds[1], bounds[3], bounds[5]]
+
+ # Create plot over line filter
+ pol = pv.PlotOverLine(cut_planes,
+ Source="High Resolution Line Source")
+ pv.RenameSource('Y' + str(index), pol)
+ pol.Source.Point1 = point1
+ pol.Source.Point2 = point2
+ pol.UpdatePipeline()
+ curves.append(pol)
+
+ index += 1
+
+ cut_planes.SliceOffsetValues = cut_positions
+ cut_planes.UpdatePipeline()
+
+ # Get Cut Lines representation object
+ cut_lines = pv.GetRepresentation(cut_planes)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ cut_lines.ColorAttributeType = EntityType.get_pvtype(entity)
+ cut_lines.ColorArrayName = field_name
+ cut_lines.LookupTable = lookup_table
+
+ # Set wireframe represenatation mode
+ cut_lines.Representation = 'Wireframe'
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ result = cut_lines
+ # If curves were generated return tuple (cut lines, list of curves)
+ if curves:
+ result = cut_lines, curves
+
+ return result
+
+
+def CutSegmentOnField(proxy, entity, field_name, timestamp_nb,
+ point1, point2, vector_mode='Magnitude'):
+ """Creates Cut Segment presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ point1: set the first point of the segment (as [x, y, z])
+ point1: set the second point of the segment (as [x, y, z])
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Cut Segment as 3D representation object.
+
+ """
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Create plot over line filter
+ pol = pv.PlotOverLine(proxy, Source="High Resolution Line Source")
+ pol.Source.Point1 = point1
+ pol.Source.Point2 = point2
+ pol.UpdatePipeline()
+
+ # Get Cut Segment representation object
+ cut_segment = pv.GetRepresentation(pol)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ cut_segment.ColorAttributeType = EntityType.get_pvtype(entity)
+ cut_segment.ColorArrayName = field_name
+ cut_segment.LookupTable = lookup_table
+
+ # Set wireframe represenatation mode
+ cut_segment.Representation = 'Wireframe'
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return cut_segment
+
+
+def VectorsOnField(proxy, entity, field_name, timestamp_nb,
+ scale_factor=None,
+ glyph_pos=GlyphPos.TAIL, glyph_type='2D Glyph',
+ is_colored=False, vector_mode='Magnitude'):
+ """Creates Vectors presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ scale_factor: scale factor
+ glyph_pos: the position of glyphs
+ glyph_type: the type of glyphs
+ is_colored: this option allows to color the presentation according to
+ the corresponding data array values
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Vectors as representation object.
+
+ """
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Extract only groups with data for the field
+ new_proxy = extract_groups_for_field(proxy, field_name, entity)
+ source = new_proxy
+
+ # Cell centers
+ if is_data_on_cells(proxy, field_name):
+ cell_centers = pv.CellCenters(source)
+ cell_centers.VertexCells = 1
+ source = cell_centers
+
+ vector_array = field_name
+ # If the given vector array has only 2 components, add the third one
+ if nb_components == 2:
+ calc = get_add_component_calc(source, EntityType.NODE, field_name)
+ vector_array = calc.ResultArrayName
+ source = calc
+
+ # Glyph
+ glyph = pv.Glyph(source)
+ glyph.Vectors = vector_array
+ glyph.ScaleMode = 'vector'
+ glyph.MaskPoints = 0
+
+ # Set glyph type
+ glyph.GlyphType = glyph_type
+ if glyph_type == '2D Glyph':
+ glyph.GlyphType.GlyphType = 'Arrow'
+ elif glyph_type == 'Cone':
+ glyph.GlyphType.Resolution = 7
+ glyph.GlyphType.Height = 2
+ glyph.GlyphType.Radius = 0.2
+
+ # Set glyph position if possible
+ if glyph.GlyphType.GetProperty("Center"):
+ if (glyph_pos == GlyphPos.TAIL):
+ glyph.GlyphType.Center = [0.5, 0.0, 0.0]
+ elif (glyph_pos == GlyphPos.HEAD):
+ glyph.GlyphType.Center = [-0.5, 0.0, 0.0]
+ elif (glyph_pos == GlyphPos.CENTER):
+ glyph.GlyphType.Center = [0.0, 0.0, 0.0]
+
+ if scale_factor is not None:
+ glyph.SetScaleFactor = scale_factor
+ else:
+ def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE,
+ new_proxy, entity, field_name)
+ glyph.SetScaleFactor = def_scale
+
+ glyph.UpdatePipeline()
+
+ # Get Vectors representation object
+ vectors = pv.GetRepresentation(glyph)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ if (is_colored):
+ vectors.ColorArrayName = 'GlyphVector'
+ else:
+ vectors.ColorArrayName = ''
+ vectors.LookupTable = lookup_table
+
+ vectors.LineWidth = 1.0
+
+ # Set wireframe represenatation mode
+ vectors.Representation = 'Wireframe'
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return vectors
+
+
+def DeformedShapeOnField(proxy, entity, field_name,
+ timestamp_nb,
+ scale_factor=None, is_colored=False,
+ vector_mode='Magnitude'):
+ """Creates Defromed Shape presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ scale_factor: scale factor of the deformation
+ is_colored: this option allows to color the presentation according to
+ the corresponding data array values
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Defromed Shape as representation object.
+
+ """
+ # We don't need mesh parts with no data on them
+ if entity == EntityType.NODE:
+ select_cells_with_data(proxy, on_points=[field_name])
+ else:
+ select_cells_with_data(proxy, on_cells=[field_name])
+
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Extract only groups with data for the field
+ new_proxy = extract_groups_for_field(proxy, field_name, entity)
+
+ # Do merge
+ source = pv.MergeBlocks(new_proxy)
+
+ # Cell data to point data
+ if is_data_on_cells(proxy, field_name):
+ cell_to_point = pv.CellDatatoPointData()
+ cell_to_point.PassCellData = 1
+ source = cell_to_point
+
+ vector_array = field_name
+ # If the given vector array has only 2 components, add the third one
+ if nb_components == 2:
+ calc = get_add_component_calc(source, EntityType.NODE, field_name)
+ vector_array = calc.ResultArrayName
+ source = calc
+
+ # Warp by vector
+ warp_vector = pv.WarpByVector(source)
+ warp_vector.Vectors = [vector_array]
+ if scale_factor is not None:
+ warp_vector.ScaleFactor = scale_factor
+ else:
+ def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE,
+ proxy, entity, field_name)
+ warp_vector.ScaleFactor = def_scale
+
+ # Get Deformed Shape representation object
+ defshape = pv.GetRepresentation(warp_vector)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ if is_colored:
+ defshape.ColorAttributeType = EntityType.get_pvtype(entity)
+ defshape.ColorArrayName = field_name
+ else:
+ defshape.ColorArrayName = ''
+ defshape.LookupTable = lookup_table
+
+ # Set wireframe represenatation mode
+ defshape.Representation = 'Wireframe'
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return defshape
+
+
+def DeformedShapeAndScalarMapOnField(proxy, entity, field_name,
+ timestamp_nb,
+ scale_factor=None,
+ scalar_entity=None,
+ scalar_field_name=None,
+ vector_mode='Magnitude'):
+ """Creates Defromed Shape And Scalar Map presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ scale_factor: scale factor of the deformation
+ scalar_entity: scalar field entity
+ scalar_field_name: scalar field, i.e. the field for coloring
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Defromed Shape And Scalar Map as representation object.
+
+ """
+ # We don't need mesh parts with no data on them
+ on_points = []
+ on_cells = []
+
+ if entity == EntityType.NODE:
+ on_points.append(field_name)
+ else:
+ on_cells.append(field_name)
+
+ if scalar_entity and scalar_field_name:
+ if scalar_entity == EntityType.NODE:
+ on_points.append(scalar_field_name)
+ else:
+ on_cells.append(scalar_field_name)
+
+ select_cells_with_data(proxy, on_points, on_cells)
+
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Set scalar field by default
+ scalar_field_entity = scalar_entity
+ scalar_field = scalar_field_name
+ if (scalar_field_entity is None) or (scalar_field is None):
+ scalar_field_entity = entity
+ scalar_field = field_name
+
+ # Extract only groups with data for the field
+ new_proxy = extract_groups_for_field(proxy, field_name, entity)
+
+ # Do merge
+ source = pv.MergeBlocks(new_proxy)
+
+ # Cell data to point data
+ if is_data_on_cells(proxy, field_name):
+ cell_to_point = pv.CellDatatoPointData(source)
+ cell_to_point.PassCellData = 1
+ source = cell_to_point
+
+ vector_array = field_name
+ # If the given vector array has only 2 components, add the third one
+ if nb_components == 2:
+ calc = get_add_component_calc(source, EntityType.NODE, field_name)
+ vector_array = calc.ResultArrayName
+ source = calc
+
+ # Warp by vector
+ warp_vector = pv.WarpByVector(source)
+ warp_vector.Vectors = [vector_array]
+ if scale_factor is not None:
+ warp_vector.ScaleFactor = scale_factor
+ else:
+ def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE,
+ new_proxy, entity, field_name)
+ warp_vector.ScaleFactor = def_scale
+
+ # Get Defromed Shape And Scalar Map representation object
+ defshapemap = pv.GetRepresentation(warp_vector)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(scalar_field, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, scalar_field_entity,
+ scalar_field, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ defshapemap.ColorArrayName = scalar_field
+ defshapemap.LookupTable = lookup_table
+ defshapemap.ColorAttributeType = EntityType.get_pvtype(scalar_field_entity)
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return defshapemap
+
+
+def Plot3DOnField(proxy, entity, field_name, timestamp_nb,
+ orientation=Orientation.AUTO,
+ angle1=0, angle2=0,
+ position=0.5, is_relative=True,
+ scale_factor=None,
+ is_contour=False, nb_contours=32,
+ vector_mode='Magnitude'):
+ """Creates Plot 3D presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ orientation: the cut plane plane orientation in 3D space, if
+ the input is planar - will not be taken into account
+ angle1: rotation of the cut plane in 3d space around the first axis
+ of the selected orientation (X axis for XY, Y axis for YZ,
+ Z axis for ZX).
+ The angle of rotation is set in degrees. Acceptable range: [-45, 45].
+ angle2: rotation of the cut plane in 3d space around the second axis
+ of the selected orientation. Acceptable range: [-45, 45].
+ position: position of the cut plane in the object (ranging from 0 to 1).
+ The value 0.5 corresponds to cutting by halves.
+ is_relative: defines if the cut plane position is relative or absolute
+ scale_factor: deformation scale factor
+ is_contour: if True - Plot 3D will be represented with a set of contours,
+ otherwise - Plot 3D will be represented with a smooth surface
+ nb_contours: number of contours, applied if is_contour is True
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Plot 3D as representation object.
+
+ """
+ # We don't need mesh parts with no data on them
+ if entity == EntityType.NODE:
+ select_cells_with_data(proxy, on_points=[field_name])
+ else:
+ select_cells_with_data(proxy, on_cells=[field_name])
+
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Extract only groups with data for the field
+ new_proxy = extract_groups_for_field(proxy, field_name, entity)
+
+ # Do merge
+ merge_blocks = pv.MergeBlocks(new_proxy)
+ merge_blocks.UpdatePipeline()
+
+ poly_data = None
+
+ # Cutting plane
+
+ # Define orientation if necessary (auto mode)
+ plane_orientation = orientation
+ if (orientation == Orientation.AUTO):
+ plane_orientation = get_orientation(proxy)
+
+ # Get cutting plane normal
+ normal = None
+
+ if (not is_planar_input(proxy)):
+ normal = get_normal_by_orientation(plane_orientation,
+ radians(angle1), radians(angle2))
+
+ # Create slice filter
+ slice_filter = pv.Slice(merge_blocks)
+ slice_filter.SliceType = "Plane"
+
+ # Set cutting plane normal
+ slice_filter.SliceType.Normal = normal
+
+ # Set cutting plane position
+ if (is_relative):
+ base_position = get_positions(1, normal,
+ get_bounds(proxy), position)
+ slice_filter.SliceOffsetValues = base_position
+ else:
+ slice_filter.SliceOffsetValues = position
+
+ slice_filter.UpdatePipeline()
+ poly_data = slice_filter
+ else:
+ normal = get_normal_by_orientation(plane_orientation, 0, 0)
+
+ use_normal = 0
+ # Geometry filter
+ if not poly_data or poly_data.GetDataInformation().GetNumberOfCells() == 0:
+ geometry_filter = pv.GeometryFilter(merge_blocks)
+ poly_data = geometry_filter
+ use_normal = 1 # TODO(MZN): workaround
+
+ warp_scalar = None
+ plot3d = None
+ source = poly_data
+
+ if is_data_on_cells(poly_data, field_name):
+ # Cell data to point data
+ cell_to_point = pv.CellDatatoPointData(poly_data)
+ cell_to_point.PassCellData = 1
+ source = cell_to_point
+
+ scalars = ['POINTS', field_name]
+
+ # Transform vector array to scalar array if necessary
+ if (nb_components > 1):
+ calc = get_calc_magnitude(source, EntityType.NODE, field_name)
+ scalars = ['POINTS', calc.ResultArrayName]
+ source = calc
+
+ # Warp by scalar
+ warp_scalar = pv.WarpByScalar(source)
+ warp_scalar.Scalars = scalars
+ warp_scalar.Normal = normal
+ warp_scalar.UseNormal = use_normal
+ if scale_factor is not None:
+ warp_scalar.ScaleFactor = scale_factor
+ else:
+ def_scale = get_default_scale(PrsTypeEnum.PLOT3D,
+ proxy, entity, field_name)
+ warp_scalar.ScaleFactor = def_scale
+
+ warp_scalar.UpdatePipeline()
+ source = warp_scalar
+
+ if (is_contour):
+ # Contours
+ contour = pv.Contour(warp_scalar)
+ contour.PointMergeMethod = "Uniform Binning"
+ contour.ContourBy = ['POINTS', field_name]
+ scalar_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ contour.Isosurfaces = get_contours(scalar_range, nb_contours)
+ contour.UpdatePipeline()
+ source = contour
+
+ # Get Plot 3D representation object
+ plot3d = pv.GetRepresentation(source)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ plot3d.ColorAttributeType = EntityType.get_pvtype(entity)
+ plot3d.ColorArrayName = field_name
+ plot3d.LookupTable = lookup_table
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return plot3d
+
+
+def IsoSurfacesOnField(proxy, entity, field_name, timestamp_nb,
+ custom_range=None, nb_surfaces=10,
+ is_colored=True, color=None, vector_mode='Magnitude'):
+ """Creates Iso Surfaces presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ custom_range: scalar range, if undefined the source range will be applied
+ nb_surfaces: number of surfaces, which will be generated
+ is_colored: this option allows to color the presentation according to
+ the corresponding data array values. If False - the presentation will
+ be one-coloured.
+ color: defines the presentation color as [R, G, B] triple. Taken into
+ account only if is_colored is False.
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Iso Surfaces as representation object.
+
+ """
+ # We don't need mesh parts with no data on them
+ if entity == EntityType.NODE:
+ select_cells_with_data(proxy, on_points=[field_name])
+ else:
+ select_cells_with_data(proxy, on_cells=[field_name])
+
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Extract only groups with data for the field
+ new_proxy = extract_groups_for_field(proxy, field_name, entity)
+
+ # Do merge
+ source = pv.MergeBlocks(new_proxy)
+
+ # Transform cell data into point data if necessary
+ if is_data_on_cells(proxy, field_name):
+ cell_to_point = pv.CellDatatoPointData(source)
+ cell_to_point.PassCellData = 1
+ source = cell_to_point
+
+ contour_by = ['POINTS', field_name]
+
+ # Transform vector array to scalar array if necessary
+ if (nb_components > 1):
+ calc = get_calc_magnitude(source, EntityType.NODE, field_name)
+ contour_by = ['POINTS', calc.ResultArrayName]
+ source = calc
+
+ # Contour filter settings
+ contour = pv.Contour(source)
+ contour.ComputeScalars = 1
+ contour.ContourBy = contour_by
+
+ # Specify the range
+ scalar_range = custom_range
+ if (scalar_range is None):
+ scalar_range = get_data_range(proxy, entity,
+ field_name, cut_off=True)
+
+ # Get contour values for the range
+ surfaces = get_contours(scalar_range, nb_surfaces)
+
+ # Set contour values
+ contour.Isosurfaces = surfaces
+
+ # Get Iso Surfaces representation object
+ isosurfaces = pv.GetRepresentation(contour)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set display properties
+ if (is_colored):
+ isosurfaces.ColorAttributeType = EntityType.get_pvtype(entity)
+ isosurfaces.ColorArrayName = field_name
+ else:
+ isosurfaces.ColorArrayName = ''
+ if color:
+ isosurfaces.DiffuseColor = color
+ isosurfaces.LookupTable = lookup_table
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return isosurfaces
+
+
+def GaussPointsOnField(proxy, entity, field_name,
+ timestamp_nb,
+ is_deformed=True, scale_factor=None,
+ is_colored=True, color=None,
+ primitive=GaussType.SPRITE,
+ is_proportional=True,
+ max_pixel_size=256,
+ multiplier=None, vector_mode='Magnitude'):
+ """Creates Gauss Points on the given field.
+
+ Arguments:
+
+ proxy: the pipeline object, containig data
+ entity: the field entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ is_deformed: defines whether the Gauss Points will be deformed or not
+ scale_factor -- the scale factor for deformation. Will be taken into
+ account only if is_deformed is True.
+ If not passed by user, default scale will be computed.
+ is_colored -- defines whether the Gauss Points will be multicolored,
+ using the corresponding data values
+ color: defines the presentation color as [R, G, B] triple. Taken into
+ account only if is_colored is False.
+ primitive: primitive type from GaussType
+ is_proportional: if True, the size of primitives will depends on
+ the gauss point value
+ max_pixel_size: the maximum sizr of the Gauss Points primitive in pixels
+ multiplier: coefficient between data values and the size of primitives
+ If not passed by user, default scale will be computed.
+ vector_mode: the mode of transformation of vector values into
+ scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude' - vector module;
+ 'X', 'Y', 'Z' - vector components.
+
+ Returns:
+ Gauss Points as representation object.
+
+ """
+ # We don't need mesh parts with no data on them
+ if entity == EntityType.NODE:
+ select_cells_with_data(proxy, on_points=[field_name])
+ else:
+ select_cells_with_data(proxy, on_cells=[field_name])
+
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ proxy.UpdatePipeline(time=time_value)
+
+ # Extract only groups with data for the field
+ source = extract_groups_for_field(proxy, field_name, entity)
+
+ # Quadrature point arrays
+ qp_arrays = proxy.QuadraturePointArrays.Available
+
+ # If no quadrature point array is passed, use cell centers
+ if field_name in qp_arrays:
+ generate_qp = pv.GenerateQuadraturePoints(source)
+ generate_qp.SelectSourceArray = ['CELLS', 'ELGA_Offset']
+ source = generate_qp
+ else:
+ # Cell centers
+ cell_centers = pv.CellCenters(source)
+ cell_centers.VertexCells = 1
+ source = cell_centers
+
+ source.UpdatePipeline()
+
+ # Check if deformation enabled
+ if is_deformed and nb_components > 1:
+ vector_array = field_name
+ # If the given vector array has only 2 components, add the third one
+ if nb_components == 2:
+ calc = get_add_component_calc(source,
+ EntityType.NODE, field_name)
+ vector_array = calc.ResultArrayName
+ source = calc
+
+ # Warp by vector
+ warp_vector = pv.WarpByVector(source)
+ warp_vector.Vectors = [vector_array]
+ if scale_factor is not None:
+ warp_vector.ScaleFactor = scale_factor
+ else:
+ def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE, proxy,
+ entity, field_name)
+ warp_vector.ScaleFactor = def_scale
+ warp_vector.UpdatePipeline()
+ source = warp_vector
+
+ # Get Gauss Points representation object
+ gausspnt = pv.GetRepresentation(source)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set display properties
+ if is_colored:
+ gausspnt.ColorAttributeType = EntityType.get_pvtype(entity)
+ gausspnt.ColorArrayName = field_name
+ else:
+ gausspnt.ColorArrayName = ''
+ if color:
+ gausspnt.DiffuseColor = color
+
+ gausspnt.LookupTable = lookup_table
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ # Set point sprite representation
+ gausspnt.Representation = 'Point Sprite'
+
+ # Point sprite settings
+ gausspnt.InterpolateScalarsBeforeMapping = 0
+ gausspnt.MaxPixelSize = max_pixel_size
+
+ # Render mode
+ gausspnt.RenderMode = GaussType.get_mode(primitive)
+
+ #if primitive == GaussType.SPRITE:
+ # Set texture
+ # TODO(MZN): replace with pvsimple high-level interface
+ # texture = sm.CreateProxy("textures", "SpriteTexture")
+ # alphamprop = texture.GetProperty("AlphaMethod")
+ # alphamprop.SetElement(0, 2) # Clamp
+ # alphatprop = texture.GetProperty("AlphaThreshold")
+ # alphatprop.SetElement(0, 63)
+ # maxprop = texture.GetProperty("Maximum")
+ # maxprop.SetElement(0, 255)
+ # texture.UpdateVTKObjects()
+
+ # gausspnt.Texture = texture
+ #gausspnt.Texture.AlphaMethod = 'Clamp'
+ #gausspnt.Texture.AlphaThreshold = 63
+ #gausspnt.Texture.Maximum= 255
+
+ # Proportional radius
+ gausspnt.RadiusUseScalarRange = 0
+ gausspnt.RadiusIsProportional = 0
+
+ if is_proportional:
+ mult = multiplier
+ if mult is None:
+ mult = abs(0.1 / data_range[1])
+
+ gausspnt.RadiusScalarRange = data_range
+ gausspnt.RadiusTransferFunctionEnabled = 1
+ gausspnt.RadiusMode = 'Scalar'
+ gausspnt.RadiusArray = ['POINTS', field_name]
+ if nb_components > 1:
+ v_comp = get_vector_component(vector_mode)
+ gausspnt.RadiusVectorComponent = v_comp
+ gausspnt.RadiusTransferFunctionMode = 'Table'
+ gausspnt.RadiusScalarRange = data_range
+ gausspnt.RadiusUseScalarRange = 1
+ gausspnt.RadiusIsProportional = 1
+ gausspnt.RadiusProportionalFactor = mult
+ else:
+ gausspnt.RadiusTransferFunctionEnabled = 0
+ gausspnt.RadiusMode = 'Constant'
+ gausspnt.RadiusArray = ['POINTS', 'Constant Radius']
+
+ return gausspnt
+
+def GaussPointsOnField1(proxy, entity, field_name,
+ timestamp_nb,
+ is_colored=True, color=None,
+ primitive=GaussType.SPHERE,
+ is_proportional=True,
+ max_pixel_size=256,
+ multiplier=None,
+ vector_mode='Magnitude'):
+ """Creates Gauss Points on the given field. Use GaussPoints() Paraview interface.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the field entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ is_colored -- defines whether the Gauss Points will be multicolored,
+ using the corresponding data values
+ color: defines the presentation color as [R, G, B] triple. Taken into
+ account only if is_colored is False.
+ primitive: primitive type from GaussType
+ is_proportional: if True, the size of primitives will depends on
+ the gauss point value
+ max_pixel_size: the maximum sizr of the Gauss Points primitive in pixels
+ multiplier: coefficient between data values and the size of primitives
+ If not passed by user, default scale will be computed.
+ vector_mode: the mode of transformation of vector values into
+ scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude' - vector module;
+ 'X', 'Y', 'Z' - vector components.
+
+ Returns:
+ Gauss Points as representation object.
+
+ """
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ proxy.UpdatePipeline(time=time_value)
+
+ # Create Gauss Points object
+ source = pv.GaussPoints(proxy)
+ source.UpdatePipeline()
+
+ # Get Gauss Points representation object
+ gausspnt = pv.GetRepresentation(source)
+
+ # Get lookup table
+ entity_data_info = None
+ point_data_info = source.GetPointDataInformation()
+ if field_name in point_data_info.keys():
+ entity_data_info = point_data_info
+ else:
+ entity_data_info = source.GetCellDataInformation()
+ nb_components = entity_data_info[field_name].GetNumberOfComponents()
+
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set display properties
+ if is_colored:
+ gausspnt.ColorAttributeType = EntityType.get_pvtype(entity)
+ gausspnt.ColorArrayName = field_name
+ else:
+ gausspnt.ColorArrayName = ''
+ if color:
+ gausspnt.DiffuseColor = color
+
+ gausspnt.LookupTable = lookup_table
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ # Set point sprite representation
+ gausspnt.Representation = 'Point Sprite'
+
+ # Point sprite settings
+ gausspnt.InterpolateScalarsBeforeMapping = 0
+ gausspnt.MaxPixelSize = max_pixel_size
+
+ # Render mode
+ gausspnt.RenderMode = GaussType.get_mode(primitive)
+
+ #if primitive == GaussType.SPRITE:
+ # Set texture
+ # TODO(MZN): replace with pvsimple high-level interface
+ # texture = sm.CreateProxy("textures", "SpriteTexture")
+ # alphamprop = texture.GetProperty("AlphaMethod")
+ # alphamprop.SetElement(0, 2) # Clamp
+ # alphatprop = texture.GetProperty("AlphaThreshold")
+ # alphatprop.SetElement(0, 63)
+ # maxprop = texture.GetProperty("Maximum")
+ # maxprop.SetElement(0, 255)
+ # texture.UpdateVTKObjects()
+
+ # gausspnt.Texture = texture
+ #gausspnt.Texture.AlphaMethod = 'Clamp'
+ #gausspnt.Texture.AlphaThreshold = 63
+ #gausspnt.Texture.Maximum= 255
+
+ # Proportional radius
+ gausspnt.RadiusUseScalarRange = 0
+ gausspnt.RadiusIsProportional = 0
+
+ if is_proportional:
+ mult = multiplier
+ if mult is None:
+ mult = abs(0.1 / data_range[1])
+
+ gausspnt.RadiusScalarRange = data_range
+ gausspnt.RadiusTransferFunctionEnabled = 1
+ gausspnt.RadiusMode = 'Scalar'
+ gausspnt.RadiusArray = ['POINTS', field_name]
+ if nb_components > 1:
+ v_comp = get_vector_component(vector_mode)
+ gausspnt.RadiusVectorComponent = v_comp
+ gausspnt.RadiusTransferFunctionMode = 'Table'
+ gausspnt.RadiusScalarRange = data_range
+ gausspnt.RadiusUseScalarRange = 1
+ gausspnt.RadiusIsProportional = 1
+ gausspnt.RadiusProportionalFactor = mult
+ else:
+ gausspnt.RadiusTransferFunctionEnabled = 0
+ gausspnt.RadiusMode = 'Constant'
+ gausspnt.RadiusArray = ['POINTS', 'Constant Radius']
+
+ return gausspnt
+
+def StreamLinesOnField(proxy, entity, field_name, timestamp_nb,
+ direction='BOTH', is_colored=False, color=None,
+ vector_mode='Magnitude'):
+ """Creates Stream Lines presentation on the given field.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ entity: the entity type from PrsTypeEnum
+ field_name: the field name
+ timestamp_nb: the number of time step (1, 2, ...)
+ direction: the stream lines direction ('FORWARD', 'BACKWARD' or 'BOTH')
+ is_colored: this option allows to color the presentation according to
+ the corresponding data values. If False - the presentation will
+ be one-coloured.
+ color: defines the presentation color as [R, G, B] triple. Taken into
+ account only if is_colored is False.
+ vector_mode: the mode of transformation of vector values
+ into scalar values, applicable only if the field contains vector values.
+ Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
+
+ Returns:
+ Stream Lines as representation object.
+
+ """
+ # We don't need mesh parts with no data on them
+ if entity == EntityType.NODE:
+ select_cells_with_data(proxy, on_points=[field_name])
+ else:
+ select_cells_with_data(proxy, on_cells=[field_name])
+
+ # Check vector mode
+ nb_components = get_nb_components(proxy, entity, field_name)
+ check_vector_mode(vector_mode, nb_components)
+
+ # Get time value
+ time_value = get_time(proxy, timestamp_nb)
+
+ # Set timestamp
+ pv.GetRenderView().ViewTime = time_value
+ pv.UpdatePipeline(time_value, proxy)
+
+ # Extract only groups with data for the field
+ new_proxy = extract_groups_for_field(proxy, field_name, entity)
+
+ # Do merge
+ source = pv.MergeBlocks(new_proxy)
+
+ # Cell data to point data
+ if is_data_on_cells(proxy, field_name):
+ cell_to_point = pv.CellDatatoPointData(source)
+ cell_to_point.PassCellData = 1
+ cell_to_point.UpdatePipeline()
+ source = cell_to_point
+
+ vector_array = field_name
+ # If the given vector array has only 2 components, add the third one
+ if nb_components == 2:
+ calc = get_add_component_calc(source, EntityType.NODE, field_name)
+ vector_array = calc.ResultArrayName
+ calc.UpdatePipeline()
+ source = calc
+
+ # Stream Tracer
+ stream = pv.StreamTracer(source)
+ stream.SeedType = "Point Source"
+ stream.Vectors = ['POINTS', vector_array]
+ stream.SeedType = "Point Source"
+ stream.IntegrationDirection = direction
+ stream.IntegratorType = 'Runge-Kutta 2'
+ stream.UpdatePipeline()
+
+ # Get Stream Lines representation object
+ if is_empty(stream):
+ return None
+ streamlines = pv.GetRepresentation(stream)
+
+ # Get lookup table
+ lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
+
+ # Set field range if necessary
+ data_range = get_data_range(new_proxy, entity,
+ field_name, vector_mode)
+ lookup_table.LockScalarRange = 1
+ lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
+
+ # Set properties
+ if is_colored:
+ streamlines.ColorAttributeType = EntityType.get_pvtype(entity)
+ streamlines.ColorArrayName = field_name
+ else:
+ streamlines.ColorArrayName = ''
+ if color:
+ streamlines.DiffuseColor = color
+
+ streamlines.LookupTable = lookup_table
+
+ # Add scalar bar
+ add_scalar_bar(field_name, nb_components,
+ vector_mode, lookup_table, time_value)
+
+ return streamlines
+
+
+def MeshOnEntity(proxy, mesh_name, entity):
+ """Creates submesh of the entity type for the mesh.
+
+ Arguments:
+ proxy -- the pipeline object, containig data
+ mesh_name -- the mesh name
+ entity -- the entity type
+
+ Returns:
+ Submesh as representation object of the given source.
+
+ """
+ # Select all cell types
+ select_all_cells(proxy)
+
+ # Get subset of groups on the given entity
+ subset = get_group_names(proxy, mesh_name, entity)
+
+ # Select only groups of the given entity type
+ proxy.Groups = subset
+ proxy.UpdatePipeline()
+
+ # Get representation object if the submesh is not empty
+ prs = None
+ if (proxy.GetDataInformation().GetNumberOfPoints() or
+ proxy.GetDataInformation().GetNumberOfCells()):
+ prs = pv.GetRepresentation(proxy)
+ prs.ColorArrayName = ''
+
+ return prs
+
+
+def MeshOnGroup(proxy, group_name):
+ """Creates submesh on the group.
+
+ Arguments:
+ proxy -- the pipeline object, containig data
+ group_name -- the full group name
+
+ Returns:
+ Representation object of the given source with single group
+ selected.
+
+ """
+ # Select all cell types
+ select_all_cells(proxy)
+
+ # Select only the group with the given name
+ one_group = [group_name]
+ proxy.Groups = one_group
+ proxy.UpdatePipeline()
+
+ # Get representation object if the submesh is not empty
+ prs = None
+
+ # Check if the group was set
+ if proxy.Groups.GetData() == one_group:
+ group_entity = get_group_entity(group_name)
+ # Check if the submesh is not empty
+ nb_items = 0
+ if group_entity == EntityType.NODE:
+ nb_items = proxy.GetDataInformation().GetNumberOfPoints()
+ elif group_entity == EntityType.CELL:
+ nb_items = proxy.GetDataInformation().GetNumberOfCells()
+
+ if nb_items:
+ prs = pv.GetRepresentation(proxy)
+ prs.ColorArrayName = ''
+
+ return prs
+
+
+def CreatePrsForFile(paravis_instance, file_name, prs_types,
+ picture_dir, picture_ext):
+ """Build presentations of the given types for the file.
+
+ Build presentations for all fields on all timestamps.
+
+ Arguments:
+ paravis_instance: ParaVis module instance object
+ file_name: full path to the MED file
+ prs_types: the list of presentation types to build
+ picture_dir: the directory path for saving snapshots
+ picture_ext: graphics files extension (determines file type)
+
+ """
+ # Import MED file
+ print "Import " + file_name.split(os.sep)[-1] + "..."
+
+ try:
+ paravis_instance.ImportFile(file_name)
+ proxy = pv.GetActiveSource()
+ if proxy is None:
+ print "FAILED"
+ else:
+ proxy.UpdatePipeline()
+ print "OK"
+ except:
+ print "FAILED"
+ else:
+ # Get view
+ view = pv.GetRenderView()
+
+ # Create required presentations for the proxy
+ CreatePrsForProxy(proxy, view, prs_types,
+ picture_dir, picture_ext)
+
+
+def CreatePrsForProxy(proxy, view, prs_types, picture_dir, picture_ext):
+ """Build presentations of the given types for all fields of the proxy.
+
+ Save snapshots in graphics files (type depends on the given extension).
+ Stores the files in the given directory.
+
+ Arguments:
+ proxy: the pipeline object, containig data
+ view: the render view
+ prs_types: the list of presentation types to build
+ picture_dir: the directory path for saving snapshots
+ picture_ext: graphics files extension (determines file type)
+
+ """
+ # List of the field names
+ field_names = list(proxy.PointArrays.GetData())
+ nb_on_nodes = len(field_names)
+ field_names.extend(proxy.CellArrays.GetData())
+
+ # Add path separator to the end of picture path if necessery
+ if not picture_dir.endswith(os.sep):
+ picture_dir += os.sep
+
+ # Mesh Presentation
+ if PrsTypeEnum.MESH in prs_types:
+ # Create Mesh presentation. Build all possible submeshes.
+
+ # Remember the current state
+ groups = list(proxy.Groups)
+
+ # Iterate on meshes
+ mesh_names = get_mesh_names(proxy)
+ for mesh_name in mesh_names:
+ # Build mesh on nodes and cells
+ for entity in (EntityType.NODE, EntityType.CELL):
+ entity_name = EntityType.get_name(entity)
+ if if_possible(proxy, mesh_name, entity, PrsTypeEnum.MESH):
+ print "Creating submesh on " + entity_name + " for '" + mesh_name + "' mesh... "
+ prs = MeshOnEntity(proxy, mesh_name, entity)
+ if prs is None:
+ print "FAILED"
+ continue
+ else:
+ print "OK"
+ # Construct image file name
+ pic_name = picture_dir + mesh_name + "_" + entity_name + "." + picture_ext
+
+ # Show and dump the presentation into a graphics file
+ process_prs_for_test(prs, view, pic_name, False)
+
+ # Build submesh on all groups of the mesh
+ mesh_groups = get_group_names(proxy, mesh_name,
+ entity, wo_nogroups=True)
+ for group in mesh_groups:
+ print "Creating submesh on group " + group + "... "
+ prs = MeshOnGroup(proxy, group)
+ if prs is None:
+ print "FAILED"
+ continue
+ else:
+ print "OK"
+ # Construct image file name
+ pic_name = picture_dir + group.replace('/', '_') + "." + picture_ext
+
+ # Show and dump the presentation into a graphics file
+ process_prs_for_test(prs, view, pic_name, False)
+
+ # Restore the state
+ proxy.Groups = groups
+ proxy.UpdatePipeline()
+
+ # Presentations on fields
+ for (i, field_name) in enumerate(field_names):
+ # Select only the current field:
+ # necessary for getting the right timestamps
+ cell_arrays = proxy.CellArrays.GetData()
+ point_arrays = proxy.PointArrays.GetData()
+ field_entity = None
+ if (i >= nb_on_nodes):
+ field_entity = EntityType.CELL
+ proxy.PointArrays.DeselectAll()
+ proxy.CellArrays = [field_name]
+ else:
+ field_entity = EntityType.NODE
+ proxy.CellArrays.DeselectAll()
+ proxy.PointArrays = [field_name]
+
+ # Get timestamps
+ proxy.UpdatePipelineInformation()
+ timestamps = proxy.TimestepValues.GetData()
+
+ # Restore fields selection state
+ proxy.CellArrays = cell_arrays
+ proxy.PointArrays = point_arrays
+ proxy.UpdatePipelineInformation()
+
+ for prs_type in prs_types:
+ # Ignore mesh presentation
+ if prs_type == PrsTypeEnum.MESH:
+ continue
+
+ # Get name of presentation type
+ prs_name = PrsTypeEnum.get_name(prs_type)
+
+ # Build the presentation if possible
+ possible = if_possible(proxy, field_name,
+ field_entity, prs_type)
+ if possible:
+ # Presentation type for graphics file name
+ f_prs_type = prs_name.replace(' ', '').upper()
+
+ for timestamp_nb in xrange(1, len(timestamps) + 1):
+ time = timestamps[timestamp_nb - 1]
+ print "Creating " + prs_name + " on " + field_name + ", time = " + str(time) + "... "
+ prs = create_prs(prs_type, proxy,
+ field_entity, field_name, timestamp_nb)
+ if prs is None:
+ print "FAILED"
+ continue
+ else:
+ print "OK"
+
+ # Construct image file name
+ pic_name = picture_dir + field_name + "_" + str(time) + "_" + f_prs_type + "." + picture_ext
+
+ # Show and dump the presentation into a graphics file
+ process_prs_for_test(prs, view, pic_name)
--- /dev/null
+# Copyright (C) 2010-2013 CEA/DEN, EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+r"""simple is a module for using paraview server manager in Python. It
+provides a simple convenience layer to functionality provided by the
+C++ classes wrapped to Python as well as the servermanager module.
+
+A simple example:
+ from paraview.simple import *
+
+ # Create a new sphere proxy on the active connection and register it
+ # in the sources group.
+ sphere = Sphere(ThetaResolution=16, PhiResolution=32)
+
+ # Apply a shrink filter
+ shrink = Shrink(sphere)
+
+ # Turn the visiblity of the shrink object on.
+ Show(shrink)
+
+ # Render the scene
+ Render()
+"""
+
+import paravisSM
+
+servermanager = paravisSM
+
+def enableMultiServer():
+ servermanager.enableMultiServer()
+
+def switchActiveConnection(newActiveConnection=None, ns=None):
+ if not ns:
+ ns = globals()
+ _remove_functions(ns)
+ servermanager.switchActiveConnection(newActiveConnection)
+ _add_functions(ns)
+
+def Disconnect(ns=None, force=True):
+ if servermanager.ActiveConnection and (force or servermanager.MultiServerConnections == None):
+ if ns:
+ _remove_functions(ns)
+ _remove_functions(globals())
+ if not servermanager.fromGUI:
+ servermanager.ProxyManager().DisableStateUpdateNotification()
+ servermanager.ProxyManager().UnRegisterProxies()
+ active_objects.view = None
+ active_objects.source = None
+ servermanager.Disconnect()
+ if not servermanager.fromGUI:
+ import gc
+ gc.collect()
+
+def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
+ """Creates a connection to a server. Example usage:
+ > Connect("amber") # Connect to a single server at default port
+ > Connect("amber", 12345) # Connect to a single server at port 12345
+ > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair"""
+ Disconnect(globals(), False)
+ connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
+ _add_functions(globals())
+
+ servermanager.ProxyManager().DisableStateUpdateNotification()
+ servermanager.ProxyManager().UpdateFromRemote()
+ tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
+ if not tk:
+ try:
+ tk = servermanager.misc.TimeKeeper()
+ servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
+ except AttributeError:
+ print "Error: Could not create TimeKeeper"
+
+ scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
+ if not scene:
+ try:
+ scene = AnimationScene()
+ scene.TimeKeeper = tk
+ except NameError:
+ print "Error: Could not create AnimationScene"
+
+ servermanager.ProxyManager().EnableStateUpdateNotification()
+ servermanager.ProxyManager().TriggerStateUpdate()
+
+ return connection
+
+def ReverseConnect(port=11111):
+ """Create a reverse connection to a server. Listens on port and waits for
+ an incoming connection from the server."""
+ Disconnect(globals(), False)
+ connection = servermanager.ReverseConnect(port)
+ _add_functions(globals())
+
+ servermanager.ProxyManager().DisableStateUpdateNotification()
+ servermanager.ProxyManager().UpdateFromRemote()
+ tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
+ if not tk:
+ tk = servermanager.misc.TimeKeeper()
+ servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
+
+ scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
+ if not scene:
+ scene = AnimationScene()
+ scene.TimeKeeper = tk
+
+ servermanager.ProxyManager().EnableStateUpdateNotification()
+ servermanager.ProxyManager().TriggerStateUpdate()
+
+ return connection
+
+def _create_view(view_xml_name):
+ "Creates and returns a 3D render view."
+ view = servermanager._create_view(view_xml_name)
+ servermanager.ProxyManager().RegisterProxy("views", \
+ "my_view%d" % _funcs_internals.view_counter, view)
+ active_objects.view = view
+ _funcs_internals.view_counter += 1
+
+ tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+ views = tk.Views
+ if not view in views:
+ views.append(view)
+ try:
+ scene = GetAnimationScene()
+ if not view in scene.ViewModules:
+ scene.ViewModules.append(view)
+ except servermanager.MissingProxy:
+ pass
+ return view
+
+def CreateRenderView():
+ return _create_view("RenderView")
+
+def CreateXYPlotView():
+ return _create_view("XYChartView")
+
+def CreateBarChartView():
+ return _create_view("XYBarChartView")
+
+def CreateComparativeRenderView():
+ return _create_view("ComparativeRenderView")
+
+def CreateComparativeXYPlotView():
+ return _create_view("ComparativeXYPlotView")
+
+def CreateComparativeBarChartView():
+ return _create_view("ComparativeBarChartView")
+
+def CreateParallelCoordinatesChartView():
+ return _create_view("ParallelCoordinatesChartView")
+
+def Create2DRenderView():
+ return _create_view("2DRenderView")
+
+def OpenDataFile(filename, **extraArgs):
+ """Creates a reader to read the give file, if possible.
+ This uses extension matching to determine the best reader possible.
+ If a reader cannot be identified, then this returns None."""
+ session = servermanager.ActiveConnection.Session
+ reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory()
+ if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
+ reader_factor.RegisterPrototypes(session, "sources")
+ first_file = filename
+ if type(filename) == list:
+ first_file = filename[0]
+ if not reader_factor.TestFileReadability(first_file, session):
+ msg = "File not readable: %s " % first_file
+ raise RuntimeError, msg
+ if not reader_factor.CanReadFile(first_file, session):
+ msg = "File not readable. No reader found for '%s' " % first_file
+ raise RuntimeError, msg
+ prototype = servermanager.ProxyManager().GetPrototypeProxy(
+ reader_factor.GetReaderGroup(), reader_factor.GetReaderName())
+ xml_name = paraview.make_name_valid(prototype.GetXMLLabel())
+ reader_func = _create_func(xml_name, servermanager.sources)
+ if prototype.GetProperty("FileNames"):
+ reader = reader_func(FileNames=filename, **extraArgs)
+ else :
+ reader = reader_func(FileName=filename, **extraArgs)
+ return reader
+
+def CreateWriter(filename, proxy=None, **extraArgs):
+ """Creates a writer that can write the data produced by the source proxy in
+ the given file format (identified by the extension). If no source is
+ provided, then the active source is used. This doesn't actually write the
+ data, it simply creates the writer and returns it."""
+ if not filename:
+ raise RuntimeError, "filename must be specified"
+ session = servermanager.ActiveConnection.Session
+ writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory()
+ if writer_factory.GetNumberOfRegisteredPrototypes() == 0:
+ writer_factory.RegisterPrototypes(session, "writers")
+ if not proxy:
+ proxy = GetActiveSource()
+ if not proxy:
+ raise RuntimeError, "Could not locate source to write"
+ writer_proxy = writer_factory.CreateWriter(filename, proxy.SMProxy, proxy.Port)
+ return servermanager._getPyProxy(writer_proxy)
+
+def GetRenderView():
+ """Returns the active view if there is one. Else creates and returns a new view."""
+ view = active_objects.view
+ if not view:
+ # it's possible that there's no active view, but a render view exists.
+ # If so, locate that and return it (before trying to create a new one).
+ view = servermanager.GetRenderView()
+ if not view:
+ view = CreateRenderView()
+ return view
+
+def GetRenderViews():
+ """Returns all render views as a list."""
+ return servermanager.GetRenderViews()
+
+def GetRepresentation(proxy=None, view=None):
+ """Given a pipeline object and view, returns the corresponding representation object.
+ If pipeline object and view are not specified, active objects are used."""
+ if not view:
+ view = active_objects.view
+ if not proxy:
+ proxy = active_objects.source
+ rep = servermanager.GetRepresentation(proxy, view)
+ if not rep:
+ rep = servermanager.CreateRepresentation(proxy, view)
+ servermanager.ProxyManager().RegisterProxy("representations", \
+ "my_representation%d" % _funcs_internals.rep_counter, rep)
+ _funcs_internals.rep_counter += 1
+ return rep
+
+def GetDisplayProperties(proxy=None, view=None):
+ """Given a pipeline object and view, returns the corresponding representation object.
+ If pipeline object and/or view are not specified, active objects are used."""
+ return GetRepresentation(proxy, view)
+
+def Show(proxy=None, view=None, **params):
+ """Turns the visibility of a given pipeline object on in the given view.
+ If pipeline object and/or view are not specified, active objects are used."""
+ if proxy == None:
+ proxy = GetActiveSource()
+ if proxy == None:
+ raise RuntimeError, "Show() needs a proxy argument or that an active source is set."
+ if not view and not active_objects.view:
+ CreateRenderView()
+ rep = GetDisplayProperties(proxy, view)
+ if rep == None:
+ raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel()
+ for param in params.keys():
+ setattr(rep, param, params[param])
+ rep.Visibility = 1
+ return rep
+
+def Hide(proxy=None, view=None):
+ """Turns the visibility of a given pipeline object off in the given view.
+ If pipeline object and/or view are not specified, active objects are used."""
+ rep = GetDisplayProperties(proxy, view)
+ rep.Visibility = 0
+
+def Render(view=None):
+ """Renders the given view (default value is active view)"""
+ if not view:
+ view = active_objects.view
+ view.StillRender()
+ if _funcs_internals.first_render:
+ # Not all views have a ResetCamera method
+ try:
+ view.ResetCamera()
+ view.StillRender()
+ except AttributeError: pass
+ _funcs_internals.first_render = False
+ return view
+
+def ResetCamera(view=None):
+ """Resets the settings of the camera to preserver orientation but include
+ the whole scene. If an argument is not provided, the active view is
+ used."""
+ if not view:
+ view = active_objects.view
+ if hasattr(view, "ResetCamera"):
+ view.ResetCamera()
+ if hasattr(view, "ResetDisplay"):
+ view.ResetDisplay()
+ Render(view)
+
+def _DisableFirstRenderCameraReset():
+ """Disable the first render camera reset. Normally a ResetCamera is called
+ automatically when Render is called for the first time after importing
+ this module."""
+ _funcs_internals.first_render = False
+
+def SetProperties(proxy=None, **params):
+ """Sets one or more properties of the given pipeline object. If an argument
+ is not provided, the active source is used. Pass a list of property_name=value
+ pairs to this function to set property values. For example:
+ SetProperties(Center=[1, 2, 3], Radius=3.5)
+ """
+ if not proxy:
+ proxy = active_objects.source
+ for param in params.keys():
+ if not hasattr(proxy, param):
+ raise AttributeError("object has no property %s" % param)
+ setattr(proxy, param, params[param])
+
+def GetProperty(*arguments, **keywords):
+ """Get one property of the given pipeline object. If keywords are used,
+ you can set the proxy and the name of the property that you want to get
+ like in the following example :
+ GetProperty({proxy=sphere, name="Radius"})
+ If it's arguments that are used, then you have two case:
+ - if only one argument is used that argument will be
+ the property name.
+ - if two arguments are used then the first one will be
+ the proxy and the second one the property name.
+ Several example are given below:
+ GetProperty({name="Radius"})
+ GetProperty({proxy=sphereProxy, name="Radius"})
+ GetProperty( sphereProxy, "Radius" )
+ GetProperty( "Radius" )
+ """
+ name = None
+ proxy = None
+ for key in keywords:
+ if key == "name":
+ name = keywords[key]
+ if key == "proxy":
+ proxy = keywords[key]
+ if len(arguments) == 1 :
+ name = arguments[0]
+ if len(arguments) == 2 :
+ proxy = arguments[0]
+ name = arguments[1]
+ if not name:
+ raise RuntimeError, "Expecting at least a property name as input. Otherwise keyword could be used to set 'proxy' and property 'name'"
+ if not proxy:
+ proxy = active_objects.source
+ return proxy.GetProperty(name)
+
+def SetDisplayProperties(proxy=None, view=None, **params):
+ """Sets one or more display properties of the given pipeline object. If an argument
+ is not provided, the active source is used. Pass a list of property_name=value
+ pairs to this function to set property values. For example:
+ SetProperties(Color=[1, 0, 0], LineWidth=2)
+ """
+ rep = GetDisplayProperties(proxy, view)
+ SetProperties(rep, **params)
+
+def SetViewProperties(view=None, **params):
+ """Sets one or more properties of the given view. If an argument
+ is not provided, the active view is used. Pass a list of property_name=value
+ pairs to this function to set property values. For example:
+ SetProperties(Background=[1, 0, 0], UseImmediateMode=0)
+ """
+ if not view:
+ view = active_objects.view
+ SetProperties(view, **params)
+
+def RenameSource(newName, proxy=None):
+ """Renames the given source. If the given proxy is not registered
+ in the sources group this method will have no effect. If no source is
+ provided, the active source is used."""
+ if not proxy:
+ proxy = active_objects.source
+ pxm = servermanager.ProxyManager()
+ oldName = pxm.GetProxyName("sources", proxy)
+ if oldName:
+ pxm.RegisterProxy("sources", newName, proxy)
+ pxm.UnRegisterProxy("sources", oldName, proxy)
+
+def FindSource(name):
+ return servermanager.ProxyManager().GetProxy("sources", name)
+
+def GetSources():
+ """Given the name of a source, return its Python object."""
+ return servermanager.ProxyManager().GetProxiesInGroup("sources")
+
+def GetRepresentations():
+ """Returns all representations (display properties)."""
+ return servermanager.ProxyManager().GetProxiesInGroup("representations")
+
+def UpdatePipeline(time=None, proxy=None):
+ """Updates (executes) the given pipeline object for the given time as
+ necessary (i.e. if it did not already execute). If no source is provided,
+ the active source is used instead."""
+ if not proxy:
+ proxy = active_objects.source
+ if time:
+ proxy.UpdatePipeline(time)
+ else:
+ proxy.UpdatePipeline()
+
+def Delete(proxy=None):
+ """Deletes the given pipeline object or the active source if no argument
+ is specified."""
+ if not proxy:
+ proxy = active_objects.source
+ # Unregister any helper proxies stored by a vtkSMProxyListDomain
+ for prop in proxy:
+ listdomain = prop.GetDomain('proxy_list')
+ if listdomain:
+ if listdomain.GetClassName() != 'vtkSMProxyListDomain':
+ continue
+ group = "pq_helper_proxies." + proxy.GetGlobalIDAsString()
+ for i in xrange(listdomain.GetNumberOfProxies()):
+ pm = servermanager.ProxyManager()
+ iproxy = listdomain.GetProxy(i)
+ name = pm.GetProxyName(group, iproxy)
+ if iproxy and name:
+ pm.UnRegisterProxy(group, name, iproxy)
+
+ # Remove source/view from time keeper
+ tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+ if isinstance(proxy, servermanager.SourceProxy):
+ try:
+ idx = tk.TimeSources.index(proxy)
+ del tk.TimeSources[idx]
+ except ValueError:
+ pass
+ else:
+ try:
+ idx = tk.Views.index(proxy)
+ del tk.Views[idx]
+ except ValueError:
+ pass
+ servermanager.UnRegister(proxy)
+
+ # If this is a representation, remove it from all views.
+ if proxy.SMProxy.IsA("vtkSMRepresentationProxy") or \
+ proxy.SMProxy.IsA("vtkSMNewWidgetRepresentationProxy"):
+ for view in GetRenderViews():
+ view.Representations.remove(proxy)
+ # If this is a source, remove the representation iff it has no consumers
+ # Also change the active source if necessary
+ elif proxy.SMProxy.IsA("vtkSMSourceProxy"):
+ sources = servermanager.ProxyManager().GetProxiesInGroup("sources")
+ for i in range(proxy.GetNumberOfConsumers()):
+ if proxy.GetConsumerProxy(i) in sources:
+ raise RuntimeError("Source has consumers. It cannot be deleted " +
+ "until all consumers are deleted.")
+ #VSV:==
+ if proxy.IsSame(GetActiveSource()):
+ if hasattr(proxy, "Input") and proxy.Input:
+ if isinstance(proxy.Input, servermanager.Proxy):
+ SetActiveSource(proxy.Input)
+ else:
+ SetActiveSource(proxy.Input[0])
+ else: SetActiveSource(None)
+ for rep in GetRepresentations().values():
+ #VSV:==
+ if rep.Input.IsSame(proxy):
+ Delete(rep)
+ # Change the active view if necessary
+ elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"):
+ ##VSV:==
+ if proxy.IsSame(GetActiveView()):
+ if len(GetRenderViews()) > 0:
+ SetActiveView(GetRenderViews()[0])
+ else:
+ SetActiveView(None)
+
+def CreateLookupTable(**params):
+ """Create and return a lookup table. Optionally, parameters can be given
+ to assign to the lookup table.
+ """
+ lt = servermanager.rendering.PVLookupTable()
+ servermanager.Register(lt)
+ SetProperties(lt, **params)
+ return lt
+
+def CreatePiecewiseFunction(**params):
+ """Create and return a piecewise function. Optionally, parameters can be
+ given to assign to the piecewise function.
+ """
+ pfunc = servermanager.piecewise_functions.PiecewiseFunction()
+ servermanager.Register(pfunc)
+ SetProperties(pfunc, **params)
+ return pfunc
+
+def GetLookupTableForArray(arrayname, num_components, **params):
+ """Used to get an existing lookuptable for a array or to create one if none
+ exists. Keyword arguments can be passed in to initialize the LUT if a new
+ one is created."""
+ proxyName = "%d.%s.PVLookupTable" % (int(num_components), arrayname)
+ lut = servermanager.ProxyManager().GetProxy("lookup_tables", proxyName)
+ if lut:
+ return lut
+ # No LUT exists for this array, create a new one.
+ # TODO: Change this to go a LookupTableManager that is shared with the GUI,
+ # so that the GUI and python end up create same type of LUTs. For now,
+ # python will create a Blue-Red LUT, unless overridden by params.
+ lut = servermanager.rendering.PVLookupTable(
+ ColorSpace="HSV", RGBPoints=[0, 0, 0, 1, 1, 1, 0, 0])
+ SetProperties(lut, **params)
+ servermanager.Register(lut, registrationName=proxyName)
+ return lut
+
+def CreateScalarBar(**params):
+ """Create and return a scalar bar widget. The returned widget may
+ be added to a render view by appending it to the view's representations
+ The widget must have a valid lookup table before it is added to a view.
+ It is possible to pass the lookup table (and other properties) as arguments
+ to this method:
+
+ lt = MakeBlueToRedLt(3.5, 7.5)
+ bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
+ GetRenderView().Representations.append(bar)
+
+ By default the returned widget is selectable and resizable.
+ """
+ sb = servermanager.rendering.ScalarBarWidgetRepresentation()
+ servermanager.Register(sb)
+ sb.Selectable = 1
+ sb.Resizable = 1
+ sb.Enabled = 1
+ sb.Title = "Scalars"
+ SetProperties(sb, **params)
+ return sb
+
+# TODO: Change this to take the array name and number of components. Register
+# the lt under the name ncomp.array_name
+def MakeBlueToRedLT(min, max):
+ # Define RGB points. These are tuples of 4 values. First one is
+ # the scalar values, the other 3 the RGB values.
+ rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
+ return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
+
+def _find_writer(filename):
+ """Internal function."""
+ extension = None
+ parts = filename.split('.')
+ if len(parts) > 1:
+ extension = parts[-1]
+ else:
+ raise RuntimeError, "Filename has no extension, please specify a write"
+
+ if extension == 'png':
+ return 'vtkPNGWriter'
+ elif extension == 'bmp':
+ return 'vtkBMPWriter'
+ elif extension == 'ppm':
+ return 'vtkPNMWriter'
+ elif extension == 'tif' or extension == 'tiff':
+ return 'vtkTIFFWriter'
+ elif extension == 'jpg' or extension == 'jpeg':
+ return 'vtkJPEGWriter'
+ else:
+ raise RuntimeError, "Cannot infer filetype from extension:", extension
+
+def AddCameraLink(viewProxy, viewProxyOther, linkName):
+ """Create a camera link between two view proxies. A name must be given
+ so that the link can be referred to by name. If a link with the given
+ name already exists it will be removed first."""
+ if not viewProxyOther: viewProxyOther = GetActiveView()
+ link = servermanager.vtkSMCameraLink()
+ link.AddLinkedProxy(viewProxy.SMProxy, 1)
+ link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
+ link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
+ link.AddLinkedProxy(viewProxy.SMProxy, 2)
+ RemoveCameraLink(linkName)
+ servermanager.ProxyManager().RegisterLink(linkName, link)
+
+def RemoveCameraLink(linkName):
+ """Remove a camera link with the given name."""
+ servermanager.ProxyManager().UnRegisterLink(linkName)
+
+def WriteImage(filename, view=None, **params):
+ """Saves the given view (or the active one if none is given) as an
+ image. Optionally, you can specify the writer and the magnification
+ using the Writer and Magnification named arguments. For example:
+ WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)
+ If no writer is provided, the type is determined from the file extension.
+ Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
+ The writer is a VTK class that is capable of writing images.
+ Magnification is used to determine the size of the written image. The size
+ is obtained by multiplying the size of the view with the magnification.
+ Rendering may be done using tiling to obtain the correct size without
+ resizing the view."""
+ if not view:
+ view = active_objects.view
+ writer = None
+ if params.has_key('Writer'):
+ writer = params['Writer']
+ mag = 1
+ if params.has_key('Magnification'):
+ mag = int(params['Magnification'])
+ if not writer:
+ writer = _find_writer(filename)
+ view.WriteImage(filename, writer, mag)
+
+def AnimateReader(reader=None, view=None, filename=None):
+ """This is a utility function that, given a reader and a view
+ animates over all time steps of the reader. If the optional
+ filename is provided, a movie is created (type depends on the
+ extension of the filename."""
+ if not reader:
+ reader = active_objects.source
+ if not view:
+ view = active_objects.view
+
+ return servermanager.AnimateReader(reader, view, filename)
+
+
+def _create_func(key, module):
+ """Internal function."""
+
+ def CreateObject(*input, **params):
+ """This function creates a new proxy. For pipeline objects that accept inputs,
+ all non-keyword arguments are assumed to be inputs. All keyword arguments are
+ assumed to be property,value pairs and are passed to the new proxy."""
+
+ # Instantiate the actual object from the given module.
+ px = module.__dict__[key]()
+
+ # Make sure non-keyword arguments are valid
+ for inp in input:
+ if inp != None and not isinstance(inp, servermanager.Proxy):
+ if px.GetProperty("Input") != None:
+ raise RuntimeError, "Expecting a proxy as input."
+ else:
+ raise RuntimeError, "This function does not accept non-keyword arguments."
+
+ # Assign inputs
+ if px.GetProperty("Input") != None:
+ if len(input) > 0:
+ px.Input = input
+ else:
+ # If no input is specified, try the active pipeline object
+ if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
+ px.Input = active_objects.get_selected_sources()
+ elif active_objects.source:
+ px.Input = active_objects.source
+ else:
+ if len(input) > 0:
+ raise RuntimeError, "This function does not expect an input."
+
+ registrationName = None
+ for nameParam in ['registrationName', 'guiName']:
+ if nameParam in params:
+ registrationName = params[nameParam]
+ del params[nameParam]
+
+ # Pass all the named arguments as property,value pairs
+ for param in params.keys():
+ setattr(px, param, params[param])
+
+ try:
+ # Register the proxy with the proxy manager.
+ if registrationName:
+ group, name = servermanager.Register(px, registrationName=registrationName)
+ else:
+ group, name = servermanager.Register(px)
+
+
+ # Register pipeline objects with the time keeper. This is used to extract time values
+ # from sources. NOTE: This should really be in the servermanager controller layer.
+ if group == "sources":
+ has_tk = True
+ try:
+ tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+ except IndexError:
+ has_tk = False
+ if has_tk:
+ sources = tk.TimeSources
+ if not px in sources:
+ sources.append(px)
+
+ active_objects.source = px
+ except servermanager.MissingRegistrationInformation:
+ pass
+
+ return px
+
+ return CreateObject
+
+def _create_doc(new, old):
+ """Internal function."""
+ import string
+ res = ""
+ for doc in (new, old):
+ ts = []
+ strpd = doc.split('\n')
+ for s in strpd:
+ ts.append(s.lstrip())
+ res += string.join(ts)
+ res += '\n'
+ return res
+
+def _func_name_valid(name):
+ """Internal function."""
+ valid = True
+ for c in name:
+ if c == '(' or c ==')':
+ valid = False
+ break
+ return valid
+
+def _add_functions(g):
+ activeModule = servermanager.ActiveConnection.Modules
+ for m in [activeModule.filters, activeModule.sources,
+ activeModule.writers, activeModule.animation]:
+ dt = m.__dict__
+ for key in dt.keys():
+ cl = dt[key]
+ if not isinstance(cl, str):
+ if not key in g and _func_name_valid(key):
+ g[key] = _create_func(key, m)
+ exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key
+
+def _remove_functions(g):
+ list = []
+ if servermanager.ActiveConnection:
+ list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_']
+
+ for m in list:
+ dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__
+ for key in dt.keys():
+ cl = dt[key]
+ if not isinstance(cl, str) and g.has_key(key):
+ g.pop(key)
+ #print "remove %s function" % key
+
+def GetActiveView():
+ """Returns the active view."""
+ return active_objects.view
+
+def SetActiveView(view):
+ """Sets the active view."""
+ active_objects.view = view
+
+def GetActiveSource():
+ """Returns the active source."""
+ return active_objects.source
+
+def SetActiveSource(source):
+ """Sets the active source."""
+ active_objects.source = source
+
+def GetActiveCamera():
+ """Returns the active camera for the active view. The returned object
+ is an instance of vtkCamera."""
+ return GetActiveView().GetActiveCamera()
+
+def GetAnimationScene():
+ """Returns the application-wide animation scene. ParaView has only one
+ global animation scene. This method provides access to that. Users are
+ free to create additional animation scenes directly, but those scenes
+ won't be shown in the ParaView GUI."""
+ animation_proxies = servermanager.ProxyManager().GetProxiesInGroup("animation")
+ scene = None
+ for aProxy in animation_proxies.values():
+ if aProxy.GetXMLName() == "AnimationScene":
+ scene = aProxy
+ break
+ if not scene:
+ raise servermanager.MissingProxy, "Could not locate global AnimationScene."
+ return scene
+
+def WriteAnimation(filename, **params):
+ """Writes the current animation as a file. Optionally one can specify
+ arguments that qualify the saved animation files as keyword arguments.
+ Accepted options are as follows:
+ * Magnification (integer) : set the maginification factor for the saved
+ animation.
+ * Quality (0 [worst] or 1 or 2 [best]) : set the quality of the generated
+ movie (if applicable).
+ * Subsampling (integer) : setting whether the movie encoder should use
+ subsampling of the chrome planes or not, if applicable. Since the human
+ eye is more sensitive to brightness than color variations, subsampling
+ can be useful to reduce the bitrate. Default value is 0.
+ * BackgroundColor (3-tuple of doubles) : set the RGB background color to
+ use to fill empty spaces in the image.
+ * FrameRate (double): set the frame rate (if applicable)."""
+ scene = GetAnimationScene()
+ # ensures that the TimeKeeper track is created.
+ GetTimeTrack()
+ iw = servermanager.vtkSMAnimationSceneImageWriter()
+ iw.SetAnimationScene(scene.SMProxy)
+ iw.SetFileName(filename)
+ if params.has_key("Magnification"):
+ iw.SetMagnification(int(params["Magnification"]))
+ if params.has_key("Quality"):
+ iw.SetQuality(int(params["Quality"]))
+ if params.has_key("Subsampling"):
+ iw.SetSubsampling(int(params["Subsampling"]))
+ if params.has_key("BackgroundColor"):
+ iw.SetBackgroundColor(params["BackgroundColor"])
+ if params.has_key("FrameRate"):
+ iw.SetFrameRate(float(params["FrameRate"]))
+ iw.Save()
+
+def _GetRepresentationAnimationHelper(sourceproxy):
+ """Internal method that returns the representation animation helper for a
+ source proxy. It creates a new one if none exists."""
+ # ascertain that proxy is a source proxy
+ if not sourceproxy in GetSources().values():
+ return None
+ for proxy in servermanager.ProxyManager():
+ if proxy.GetXMLName() == "RepresentationAnimationHelper" and\
+ proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy):
+ return proxy
+ # create a new helper
+ proxy = servermanager.misc.RepresentationAnimationHelper(
+ Source=sourceproxy)
+ servermanager.ProxyManager().RegisterProxy(
+ "pq_helper_proxies.%s" % sourceproxy.GetGlobalIDAsString(),
+ "RepresentationAnimationHelper", proxy)
+ return proxy
+
+def GetAnimationTrack(propertyname_or_property, index=None, proxy=None):
+ """Returns an animation cue for the property. If one doesn't exist then a
+ new one will be created.
+ Typical usage:
+ track = GetAnimationTrack("Center", 0, sphere) or
+ track = GetAnimationTrack(sphere.GetProperty("Radius")) or
+
+ # this returns the track to animate visibility of the active source in
+ # all views.
+ track = GetAnimationTrack("Visibility")
+
+ For animating properties on implicit planes etc., use the following
+ signatures:
+ track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or
+ track = GetAnimationTrack("Origin", 0, slice.SliceType)
+
+ """
+ if not proxy:
+ proxy = GetActiveSource()
+ if not isinstance(proxy, servermanager.Proxy):
+ raise TypeError, "proxy must be a servermanager.Proxy instance"
+ if isinstance(propertyname_or_property, str):
+ propertyname = propertyname_or_property
+ elif isinstance(propertyname_or_property, servermanager.Property):
+ prop = propertyname_or_property
+ propertyname = prop.Name
+ proxy = prop.Proxy
+ else:
+ raise TypeError, "propertyname_or_property must be a string or servermanager.Property"
+
+ # To handle the case where the property is actually a "display" property, in
+ # which case we are actually animating the "RepresentationAnimationHelper"
+ # associated with the source.
+ if propertyname in ["Visibility", "Opacity"]:
+ proxy = _GetRepresentationAnimationHelper(proxy)
+ if not proxy or not proxy.GetProperty(propertyname):
+ raise AttributeError, "Failed to locate property %s" % propertyname
+
+ scene = GetAnimationScene()
+ for cue in scene.Cues:
+ try:
+ if cue.AnimatedProxy.IsSame(proxy) and\
+ cue.AnimatedPropertyName == propertyname:
+ if index == None or index.IsSame(cue.AnimatedElement): ##index == cue.AnimatedElement:
+ return cue
+ except AttributeError:
+ pass
+
+ # matching animation track wasn't found, create a new one.
+ cue = KeyFrameAnimationCue()
+ cue.AnimatedProxy = proxy
+ cue.AnimatedPropertyName = propertyname
+ if index != None:
+ cue.AnimatedElement = index
+ scene.Cues.append(cue)
+ return cue
+
+def GetCameraTrack(view=None):
+ """Returns the camera animation track for the given view. If no view is
+ specified, active view will be used. If no exisiting camera animation track
+ is found, a new one will be created."""
+ if not view:
+ view = GetActiveView()
+ if not view:
+ raise ValueError, "No view specified"
+ scene = GetAnimationScene()
+ for cue in scene.Cues:
+ if cue.AnimatedProxy.IsSame(view) and\
+ cue.GetXMLName() == "CameraAnimationCue":
+ return cue
+ # no cue was found, create a new one.
+ cue = CameraAnimationCue()
+ cue.AnimatedProxy = view
+ scene.Cues.append(cue)
+ return cue
+
+def GetTimeTrack():
+ """Returns the animation track used to control the time requested from all
+ readers/filters during playback.
+ This is the "TimeKeeper - Time" track shown in ParaView's 'Animation View'.
+ If none exists, a new one will be created."""
+ scene = GetAnimationScene()
+ tk = scene.TimeKeeper
+ for cue in scene.Cues:
+ if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy.IsSame(tk)\
+ and cue.AnimatedPropertyName == "Time":
+ return cue
+ # no cue was found, create a new one.
+ cue = TimeAnimationCue()
+ cue.AnimatedProxy = tk
+ cue.AnimatedPropertyName = "Time"
+ scene.Cues.append(cue)
+ return cue
+
+def LoadXML(xmlstring, ns=None):
+ """Given a server manager XML as a string, parse and process it.
+ If you loaded the simple module with from paraview.simple import *,
+ make sure to pass globals() as the second arguments:
+ LoadXML(xmlstring, globals())
+ Otherwise, the new functions will not appear in the global namespace."""
+ if not ns:
+ ns = globals()
+ servermanager.LoadXML(xmlstring)
+ _add_functions(ns)
+
+def LoadPlugin(filename, remote=True, ns=None):
+ """Loads a ParaView plugin and updates this module with new constructors
+ if any. The remote argument (default to True) is to specify whether
+ the plugin will be loaded on client (remote=False) or on server (remote=True).
+ If you loaded the simple module with from paraview.simple import *,
+ make sure to pass globals() as an argument:
+ LoadPlugin("myplugin", False, globals()), to load on client;
+ LoadPlugin("myplugin", True, globals()), to load on server;
+ LoadPlugin("myplugin", ns=globals()), to load on server.
+ Otherwise, the new functions will not appear in the global namespace."""
+
+ if not ns:
+ ns = globals()
+ servermanager.LoadPlugin(filename, remote)
+ _add_functions(ns)
+
+def LoadDistributedPlugin(pluginname, remote=True, ns=None):
+ """Loads a plugin that's distributed with the executable. This uses the
+ information known about plugins distributed with ParaView to locate the
+ shared library for the plugin to load. Raises a RuntimeError if the plugin
+ was not found."""
+ if not servermanager.ActiveConnection:
+ raise RuntimeError, "Cannot load a plugin without a session."
+ plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager()
+ if remote:
+ session = servermanager.ActiveConnection.Session
+ info = plm.GetRemoteInformation(session)
+ else:
+ info = plm.GetLocalInformation()
+ for cc in range(0, info.GetNumberOfPlugins()):
+ if info.GetPluginName(cc) == pluginname:
+ return LoadPlugin(info.GetPluginFileName(cc), remote, ns)
+ raise RuntimeError, "Plugin '%s' not found" % pluginname
+
+def GetLayouts():
+ """Returns the layout proxies on the active session.
+ Layout proxies are used to place views in a grid."""
+ return servermanager.ProxyManager().GetProxiesInGroup("layouts")
+
+def GetLayout(view=None):
+ """Return the layout containing the give view, if any.
+ If no view is specified, active view is used.
+ """
+ if not view:
+ view = GetActiveView()
+ if not view:
+ raise RuntimeError, "No active view was found."
+ layouts = GetLayouts()
+ for layout in layouts.values():
+ if layout.GetViewLocation(view) != -1:
+ return layout
+ return None
+
+
+def SelectCells(query=None, proxy=None):
+ """Select cells satisfying the query. If query is None, then all cells are
+ selected. If proxy is None, then the active source is used."""
+ if not proxy:
+ proxy = GetActiveSource()
+ if not proxy:
+ raise RuntimeError, "No active source was found."
+
+ if not query:
+ # This ends up being true for all cells.
+ query = "id >= 0"
+
+ # Note, selSource is not registered with the proxy manager.
+ selSource = servermanager.sources.SelectionQuerySource()
+ selSource.FieldType = "CELL"
+ selSource.QueryString = str(query)
+ proxy.SMProxy.SetSelectionInput(proxy.Port, selSource.SMProxy, 0)
+ return selSource
+
+def ClearSelection(proxy=None):
+ """Clears the selection on the active source."""
+ if not proxy:
+ proxy = GetActiveSource()
+ if not proxy:
+ raise RuntimeError, "No active source was found."
+ proxy.SMProxy.SetSelectionInput(proxy.Port, None, 0)
+
+class ActiveObjects(object):
+ """This class manages the active objects (source and view). The active
+ objects are shared between Python and the user interface. This class
+ is for internal use. Use the Set/Get methods for setting and getting
+ active objects."""
+ def __get_selection_model(self, name, session=None):
+ "Internal method."
+ if session and not servermanager.ActiveConnection.Session.IsSame(session):
+ raise RuntimeError, "Try to set an active object with invalid active connection."
+ pxm = servermanager.ProxyManager(session)
+ model = pxm.GetSelectionModel(name)
+ if not model:
+ model = servermanager.vtkSMProxySelectionModel()
+ pxm.RegisterSelectionModel(name, model)
+ return model
+
+ def set_view(self, view):
+ "Sets the active view."
+ active_view_model = self.__get_selection_model("ActiveView")
+ if view:
+ active_view_model = self.__get_selection_model("ActiveView", view.GetSession())
+ active_view_model.SetCurrentProxy(view.SMProxy, 0)
+ else:
+ active_view_model = self.__get_selection_model("ActiveView")
+ active_view_model.SetCurrentProxy(None, 0)
+
+ def get_view(self):
+ "Returns the active view."
+ return servermanager._getPyProxy(
+ self.__get_selection_model("ActiveView").GetCurrentProxy())
+
+ def set_source(self, source):
+ "Sets the active source."
+ active_sources_model = self.__get_selection_model("ActiveSources")
+ if source:
+ # 3 == CLEAR_AND_SELECT
+ active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession())
+ active_sources_model.SetCurrentProxy(source.SMProxy, 3)
+ else:
+ active_sources_model = self.__get_selection_model("ActiveSources")
+ active_sources_model.SetCurrentProxy(None, 3)
+
+ def __convert_proxy(self, px):
+ "Internal method."
+ if not px:
+ return None
+ if px.IsA("vtkSMSourceProxy"):
+ return servermanager._getPyProxy(px)
+ else:
+ return servermanager.OutputPort(
+ servermanager._getPyProxy(px.GetSourceProxy()),
+ px.GetPortIndex())
+
+ def get_source(self):
+ "Returns the active source."
+ return self.__convert_proxy(
+ self.__get_selection_model("ActiveSources").GetCurrentProxy())
+
+ def get_selected_sources(self):
+ "Returns the set of sources selected in the pipeline browser."
+ model = self.__get_selection_model("ActiveSources")
+ proxies = []
+ for i in xrange(model.GetNumberOfSelectedProxies()):
+ proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
+ return proxies
+
+ view = property(get_view, set_view)
+ source = property(get_source, set_source)
+
+class _funcs_internals:
+ """Internal class."""
+ first_render = True
+ view_counter = 0
+ rep_counter = 0
+
+def demo1():
+ """Simple demo that create the following pipeline
+ sphere - shrink - \
+ - append
+ cone - /
+ """
+ # Create a sphere of radius = 2, theta res. = 32
+ # This object becomes the active source.
+ ss = Sphere(Radius=2, ThetaResolution=32)
+ # Apply the shrink filter. The Input property is optional. If Input
+ # is not specified, the filter is applied to the active source.
+ shr = Shrink(Input=ss)
+ # Create a cone source.
+ cs = Cone()
+ # Append cone and shrink
+ app = AppendDatasets()
+ app.Input = [shr, cs]
+ # Show the output of the append filter. The argument is optional
+ # as the app filter is now the active object.
+ Show(app)
+ # Render the default view.
+ Render()
+
+def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"):
+ """This demo shows the use of readers, data information and display
+ properties."""
+
+ # Create the exodus reader and specify a file name
+ reader = ExodusIIReader(FileName=fname)
+ # Get the list of point arrays.
+ avail = reader.PointVariables.Available
+ print avail
+ # Select all arrays
+ reader.PointVariables = avail
+
+ # Turn on the visibility of the reader
+ Show(reader)
+ # Set representation to wireframe
+ SetDisplayProperties(Representation = "Wireframe")
+ # Black background is not pretty
+ SetViewProperties(Background = [0.4, 0.4, 0.6])
+ Render()
+ # Change the elevation of the camera. See VTK documentation of vtkCamera
+ # for camera parameters.
+ # NOTE: THIS WILL BE SIMPLER
+ GetActiveCamera().Elevation(45)
+ Render()
+ # Now that the reader executed, let's get some information about it's
+ # output.
+ pdi = reader[0].PointData
+ # This prints a list of all read point data arrays as well as their
+ # value ranges.
+ print 'Number of point arrays:', len(pdi)
+ for i in range(len(pdi)):
+ ai = pdi[i]
+ print "----------------"
+ print "Array:", i, " ", ai.Name, ":"
+ numComps = ai.GetNumberOfComponents()
+ print "Number of components:", numComps
+ for j in range(numComps):
+ print "Range:", ai.GetRange(j)
+ # White is boring. Let's color the geometry using a variable.
+ # First create a lookup table. This object controls how scalar
+ # values are mapped to colors. See VTK documentation for
+ # details.
+ # Map min (0.00678) to blue, max (0.0288) to red
+ SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
+ # Color by point array called Pres
+ SetDisplayProperties(ColorAttributeType = "POINT_DATA")
+ SetDisplayProperties(ColorArrayName = "Pres")
+ Render()
+
+def PrintTrace():
+ print paravisSM.myParavis.GetTrace()
+
+def SaveTrace(fileName):
+ paravisSM.myParavis.SaveTrace(fileName)
+
+
+if not servermanager.ActiveConnection:
+ Connect()
+else:
+ _add_functions(globals())
+
+def ImportFile(theFileName):
+ paravisSM.ImportFile(theFileName)
+
+active_objects = ActiveObjects()
+active_objects.view = GetRenderView()
--- /dev/null
+0a1,19
+> # Copyright (C) 2010-2013 CEA/DEN, EDF R&D
+> #
+> # This library is free software; you can redistribute it and/or
+> # modify it under the terms of the GNU Lesser General Public
+> # License as published by the Free Software Foundation; either
+> # version 2.1 of the License.
+> #
+> # This library is distributed in the hope that it will be useful,
+> # but WITHOUT ANY WARRANTY; without even the implied warranty of
+> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+> # Lesser General Public License for more details.
+> #
+> # You should have received a copy of the GNU Lesser General Public
+> # License along with this library; if not, write to the Free Software
+> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+> #
+> # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+> #
+>
+29,43d47
+< #==============================================================================
+< #
+< # Program: ParaView
+< # Module: servermanager.py
+< #
+< # Copyright (c) Kitware, Inc.
+< # All rights reserved.
+< # See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
+< #
+< # This software is distributed WITHOUT ANY WARRANTY without even
+< # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+< # PURPOSE. See the above copyright notice for more information.
+< #
+< #==============================================================================
+< import paraview, re, os, os.path, new, sys, vtk
+45,53c49,54
+< if not paraview.compatibility.minor:
+< paraview.compatibility.major = 3
+< if not paraview.compatibility.major:
+< paraview.compatibility.minor = 5
+<
+< from vtkPVClientServerCorePython import *
+< from vtkPVServerImplementationPython import *
+< from vtkPVServerManagerPython import *
+< from vtkPVCommonPython import *
+---
+>
+>
+> import re, os, new, sys
+> from paravis import *
+>
+>
+61,62c62
+< if paraview.compatibility.GetVersion() >= 3.5 and \
+< smproperty.IsA("vtkSMStringVectorProperty"):
+---
+> if smproperty.IsA("vtkSMStringVectorProperty"):
+251,252c251,253
+< return self.SMProxy == other.SMProxy
+< return self.SMProxy == other
+---
+> ## VSV using IsSame instead ==
+> return self.SMProxy.IsSame(other.SMProxy)
+> return self.SMProxy.IsSame(other)
+347,350c348,351
+< if not c.HasObserver("ModifiedEvent"):
+< self.ObserverTag =c.AddObserver("ModifiedEvent", \
+< _makeUpdateCameraMethod(weakref.ref(self)))
+< self.Observed = c
+---
+> # VSV: Observers are not supported
+> ## if not c.HasObserver("ModifiedEvent"):
+> ## self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self)))
+> ## self.Observed = c
+454,472c455,472
+< if paraview.compatibility.GetVersion() >= 3.5:
+< def FileNameChanged(self):
+< "Called when the filename changes. Selects all variables."
+< SourceProxy.FileNameChanged(self)
+< self.SelectAllVariables()
+<
+< def SelectAllVariables(self):
+< "Select all available variables for reading."
+< for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+< 'ElementVariables', 'GlobalVariables'):
+< f = getattr(self, prop)
+< f.SelectAll()
+<
+< def DeselectAllVariables(self):
+< "Deselects all variables."
+< for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+< 'ElementVariables', 'GlobalVariables'):
+< f = getattr(self, prop)
+< f.DeselectAll()
+---
+> def FileNameChanged(self):
+> "Called when the filename changes. Selects all variables."
+> SourceProxy.FileNameChanged(self)
+> self.SelectAllVariables()
+>
+> def SelectAllVariables(self):
+> "Select all available variables for reading."
+> for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+> 'ElementVariables', 'GlobalVariables'):
+> f = getattr(self, prop)
+> f.SelectAll()
+>
+> def DeselectAllVariables(self):
+> "Deselects all variables."
+> for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+> 'ElementVariables', 'GlobalVariables'):
+> f = getattr(self, prop)
+> f.DeselectAll()
+1110c1110,1111
+< if proxy == px:
+---
+> ## VSV: ==
+> if proxy.IsSame(px):
+1329,1332d1329
+< if paraview.compatibility.GetVersion() <= 3.4:
+< def Range(self, component=0):
+< return self.GetRange(component)
+<
+1526c1523
+< aProxy = self.SMProxyManager.NewProxy(group, name)
+---
+> aProxy = self.SMProxyManager.NewProxy(group, name, "NULL")
+1838a1836
+> # VTN: Observers are not supported
+1840c1838
+< self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions)
+---
+> ## self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions)
+1842c1840
+< self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions)
+---
+> ## self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions)
+2056c2054,2055
+< try: isRep = rep.Input == aProxy
+---
+> #VSV: ==
+> try: isRep = rep.Input.IsSame(aProxy)
+2287,2303c2286,2287
+< """Turn on/off printing of progress (by default, it is on). You can
+< always turn progress off and add your own observer to the process
+< module to handle progress in a custom way. See _printProgress for
+< an example event observer."""
+< global progressObserverTag
+<
+< # If value is true and progress printing is currently off...
+< if value and not GetProgressPrintingIsEnabled():
+< if fromGUI:
+< raise RuntimeError("Printing progress in the GUI is not supported.")
+< progressObserverTag = vtkProcessModule.GetProcessModule().AddObserver(\
+< "ProgressEvent", _printProgress)
+<
+< # If value is false and progress printing is currently on...
+< elif GetProgressPrintingIsEnabled():
+< vtkProcessModule.GetProcessModule().RemoveObserver(progressObserverTag)
+< progressObserverTag = None
+---
+> """Is not supported because of not supported observers"""
+> pass
+2330,2332c2314,2315
+< if paraview.compatibility.GetVersion() >= 3.5:
+< if smproxy.GetXMLLabel():
+< xmlName = smproxy.GetXMLLabel()
+---
+> if smproxy.GetXMLLabel():
+> xmlName = smproxy.GetXMLLabel()
+2375,2378c2358
+< if paraview.compatibility.GetVersion() >= 3.5:
+< return self.GetPropertyValue(propName)
+< else:
+< return self.GetProperty(propName)
+---
+> return self.GetPropertyValue(propName)
+2494c2474,2482
+< return paraview.make_name_valid(name)
+---
+> """Make a string into a valid Python variable name."""
+> if not name:
+> return None
+> import string
+> valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
+> name = str().join([c for c in name if c in valid_chars])
+> if not name[0].isalpha():
+> name = 'a' + name
+> return name
+2520,2521c2508
+< if paraview.compatibility.GetVersion() >= 3.5 and\
+< proto.GetXMLLabel():
+---
+> if proto.GetXMLLabel():
+2536,2539c2523,2525
+< if paraview.compatibility.GetVersion() >= 3.5:
+< if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
+< or prop.GetIsInternal():
+< continue
+---
+> if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
+> or prop.GetIsInternal():
+> continue
+2541,2542c2527
+< if paraview.compatibility.GetVersion() >= 3.5:
+< names = [iter.PropertyLabel]
+---
+> names = [iter.PropertyLabel]
+2681,2690c2666,2669
+< if paraview.compatibility.GetVersion() <= 3.4:
+< ss = sources.SphereSource(Radius=2, ThetaResolution=32)
+< shr = filters.ShrinkFilter(Input=OutputPort(ss,0))
+< cs = sources.ConeSource()
+< app = filters.Append()
+< else:
+< ss = sources.Sphere(Radius=2, ThetaResolution=32)
+< shr = filters.Shrink(Input=OutputPort(ss,0))
+< cs = sources.Cone()
+< app = filters.AppendDatasets()
+---
+> ss = sources.Sphere(Radius=2, ThetaResolution=32)
+> shr = filters.Shrink(Input=OutputPort(ss,0))
+> cs = sources.Cone()
+> app = filters.AppendDatasets()
+2711,2714c2690
+< if paraview.compatibility.GetVersion() <= 3.4:
+< arraySelection = reader.PointResultArrayStatus
+< else:
+< arraySelection = reader.PointVariables
+---
+> arraySelection = reader.PointVariables
+2748,2751c2724
+< if paraview.compatibility.GetVersion() <= 3.4:
+< print "Range:", ai.Range(j)
+< else:
+< print "Range:", ai.GetRange(j)
+---
+> print "Range:", ai.GetRange(j)
+2782,2785c2755
+< if paraview.compatibility.GetVersion() <= 3.4:
+< source = sources.RTAnalyticSource()
+< else:
+< source = sources.Wavelet()
+---
+> source = sources.Wavelet()
+2816,2823c2786,2788
+< if paraview.compatibility.GetVersion() <= 3.4:
+< probe = filters.Probe(Input=source)
+< # with a line
+< line = sources.LineSource(Resolution=60)
+< else:
+< probe = filters.ResampleWithDataset(Input=source)
+< # with a line
+< line = sources.Line(Resolution=60)
+---
+> probe = filters.ResampleWithDataset(Input=source)
+> # with a line
+> line = sources.Line(Resolution=60)
+2867,2870c2832
+< if paraview.compatibility.GetVersion() <= 3.4:
+< sphere = sources.SphereSource()
+< else:
+< sphere = sources.Sphere()
+---
+> sphere = sources.Sphere()
+2960,2965c2922,2927
+< pvoptions = None
+< if paraview.options.batch:
+< pvoptions = vtkPVOptions();
+< pvoptions.SetProcessType(0x40)
+< if paraview.options.symmetric:
+< pvoptions.SetSymmetricMPIMode(True)
+---
+> # pvoptions = None Not applicable for SALOME Python console
+> # if paraview.options.batch:
+> # pvoptions = vtkPVOptions();
+> # pvoptions.SetProcessType(0x40)
+> # if paraview.options.symmetric:
+> # pvoptions.SetSymmetricMPIMode(True)
+2994,2995c2956,2957
+<
+< if not paraview.fromFilter:
+---
+> ## VSV fromFilter is alwais False for SALOME because it can't be changed from ParaView code
+> #if not paraview.fromFilter:
+2998,2999c2960,2963
+< connection.AttachDefinitionUpdater()
+< pass
+---
+> # global _defUpdater
+> # _defUpdater = __DefinitionUpdater()
+> connection.AttachDefinitionUpdater()
+> pass
+3008a2973,2982
+> # Definitions for working in SALOME GUI mode
+> #aParams = myParavis.GetConnectionParameters()
+> #ActiveConnection = Connect()
+> ##Connection(aParams[0])
+> #ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5])
+> #ToggleProgressPrinting()
+> #fromGUI = True
+>
+> InitFromGUI()
+>
--- /dev/null
+0a1,19
+> # Copyright (C) 2010-2013 CEA/DEN, EDF R&D
+> #
+> # This library is free software; you can redistribute it and/or
+> # modify it under the terms of the GNU Lesser General Public
+> # License as published by the Free Software Foundation; either
+> # version 2.1 of the License.
+> #
+> # This library is distributed in the hope that it will be useful,
+> # but WITHOUT ANY WARRANTY; without even the implied warranty of
+> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+> # Lesser General Public License for more details.
+> #
+> # You should have received a copy of the GNU Lesser General Public
+> # License along with this library; if not, write to the Free Software
+> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+> #
+> # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+> #
+>
+21,34d39
+< #==============================================================================
+< #
+< # Program: ParaView
+< # Module: simple.py
+< #
+< # Copyright (c) Kitware, Inc.
+< # All rights reserved.
+< # See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
+< #
+< # This software is distributed WITHOUT ANY WARRANTY; without even
+< # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+< # PURPOSE. See the above copyright notice for more information.
+< #
+< #==============================================================================
+36,39c41
+< import paraview
+< paraview.compatibility.major = 3
+< paraview.compatibility.minor = 5
+< import servermanager
+---
+> import paravisSM
+41,42c43
+< def enableMultiServer():
+< servermanager.enableMultiServer()
+---
+> servermanager = paravisSM
+44,56c45,46
+< def switchActiveConnection(newActiveConnection=None, ns=None):
+< if not ns:
+< ns = globals()
+< _remove_functions(ns)
+< servermanager.switchActiveConnection(newActiveConnection)
+< _add_functions(ns)
+<
+< def Disconnect(ns=None, force=True):
+< if servermanager.ActiveConnection and (force or servermanager.MultiServerConnections == None):
+< if ns:
+< _remove_functions(ns)
+< _remove_functions(globals())
+< servermanager.ProxyManager().DisableStateUpdateNotification()
+---
+> def _disconnect():
+> if servermanager.ActiveConnection:
+61d50
+< servermanager.Disconnect()
+62a52
+> servermanager.Disconnect()
+69,70c59,60
+< Disconnect(globals(), False)
+< connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
+---
+> _disconnect()
+> session = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
+73,88c63,67
+< servermanager.ProxyManager().DisableStateUpdateNotification()
+< servermanager.ProxyManager().UpdateFromRemote()
+< tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
+< if not tk:
+< tk = servermanager.misc.TimeKeeper()
+< servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
+<
+< scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
+< if not scene:
+< scene = AnimationScene()
+< scene.TimeKeeper = tk
+<
+< servermanager.ProxyManager().EnableStateUpdateNotification()
+< servermanager.ProxyManager().TriggerStateUpdate()
+<
+< return connection
+---
+> tk = servermanager.misc.TimeKeeper()
+> servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", tk)
+> scene = AnimationScene()
+> scene.TimeKeeper = tk
+> return session
+93,94c72,73
+< Disconnect(globals(), False)
+< connection = servermanager.ReverseConnect(port)
+---
+> _disconnect()
+> session = servermanager.ReverseConnect(port)
+96,112c75,79
+<
+< servermanager.ProxyManager().DisableStateUpdateNotification()
+< servermanager.ProxyManager().UpdateFromRemote()
+< tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
+< if not tk:
+< tk = servermanager.misc.TimeKeeper()
+< servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
+<
+< scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
+< if not scene:
+< scene = AnimationScene()
+< scene.TimeKeeper = tk
+<
+< servermanager.ProxyManager().EnableStateUpdateNotification()
+< servermanager.ProxyManager().TriggerStateUpdate()
+<
+< return connection
+---
+> tk = servermanager.misc.TimeKeeper()
+> servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", tk)
+> scene = AnimationScene()
+> scene.TimeKeeper = tk
+> return session
+121c88
+<
+---
+>
+161a129,131
+> reader_factor = servermanager.ProxyManager().GetReaderFactory()
+> if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
+> reader_factor.RegisterPrototypes("sources")
+163,165d132
+< reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory()
+< if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
+< reader_factor.RegisterPrototypes(session, "sources")
+170,171c137
+< msg = "File not readable: %s " % first_file
+< raise RuntimeError, msg
+---
+> raise RuntimeError, "File not readable: %s " % first_file
+173,174c139
+< msg = "File not readable. No reader found for '%s' " % first_file
+< raise RuntimeError, msg
+---
+> raise RuntimeError, "File not readable. No reader found for '%s' " % first_file
+192,193c157
+< session = servermanager.ActiveConnection.Session
+< writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory()
+---
+> writer_factory = servermanager.ProxyManager().GetWriterFactory()
+195c159
+< writer_factory.RegisterPrototypes(session, "writers")
+---
+> writer_factory.RegisterPrototypes("writers")
+441c405,406
+< if proxy == GetActiveSource():
+---
+> #VSV:==
+> if proxy.IsSame(GetActiveSource()):
+449c414,415
+< if rep.Input == proxy:
+---
+> #VSV:==
+> if rep.Input.IsSame(proxy):
+453c419,420
+< if proxy == GetActiveView():
+---
+> ##VSV:==
+> if proxy.IsSame(GetActiveView()):
+691,693c658,659
+< activeModule = servermanager.ActiveConnection.Modules
+< for m in [activeModule.filters, activeModule.sources,
+< activeModule.writers, activeModule.animation]:
+---
+> for m in [servermanager.filters, servermanager.sources,
+> servermanager.writers, servermanager.animation]:
+699d664
+< #print "add %s function" % key
+703,715d667
+< def _remove_functions(g):
+< list = []
+< if servermanager.ActiveConnection:
+< list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_']
+<
+< for m in list:
+< dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__
+< for key in dt.keys():
+< cl = dt[key]
+< if not isinstance(cl, str) and g.has_key(key):
+< g.pop(key)
+< #print "remove %s function" % key
+<
+844c796
+< if cue.AnimatedProxy == proxy and\
+---
+> if cue.AnimatedProxy.IsSame(proxy) and\
+846c798
+< if index == None or index == cue.AnimatedElement:
+---
+> if index == None or index.IsSame(cue.AnimatedElement): ##index == cue.AnimatedElement:
+870c822
+< if cue.AnimatedProxy == view and\
+---
+> if cue.AnimatedProxy.IsSame(view) and\
+887c839
+< if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy == tk\
+---
+> if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy.IsSame(tk)\
+929,931c881
+< if not servermanager.ActiveConnection:
+< raise RuntimeError, "Cannot load a plugin without a session."
+< plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager()
+---
+> plm = servermanager.ProxyManager().GetSession().GetPluginManager()
+933,934c883
+< session = servermanager.ActiveConnection.Session
+< info = plm.GetRemoteInformation(session)
+---
+> info = plm.GetRemoteInformation()
+942,959d890
+< def GetLayouts():
+< """Returns the layout proxies on the active session.
+< Layout proxies are used to place views in a grid."""
+< return servermanager.ProxyManager().GetProxiesInGroup("layouts")
+<
+< def GetLayout(view=None):
+< """Return the layout containing the give view, if any.
+< If no view is specified, active view is used.
+< """
+< if not view:
+< view = GetActiveView()
+< if not view:
+< raise RuntimeError, "No active view was found."
+< layouts = GetLayouts()
+< for layout in layouts.values():
+< if layout.GetViewLocation(view) != -1:
+< return layout
+< return None
+966c897
+< def __get_selection_model(self, name, session=None):
+---
+> def __get_selection_model(self, name):
+968,970c899
+< if session and session != servermanager.ActiveConnection.Session:
+< raise RuntimeError, "Try to set an active object with invalid active connection."
+< pxm = servermanager.ProxyManager(session)
+---
+> pxm = servermanager.ProxyManager()
+979c908
+< active_view_model = self.__get_selection_model("ActiveView")
+---
+> active_view_model = self.__get_selection_model("ActiveView")
+981d909
+< active_view_model = self.__get_selection_model("ActiveView", view.GetSession())
+984d911
+< active_view_model = self.__get_selection_model("ActiveView")
+994c921
+< active_sources_model = self.__get_selection_model("ActiveSources")
+---
+> active_sources_model = self.__get_selection_model("ActiveSources")
+997d923
+< active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession())
+1000d925
+< active_sources_model = self.__get_selection_model("ActiveSources")
+1107a1033,1041
+> def PrintTrace():
+> print paravisSM.myParavis.GetTrace()
+>
+> def SaveTrace(fileName):
+> paravisSM.myParavis.SaveTrace(fileName)
+>
+>
+> _add_functions(globals())
+>
+1110,1111d1043
+< else:
+< _add_functions(globals())
+1113c1045,1046
+< active_objects = ActiveObjects()
+---
+> def ImportFile(theFileName):
+> paravisSM.ImportFile(theFileName)
+1115,1129c1048,1049
+< def _switchToActiveConnectionCallback(caller, event):
+< if servermanager:
+< session = servermanager.vtkSMProxyManager.GetProxyManager().GetActiveSession()
+< if session and ((not servermanager.ActiveConnection) or session != servermanager.ActiveConnection.Session):
+< switchActiveConnection(servermanager.GetConnectionFromSession(session))
+<
+< class ActiveSessionObserver:
+< def __init__(self):
+< self.ObserverTag = servermanager.vtkSMProxyManager.GetProxyManager().AddObserver(9753, _switchToActiveConnectionCallback)
+<
+< def __del__(self):
+< if servermanager:
+< servermanager.vtkSMProxyManager.GetProxyManager().RemoveObserver(self.ObserverTag)
+<
+< active_session_observer = ActiveSessionObserver()
+---
+> active_objects = ActiveObjects()
+> active_objects.view = GetRenderView()
"Import a file of any format supported by ParaView"
myParavis.ImportFile(theFileName)
-
-def createFunction(theName):
- "Create function - constructor of Paravis object"
- def MyFunction():
- return myParavis.CreateClass(theName)
- return MyFunction
-
-
-def createConstructors():
- "Create constructor functions according to list of extracted classes"
- g = globals()
- aClassNames = myParavis.GetClassesList();
- for aName in aClassNames:
- g[aName] = createFunction(aName)
-
-## Initialize of a PARAVIS interface
+## Initialize PARAVIS interface
myParavis = Initialize(orb, naming_service,lcc,myStudyManager,myStudy, 2)
-## Initialize constructor functions
-createConstructors()
-
## Initialize Paravis static objects
-vtkSMObject = vtkSMObject()
-vtkProcessModule = vtkProcessModule()
-vtkPVPythonModule = vtkPVPythonModule()
-vtkSMProxyManager = vtkSMProxyManager()
-
+#vtkSMObject = vtkSMObject()
+#vtkProcessModule = vtkProcessModule()
+#vtkPVPythonModule = vtkPVPythonModule()
+#vtkSMProxyManager = vtkSMProxyManager()
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-r"""servermanager is a module for using paraview server manager in Python.
-One can always use the server manager API directly. However, this module
-provides an interface easier to use from Python by wrapping several VTK
-classes around Python classes.
-
-Note that, upon load, this module will create several sub-modules: sources,
-filters and rendering. These modules can be used to instantiate specific
-proxy types. For a list, try "dir(servermanager.sources)"
-
-A simple example:
- from paraview.servermanager import *
-
- # Creates a new built-in session and makes it the active session.
- Connect()
-
- # Creates a new render view on the active session.
- renModule = CreateRenderView()
-
- # Create a new sphere proxy on the active session and register it
- # in the sources group.
- sphere = sources.SphereSource(registrationGroup="sources", ThetaResolution=16, PhiResolution=32)
-
- # Create a representation for the sphere proxy and adds it to the render
- # module.
- display = CreateRepresentation(sphere, renModule)
-
- renModule.StillRender()
+r""" This module is a direct forward to the initial
+'servermanager' module of ParaView.
"""
-
-
-import re, os, new, sys
+from paraview import servermanager
from paravis import *
-# VTN: Avoid paraview.* instructions in this file.
-# It leads to problems during execution.
-
-def _wrap_property(proxy, smproperty):
- """ Internal function.
- Given a server manager property and its domains, returns the
- appropriate python object.
- """
- property = None
- if smproperty.IsA("vtkSMStringVectorProperty"):
- al = smproperty.GetDomain("array_list")
- if al and al.IsA("vtkSMArraySelectionDomain") and \
- smproperty.GetRepeatable():
- property = ArrayListProperty(proxy, smproperty)
- elif al and al.IsA("vtkSMArrayListDomain") and smproperty.GetNumberOfElements() == 5:
- property = ArraySelectionProperty(proxy, smproperty)
- else:
- iter = smproperty.NewDomainIterator()
- isFileName = False
- while not iter.IsAtEnd():
- # Refer to BUG #9710 to see why optional domains need to be
- # ignored.
- if iter.GetDomain().IsA("vtkSMFileListDomain") and \
- iter.GetDomain().GetIsOptional() == 0 :
- isFileName = True
- break
- iter.Next()
- iter.UnRegister(None)
- if isFileName:
- property = FileNameProperty(proxy, smproperty)
- elif _make_name_valid(smproperty.GetXMLLabel()) == 'ColorArrayName':
- property = ColorArrayProperty(proxy, smproperty)
- else:
- property = VectorProperty(proxy, smproperty)
- elif smproperty.IsA("vtkSMVectorProperty"):
- if smproperty.IsA("vtkSMIntVectorProperty") and \
- smproperty.GetDomain("enum"):
- property = EnumerationProperty(proxy, smproperty)
- else:
- property = VectorProperty(proxy, smproperty)
- elif smproperty.IsA("vtkSMInputProperty"):
- property = InputProperty(proxy, smproperty)
- elif smproperty.IsA("vtkSMProxyProperty"):
- property = ProxyProperty(proxy, smproperty)
- else:
- property = Property(proxy, smproperty)
- return property
-
-class Proxy(object):
- """Proxy for a server side object. A proxy manages the lifetime of
- one or more server manager objects. It also provides an interface
- to set and get the properties of the server side objects. These
- properties are presented as Python properties. For example,
- you can set a property Foo using the following:
- proxy.Foo = (1,2)
- or
- proxy.Foo.SetData((1,2))
- or
- proxy.Foo[0:2] = (1,2)
- For more information, see the documentation of the property which
- you can obtain with
- help(proxy.Foo).
-
- This class also provides an iterator which can be used to iterate
- over all properties.
- eg:
- proxy = Proxy(proxy=smproxy)
- for property in proxy:
- print property
-
- For advanced users:
- This is a python class that wraps a vtkSMProxy.. Makes it easier to
- set/get properties.
- Instead of:
- proxy.GetProperty("Foo").SetElement(0, 1)
- proxy.GetProperty("Foo").SetElement(0, 2)
- you can do:
- proxy.Foo = (1,2)
- or
- proxy.Foo.SetData((1,2))
- or
- proxy.Foo[0:2] = (1,2)
- Instead of:
- proxy.GetProperty("Foo").GetElement(0)
- you can do:
- proxy.Foo.GetData()[0]
- or
- proxy.Foo[0]
- For proxy properties, you can use append:
- proxy.GetProperty("Bar").AddProxy(foo)
- you can do:
- proxy.Bar.append(foo)
- Properties support most of the list API. See VectorProperty and
- ProxyProperty documentation for details.
-
- Please note that some of the methods accessible through the Proxy
- class are not listed by help() because the Proxy objects forward
- unresolved attributes to the underlying object. To get the full list,
- see also dir(proxy.SMProxy). See also the doxygen based documentation
- of the vtkSMProxy C++ class.
- """
-
- def __init__(self, **args):
- """ Default constructor. It can be used to initialize properties
- by passing keyword arguments where the key is the name of the
- property. In addition registrationGroup and registrationName (optional)
- can be specified (as keyword arguments) to automatically register
- the proxy with the proxy manager. """
- self.add_attribute('Observed', None)
- self.add_attribute('ObserverTag', -1)
- self.add_attribute('_Proxy__Properties', {})
- self.add_attribute('_Proxy__LastAttrName', None)
- self.add_attribute('SMProxy', None)
- self.add_attribute('Port', 0)
-
- if 'port' in args:
- self.Port = args['port']
- del args['port']
-
- update = True
- if 'no_update' in args:
- if args['no_update']:
- update = False
- del args['no_update']
-
- if 'proxy' in args:
- self.InitializeFromProxy(args['proxy'])
- del args['proxy']
- else:
- self.Initialize(None, update)
- if 'registrationGroup' in args:
- registrationGroup = args['registrationGroup']
- del args['registrationGroup']
- registrationName = self.SMProxy.GetGlobalIDAsString()
- if 'registrationName' in args:
- registrationName = args['registrationName']
- del args['registrationName']
- pxm = ProxyManager()
- pxm.RegisterProxy(registrationGroup, registrationName, self.SMProxy)
- if update:
- self.UpdateVTKObjects()
- for key in args.keys():
- setattr(self, key, args[key])
- # Visit all properties so that they are created
- for prop in self:
- pass
-
- def __setattr__(self, name, value):
- try:
- setter = getattr(self.__class__, name)
- setter = setter.__set__
- except AttributeError:
- if not hasattr(self, name):
- raise AttributeError("Attribute %s does not exist. " % name +
- " This class does not allow addition of new attributes to avoid " +
- "mistakes due to typos. Use add_attribute() if you really want " +
- "to add this attribute.")
- self.__dict__[name] = value
- else:
- setter(self, value)
-
- def add_attribute(self, name, value):
- self.__dict__[name] = value
-
- def __del__(self):
- """Destructor. Cleans up all observers as well as remove
- the proxy from the _pyproxies dictionary"""
- # Make sure that we remove observers we added
- if self.Observed:
- observed = self.Observed
- tag = self.ObserverTag
- self.Observed = None
- self.ObserverTag = -1
- observed.RemoveObserver(tag)
- if _pyproxies and self.SMProxy and (self.SMProxy, self.Port) in _pyproxies:
- del _pyproxies[(self.SMProxy, self.Port)]
-
- def InitializeFromProxy(self, aProxy, update=True):
- """Constructor. Assigns proxy to self.SMProxy, updates the server
- object as well as register the proxy in _pyproxies dictionary."""
- import weakref
- self.SMProxy = aProxy
- if update:
- self.SMProxy.UpdateVTKObjects()
- _pyproxies[(self.SMProxy, self.Port)] = weakref.ref(self)
-
- def Initialize(self):
- "Overridden by the subclass created automatically"
- pass
-
- def __eq__(self, other):
- "Returns true if the underlying SMProxies are the same."
- if isinstance(other, Proxy):
- try:
- if self.Port != other.Port:
- return False
- except:
- pass
- ## VSV using IsSame instead ==
- return self.SMProxy.IsSame(other.SMProxy)
- return self.SMProxy.IsSame(other)
-
- def __ne__(self, other):
- "Returns false if the underlying SMProxies are the same."
- return not self.__eq__(other)
-
- def __iter__(self):
- "Creates an iterator for the properties."
- return PropertyIterator(self)
-
- def SetPropertyWithName(self, pname, arg):
- """Generic method for setting the value of a property."""
- prop = self.GetProperty(pname)
- if prop is None:
- raise RuntimeError, "Property %s does not exist. Please check the property name for typos." % pname
- prop.SetData(arg)
-
- def GetPropertyValue(self, name):
- """Returns a scalar for properties with 1 elements, the property
- itself for vectors."""
- p = self.GetProperty(name)
- if isinstance(p, VectorProperty):
- if p.GetNumberOfElements() == 1 and not p.GetRepeatable():
- if p.SMProperty.IsA("vtkSMStringVectorProperty") or not p.GetArgumentIsArray():
- return p[0]
- elif isinstance(p, InputProperty):
- if not p.GetMultipleInput():
- if len(p) > 0:
- return p[0]
- else:
- return None
- elif isinstance(p, ProxyProperty):
- if not p.GetRepeatable():
- if len(p) > 0:
- return p[0]
- else:
- return None
- return p
-
- def GetProperty(self, name):
- """Given a property name, returns the property object."""
- if name in self.__Properties and self.__Properties[name]():
- return self.__Properties[name]()
- smproperty = self.SMProxy.GetProperty(name)
- # Maybe they are looking by the label. Try to match that.
- if not smproperty:
- iter = PropertyIterator(self)
- for prop in iter:
- if name == _make_name_valid(iter.PropertyLabel):
- smproperty = prop.SMProperty
- break
- if smproperty:
- property = _wrap_property(self, smproperty)
- if property is not None:
- import weakref
- self.__Properties[name] = weakref.ref(property)
- return property
- return None
-
- def ListProperties(self):
- """Returns a list of all property names on this proxy."""
- property_list = []
- iter = self.__iter__()
- for property in iter:
- name = _make_name_valid(iter.PropertyLabel)
- if name:
- property_list.append(name)
- return property_list
-
- def __ConvertArgumentsAndCall(self, *args):
- """ Internal function.
- Used to call a function on SMProxy. Converts input and
- output values as appropriate.
- """
- newArgs = []
- for arg in args:
- if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
- newArgs.append(arg.SMProxy)
- else:
- newArgs.append(arg)
- func = getattr(self.SMProxy, self.__LastAttrName)
- retVal = func(*newArgs)
- if type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProxy"):
- return _getPyProxy(retVal)
- elif type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProperty"):
- return _wrap_property(self, retVal)
- else:
- return retVal
-
- def __GetActiveCamera(self):
- """ This method handles GetActiveCamera specially. It adds
- an observer to the camera such that everytime it is modified
- the render view updated"""
- import weakref
- c = self.SMProxy.GetActiveCamera()
- # VSV: Observers are not supported
-## if not c.HasObserver("ModifiedEvent"):
-## self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self)))
-## self.Observed = c
- return c
-
- def __getattr__(self, name):
- """With the exception of a few overloaded methods,
- returns the SMProxy method"""
- if not self.SMProxy:
- raise AttributeError("class %s has no attribute %s" % ("None", name))
- return None
- # Handle GetActiveCamera specially.
- if name == "GetActiveCamera" and \
- hasattr(self.SMProxy, "GetActiveCamera"):
- return self.__GetActiveCamera
- if name == "SaveDefinition" and hasattr(self.SMProxy, "SaveDefinition"):
- return self.__SaveDefinition
- # If not a property, see if SMProxy has the method
- try:
- proxyAttr = getattr(self.SMProxy, name)
- self.__LastAttrName = name
- return self.__ConvertArgumentsAndCall
- except:
- pass
- return getattr(self.SMProxy, name)
-
-class SourceProxy(Proxy):
- """Proxy for a source object. This class adds a few methods to Proxy
- that are specific to sources. It also provides access to the output
- ports. Output ports can be accessed by name or index:
- > op = source[0]
- or
- > op = source['some name'].
- """
- def UpdatePipeline(self, time=None):
- """This method updates the server-side VTK pipeline and the associated
- data information. Make sure to update a source to validate the output
- meta-data."""
- if time != None:
- self.SMProxy.UpdatePipeline(time)
- else:
- self.SMProxy.UpdatePipeline()
- # This is here to cause a receive
- # on the client side so that progress works properly.
- if ActiveConnection and ActiveConnection.IsRemote():
- self.SMProxy.GetDataInformation()
-
- def FileNameChanged(self):
- "Called when the filename of a source proxy is changed."
- self.UpdatePipelineInformation()
-
- def UpdatePipelineInformation(self):
- """This method updates the meta-data of the server-side VTK pipeline and
- the associated information properties"""
- self.SMProxy.UpdatePipelineInformation()
-
- def GetDataInformation(self, idx=None):
- """This method returns a DataInformation wrapper around a
- vtkPVDataInformation"""
- if idx == None:
- idx = self.Port
- if self.SMProxy:
- return DataInformation( \
- self.SMProxy.GetDataInformation(idx), \
- self.SMProxy, idx)
-
- def __getitem__(self, idx):
- """Given a slice, int or string, returns the corresponding
- output port"""
- if isinstance(idx, slice):
- indices = idx.indices(self.SMProxy.GetNumberOfOutputPorts())
- retVal = []
- for i in range(*indices):
- retVal.append(OutputPort(self, i))
- return retVal
- elif isinstance(idx, int):
- if idx >= self.SMProxy.GetNumberOfOutputPorts() or idx < 0:
- raise IndexError
- return OutputPort(self, idx)
- else:
- return OutputPort(self, self.SMProxy.GetOutputPortIndex(idx))
-
- def GetPointDataInformation(self):
- """Returns the associated point data information."""
- self.UpdatePipeline()
- return FieldDataInformation(self.SMProxy, self.Port, "PointData")
-
- def GetCellDataInformation(self):
- """Returns the associated cell data information."""
- self.UpdatePipeline()
- return FieldDataInformation(self.SMProxy, self.Port, "CellData")
-
- def GetFieldDataInformation(self):
- """Returns the associated cell data information."""
- self.UpdatePipeline()
- return FieldDataInformation(self.SMProxy, self.Port, "FieldData")
-
- PointData = property(GetPointDataInformation, None, None, "Returns point data information")
- CellData = property(GetCellDataInformation, None, None, "Returns cell data information")
- FieldData = property(GetFieldDataInformation, None, None, "Returns field data information")
-
-
-class ExodusIIReaderProxy(SourceProxy):
- """Special class to define convenience functions for array
- selection."""
-
- def FileNameChanged(self):
- "Called when the filename changes. Selects all variables."
- SourceProxy.FileNameChanged(self)
- self.SelectAllVariables()
-
- def SelectAllVariables(self):
- "Select all available variables for reading."
- for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
- 'ElementVariables', 'GlobalVariables'):
- f = getattr(self, prop)
- f.SelectAll()
-
- def DeselectAllVariables(self):
- "Deselects all variables."
- for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
- 'ElementVariables', 'GlobalVariables'):
- f = getattr(self, prop)
- f.DeselectAll()
-
-class ViewLayoutProxy(Proxy):
- """Special class to define convenience methods for View Layout"""
-
- def SplitViewHorizontal(self, view, fraction=0.5):
- """Split the cell containing the specified view horizontally.
- If no fraction is specified, the frame is split into equal parts.
- On success returns a positve number that identifying the new cell
- location that can be used to assign view to, or split further.
- Return -1 on failure."""
- location = self.GetViewLocation(view)
- if location == -1:
- raise RuntimeError, "View is not present in this layout."
- if fraction < 0.0 or fraction > 1.0:
- raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]"
- return self.SMProxy.SplitHorizontal(location, fraction)
-
- def SplitViewVertical(self, view=None, fraction=0.5):
- """Split the cell containing the specified view horizontally.
- If no view is specified, active view is used.
- If no fraction is specified, the frame is split into equal parts.
- On success returns a positve number that identifying the new cell
- location that can be used to assign view to, or split further.
- Return -1 on failure."""
- location = self.GetViewLocation(view)
- if location == -1:
- raise RuntimeError, "View is not present in this layout."
- if fraction < 0.0 or fraction > 1.0:
- raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]"
- return self.SMProxy.SplitVertical(location, fraction)
-
- def AssignView(self, location, view):
- """Assign a view at a particular location. Note that the view's position may
- be changed by subsequent Split() calls. Returns true on success."""
- viewproxy = None
- if isinstance(view, Proxy):
- view = view.SMProxy
- return self.SMProxy.AssignView(location, view)
-
- def GetViewLocation(self, view):
- if isinstance(view, Proxy):
- view = view.SMProxy
- return self.SMProxy.GetViewLocation(view)
-
-class Property(object):
- """Generic property object that provides access to one of the properties of
- a server object. This class does not allow setting/getting any values but
- provides an interface to update a property using __call__. This can be used
- for command properties that correspond to function calls without arguments.
- For example,
- > proxy.Foo()
- would push a Foo property which may cause the proxy to call a Foo method
- on the actual VTK object.
-
- For advanced users:
- Python wrapper around a vtkSMProperty with a simple interface.
- In addition to all method provided by vtkSMProperty (obtained by
- forwarding unknown attributes requests to the underlying SMProxy),
- Property and sub-class provide a list API.
-
- Please note that some of the methods accessible through the Property
- class are not listed by help() because the Property objects forward
- unresolved attributes to the underlying object. To get the full list,
- see also dir(proxy.SMProperty). See also the doxygen based documentation
- of the vtkSMProperty C++ class.
- """
- def __init__(self, proxy, smproperty):
- """Default constructor. Stores a reference to the proxy."""
- import weakref
- self.SMProperty = smproperty
- self.Proxy = proxy
-
- def __repr__(self):
- """Returns a string representation containing property name
- and value"""
- if not type(self) is Property:
- if self.GetData() is not None:
- repr = self.GetData().__repr__()
- else:
- repr = "None"
- else:
- repr = "Property name= "
- name = self.Proxy.GetPropertyName(self.SMProperty)
- if name:
- repr += name
- else:
- repr += "Unknown"
-
- return repr
-
- def __call__(self):
- """Forces a property update using InvokeCommand."""
- if type(self) is Property:
- self.Proxy.SMProxy.InvokeCommand(self._FindPropertyName())
- else:
- raise RuntimeError, "Cannot invoke this property"
-
- def _FindPropertyName(self):
- "Returns the name of this property."
- return self.Proxy.GetPropertyName(self.SMProperty)
-
- def _UpdateProperty(self):
- "Pushes the value of this property to the server."
- # For now, we are updating all properties. This is due to an
- # issue with the representations. Their VTK objects are not
- # created until Input is set therefore, updating a property
- # has no effect. Updating all properties everytime one is
- # updated has the effect of pushing values set before Input
- # when Input is updated.
- # self.Proxy.SMProxy.UpdateProperty(self._FindPropertyName())
- self.Proxy.SMProxy.UpdateVTKObjects()
-
- def __getattr__(self, name):
- "Unknown attribute requests get forwarded to SMProperty."
- return getattr(self.SMProperty, name)
-
- Name = property(_FindPropertyName, None, None,
- "Returns the name for the property")
-
-class GenericIterator(object):
- """Iterator for container type objects"""
-
- def __init__(self, obj):
- self.Object = obj
- self.index = 0
-
- def __iter__(self):
- return self
-
- def next(self):
- if self.index >= len(self.Object):
- raise StopIteration
-
- idx = self.index
- self.index += 1
- return self.Object[idx]
-
-class VectorProperty(Property):
- """A VectorProperty provides access to one or more values. You can use
- a slice to get one or more property values:
- > val = property[2]
- or
- > vals = property[0:5:2]
- You can use a slice to set one or more property values:
- > property[2] = val
- or
- > property[1:3] = (1,2)
- """
- def ConvertValue(self, value):
- return value
-
- def __len__(self):
- """Returns the number of elements."""
- return self.SMProperty.GetNumberOfElements()
-
- def __iter__(self):
- """Implementation of the sequence API"""
- return GenericIterator(self)
-
- def __setitem__(self, idx, value):
- """Given a list or tuple of values, sets a slice of values [min, max)"""
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- for i, j in zip(range(*indices), value):
- self.SMProperty.SetElement(i, self.ConvertValue(j))
- self._UpdateProperty()
- elif idx >= len(self) or idx < 0:
- raise IndexError
- else:
- self.SMProperty.SetElement(idx, self.ConvertValue(value))
- self._UpdateProperty()
-
- def GetElement(self, index):
- return self.SMProperty.GetElement(index)
-
- def __getitem__(self, idx):
- """Returns the range [min, max) of elements. Raises an IndexError
- exception if an argument is out of bounds."""
- ls = len(self)
- if isinstance(idx, slice):
- indices = idx.indices(ls)
- retVal = []
- for i in range(*indices):
- retVal.append(self.GetElement(i))
- return retVal
- elif idx >= ls:
- raise IndexError
- elif idx < 0:
- idx = ls + idx
- if idx < 0:
- raise IndexError
-
- return self.GetElement(idx)
-
- def GetData(self):
- "Returns all elements as either a list or a single value."
- property = self.SMProperty
- if property.GetRepeatable() or \
- property.GetNumberOfElements() > 1:
- return self[0:len(self)]
- elif property.GetNumberOfElements() == 1:
- return self.GetElement(0)
-
- def SetData(self, values):
- """Allows setting of all values at once. Requires a single value or
- a iterable object."""
- if not hasattr(values, "__iter__"):
- values = (values,)
- if not self.GetRepeatable() and len(values) != self.GetNumberOfElements():
- raise RuntimeError("This property requires %d values." % self.GetNumberOfElements())
- if self.GetRepeatable():
- # Clean up first
- self.SMProperty.SetNumberOfElements(0)
- idx = 0
- for val in values:
- self.SMProperty.SetElement(idx, self.ConvertValue(val))
- idx += 1
- self._UpdateProperty()
-
- def Clear(self):
- "Removes all elements."
- self.SMProperty().SetNumberOfElements(0)
- self._UpdateProperty()
-
-class ColorArrayProperty(VectorProperty):
- """This subclass of VectorProperty handles setting of the array to
- color by. It handles attribute type as well as well array name."""
-
- def GetAvailable(self):
- """Returns the list of available arrays as (attribute type, array name
- tuples."""
- arrays = []
- for a in self.Proxy.Input.PointData:
- arrays.append(('POINT_DATA', a.GetName()))
- for a in self.Proxy.Input.CellData:
- arrays.append(('CELL_DATA', a.GetName()))
- return arrays
-
- def SetData(self, value):
- """Overwritten to enable setting attribute type (the ColorAttributeType
- property and the array name. The argument should be the array name
- (in which case the first appropriate attribute type is picked) or
- a tuple of attribute type and array name."""
- if isinstance(value, tuple) and len(value) == 2:
- att = value[0]
- arr = value[1]
- elif isinstance(value, str):
- att = None
- arr = value
- else:
- raise ValueError("Expected a tuple of 2 values or a string.")
-
- if not arr:
- self.SMProperty.SetElement(0, '')
- self._UpdateProperty()
- return
-
- found = False
- for a in self.Available:
- if a[1] == arr and (not att or att == a[0]):
- att = a[0]
- found = True
- break
-
- if not found:
- pvoptions = vtkProcessModule.GetProcessModule().GetOptions()
- # if this process is from a parallel batch run in symmetric mpi mode
- # then we may not have any points or cells on some processes in which
- # case we'll probably be missing the point and cell data too. the
- # check below makes sure that we avoid this situation.
- if pvoptions.GetProcessType() != 0x40 or pvoptions.GetSymmetricMPIMode() == False \
- or len(self.Available) != 0:
- raise ValueError("Could not locate array %s in the input." % arr)
-
- catt = self.Proxy.GetProperty("ColorAttributeType")
- if att != None:
- catt.SetData(att)
- self.SMProperty.SetElement(0, arr)
- self._UpdateProperty()
-
- Available = property(GetAvailable, None, None, \
- "This read-only property returns the list of arrays that can be colored by.")
-
-
-class EnumerationProperty(VectorProperty):
- """Subclass of VectorProperty that is applicable for enumeration type
- properties."""
-
- def GetElement(self, index):
- """Returns the text for the given element if available. Returns
- the numerical values otherwise."""
- val = self.SMProperty.GetElement(index)
- domain = self.SMProperty.GetDomain("enum")
- for i in range(domain.GetNumberOfEntries()):
- if domain.GetEntryValue(i) == val:
- return domain.GetEntryText(i)
- return val
-
- def ConvertValue(self, value):
- """Converts value to type suitable for vtSMProperty::SetElement()"""
- if type(value) == str:
- domain = self.SMProperty.GetDomain("enum")
- if domain.HasEntryText(value):
- return domain.GetEntryValueForText(value)
- else:
- raise ValueError("%s is not a valid value." % value)
- return VectorProperty.ConvertValue(self, value)
-
- def GetAvailable(self):
- "Returns the list of available values for the property."
- retVal = []
- domain = self.SMProperty.GetDomain("enum")
- for i in range(domain.GetNumberOfEntries()):
- retVal.append(domain.GetEntryText(i))
- return retVal
-
- Available = property(GetAvailable, None, None, \
- "This read-only property contains the list of values that can be applied to this property.")
-
-
-class FileNameProperty(VectorProperty):
- """Property to set/get one or more file names.
- This property updates the pipeline information everytime its value changes.
- This is used to keep the array lists up to date."""
-
- def _UpdateProperty(self):
- "Pushes the value of this property to the server."
- VectorProperty._UpdateProperty(self)
- self.Proxy.FileNameChanged()
-
-class ArraySelectionProperty(VectorProperty):
- "Property to select an array to be processed by a filter."
-
- def GetAssociation(self):
- val = self.GetElement(3)
- if val == "":
- return None
- for key, value in ASSOCIATIONS.iteritems():
- if value == int(val):
- return key
-
- return None
-
- def GetArrayName(self):
- return self.GetElement(4)
-
- def __len__(self):
- """Returns the number of elements."""
- return 2
-
- def __setitem__(self, idx, value):
- raise RuntimeError, "This property cannot be accessed using __setitem__"
-
- def __getitem__(self, idx):
- """Returns attribute type for index 0, array name for index 1"""
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- retVal = []
- for i in range(*indices):
- if i >= 2 or i < 0:
- raise IndexError
- if i == 0:
- retVal.append(self.GetAssociation())
- else:
- retVal.append(self.GetArrayName())
- return retVal
- elif idx >= 2 or idx < 0:
- raise IndexError
-
- if i == 0:
- return self.GetAssociation()
- else:
- return self.GetArrayName()
-
- def SetData(self, values):
- """Allows setting of all values at once. Requires a single value,
- a tuple or list."""
- if not isinstance(values, tuple) and \
- not isinstance(values, list):
- values = (values,)
- if len(values) == 1:
- self.SMProperty.SetElement(4, values[0])
- elif len(values) == 2:
- if isinstance(values[0], str):
- val = str(ASSOCIATIONS[values[0]])
- else:
- # In case user didn't specify valid association,
- # just pick POINTS.
- val = str(ASSOCIATIONS['POINTS'])
- self.SMProperty.SetElement(3, str(val))
- self.SMProperty.SetElement(4, values[1])
- else:
- raise RuntimeError, "Expected 1 or 2 values."
- self._UpdateProperty()
-
- def UpdateDefault(self):
- "Helper method to set default values."
- if self.SMProperty.GetNumberOfElements() != 5:
- return
- if self.GetElement(4) != '' or \
- self.GetElement(3) != '':
- return
-
- for i in range(0,3):
- if self.GetElement(i) == '':
- self.SMProperty.SetElement(i, '0')
- al = self.SMProperty.GetDomain("array_list")
- al.Update(self.SMProperty)
- al.SetDefaultValues(self.SMProperty)
-
-class ArrayListProperty(VectorProperty):
- """This property provides a simpler interface for selecting arrays.
- Simply assign a list of arrays that should be loaded by the reader.
- Use the Available property to get a list of available arrays."""
-
- def __init__(self, proxy, smproperty):
- VectorProperty.__init__(self, proxy, smproperty)
- self.__arrays = []
-
- def GetAvailable(self):
- "Returns the list of available arrays"
- dm = self.GetDomain("array_list")
- retVal = []
- for i in range(dm.GetNumberOfStrings()):
- retVal.append(dm.GetString(i))
- return retVal
-
- Available = property(GetAvailable, None, None, \
- "This read-only property contains the list of items that can be read by a reader.")
-
- def SelectAll(self):
- "Selects all arrays."
- self.SetData(self.Available)
-
- def DeselectAll(self):
- "Deselects all arrays."
- self.SetData([])
-
- def __iter__(self):
- """Implementation of the sequence API"""
- return GenericIterator(self)
-
- def __len__(self):
- """Returns the number of elements."""
- return len(self.GetData())
-
- def __setitem__(self, idx, value):
- """Given a list or tuple of values, sets a slice of values [min, max)"""
- self.GetData()
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- for i, j in zip(range(*indices), value):
- self.__arrays[i] = j
- self.SetData(self.__arrays)
- elif idx >= len(self) or idx < 0:
- raise IndexError
- else:
- self.__arrays[idx] = self.ConvertValue(value)
- self.SetData(self.__arrays)
-
- def __getitem__(self, idx):
- """Returns the range [min, max) of elements. Raises an IndexError
- exception if an argument is out of bounds."""
- self.GetData()
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- retVal = []
- for i in range(*indices):
- retVal.append(self.__arrays[i])
- return retVal
- elif idx >= len(self) or idx < 0:
- raise IndexError
- return self.__arrays[idx]
-
- def SetData(self, values):
- """Allows setting of all values at once. Requires a single value,
- a tuple or list."""
- # Clean up first
- iup = self.SMProperty.GetImmediateUpdate()
- self.SMProperty.SetImmediateUpdate(False)
- # Clean up first
- self.SMProperty.SetNumberOfElements(0)
- if not isinstance(values, tuple) and \
- not isinstance(values, list):
- values = (values,)
- fullvalues = []
-
- # WARNING:
- # The order of the two loops below are delibrately set in this way
- # so that values passed in will take precedence.
- # This is needed for backward compatibility of the
- # property ElementBlocks for vtkExodusIIReader.
- # If you attemp to change this, please verify that
- # python state files for opening old .ex2 file (<=3.14) still works.
- for array in self.Available:
- if not values.__contains__(array):
- fullvalues.append(array)
- fullvalues.append('0')
-
- for i in range(len(values)):
- val = self.ConvertValue(values[i])
- fullvalues.append(val)
- fullvalues.append('1')
-
-
- i = 0
- for value in fullvalues:
- self.SMProperty.SetElement(i, value)
- i += 1
-
- self._UpdateProperty()
- self.SMProperty.SetImmediateUpdate(iup)
-
- def GetData(self):
- "Returns all elements as a list."
- property = self.SMProperty
- nElems = property.GetNumberOfElements()
- if nElems%2 != 0:
- raise ValueError, "The SMProperty with XML label '%s' has a size that is not a multiple of 2." % property.GetXMLLabel()
- self.__arrays = []
- for i in range(0, nElems, 2):
- if self.GetElement(i+1) != '0':
- self.__arrays.append(self.GetElement(i))
- return list(self.__arrays)
-
-class ProxyProperty(Property):
- """A ProxyProperty provides access to one or more proxies. You can use
- a slice to get one or more property values:
- > proxy = property[2]
- or
- > proxies = property[0:5:2]
- You can use a slice to set one or more property values:
- > property[2] = proxy
- or
- > property[1:3] = (proxy1, proxy2)
- You can also append and delete:
- > property.append(proxy)
- and
- > del property[1:2]
-
- You can also remove all elements with Clear().
-
- Note that some properties expect only 1 proxy and will complain if
- you set the number of values to be something else.
- """
- def __init__(self, proxy, smproperty):
- """Default constructor. Stores a reference to the proxy. Also looks
- at domains to find valid values."""
- Property.__init__(self, proxy, smproperty)
- # Check to see if there is a proxy list domain and, if so,
- # initialize ourself. (Should this go in ProxyProperty?)
- listdomain = self.GetDomain('proxy_list')
- if listdomain:
- if listdomain.GetClassName() != 'vtkSMProxyListDomain':
- raise ValueError, "Found a 'proxy_list' domain on an InputProperty that is not a ProxyListDomain."
- pm = ProxyManager()
- group = "pq_helper_proxies." + proxy.GetGlobalIDAsString()
- if listdomain.GetNumberOfProxies() == 0:
- for i in xrange(listdomain.GetNumberOfProxyTypes()):
- igroup = listdomain.GetProxyGroup(i)
- name = listdomain.GetProxyName(i)
- iproxy = CreateProxy(igroup, name)
- listdomain.AddProxy(iproxy)
- pm.RegisterProxy(group, proxy.GetPropertyName(smproperty), iproxy)
- listdomain.SetDefaultValues(self.SMProperty)
-
- def GetAvailable(self):
- """If this proxy has a list domain, then this function returns the
- strings you can use to select from the domain. If there is no such
- list domain, the returned list is empty."""
- listdomain = self.GetDomain('proxy_list')
- retval = []
- if listdomain:
- for i in xrange(listdomain.GetNumberOfProxies()):
- proxy = listdomain.GetProxy(i)
- retval.append(proxy.GetXMLLabel())
- return retval
-
- Available = property(GetAvailable, None, None,
- """This read only property is a list of strings you can
- use to select from the list domain. If there is no
- such list domain, the array is empty.""")
-
- def __iter__(self):
- """Implementation of the sequence API"""
- return GenericIterator(self)
-
- def __len__(self):
- """Returns the number of elements."""
- return self.SMProperty.GetNumberOfProxies()
-
- def remove(self, proxy):
- """Removes the first occurence of the proxy from the property."""
- self.SMProperty.RemoveProxy(proxy.SMProxy)
- self._UpdateProperty()
-
- def __setitem__(self, idx, value):
- """Given a list or tuple of values, sets a slice of values [min, max)"""
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- for i, j in zip(range(*indices), value):
- self.SMProperty.SetProxy(i, j.SMProxy)
- self._UpdateProperty()
- elif idx >= len(self) or idx < 0:
- raise IndexError
- else:
- self.SMProperty.SetProxy(idx, value.SMProxy)
- self._UpdateProperty()
-
- def __delitem__(self,idx):
- """Removes the element idx"""
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- # Collect the elements to delete to a new list first.
- # Otherwise indices are screwed up during the actual
- # remove loop.
- toremove = []
- for i in range(*indices):
- toremove.append(self[i])
- for i in toremove:
- self.SMProperty.RemoveProxy(i.SMProxy)
- self._UpdateProperty()
- elif idx >= len(self) or idx < 0:
- raise IndexError
- else:
- self.SMProperty.RemoveProxy(self[idx].SMProxy)
- self._UpdateProperty()
-
- def __getitem__(self, idx):
- """Returns the range [min, max) of elements. Raises an IndexError
- exception if an argument is out of bounds."""
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- retVal = []
- for i in range(*indices):
- retVal.append(_getPyProxy(self.SMProperty.GetProxy(i)))
- return retVal
- elif idx >= len(self) or idx < 0:
- raise IndexError
- return _getPyProxy(self.SMProperty.GetProxy(idx))
-
- def __getattr__(self, name):
- "Unknown attribute requests get forwarded to SMProperty."
- return getattr(self.SMProperty, name)
-
- def index(self, proxy):
- idx = 0
- for px in self:
- ## VSV: ==
- if proxy.IsSame(px):
- return idx
- idx += 1
- raise ValueError("proxy is not in the list.")
-
- def append(self, proxy):
- "Appends the given proxy to the property values."
- self.SMProperty.AddProxy(proxy.SMProxy)
- self._UpdateProperty()
-
- def GetData(self):
- "Returns all elements as either a list or a single value."
- property = self.SMProperty
- if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
- return self[0:len(self)]
- else:
- if property.GetNumberOfProxies() > 0:
- return _getPyProxy(property.GetProxy(0))
- return None
-
- def SetData(self, values):
- """Allows setting of all values at once. Requires a single value,
- a tuple or list."""
- if isinstance(values, str):
- position = -1
- try:
- position = self.Available.index(values)
- except:
- raise ValueError, values + " is not a valid object in the domain."
- values = self.GetDomain('proxy_list').GetProxy(position)
- if not isinstance(values, tuple) and \
- not isinstance(values, list):
- values = (values,)
- self.SMProperty.RemoveAllProxies()
- for value in values:
- if isinstance(value, Proxy):
- value_proxy = value.SMProxy
- else:
- value_proxy = value
- self.SMProperty.AddProxy(value_proxy)
- self._UpdateProperty()
-
- def Clear(self):
- "Removes all elements."
- self.SMProperty.RemoveAllProxies()
- self._UpdateProperty()
-
-class InputProperty(ProxyProperty):
- """An InputProperty allows making pipeline connections. You can set either
- a source proxy or an OutputProperty to an input property:
-
- > property[0] = proxy
- or
- > property[0] = OuputPort(proxy, 1)
-
- > property.append(proxy)
- or
- > property.append(OutputPort(proxy, 0))
- """
- def __setitem__(self, idx, value):
- """Given a list or tuple of values, sets a slice of values [min, max)"""
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- for i, j in zip(range(*indices), value):
- op = value[i-min]
- self.SMProperty.SetInputConnection(i, op.SMProxy, op.Port)
- self._UpdateProperty()
- elif idx >= len(self) or idx < 0:
- raise IndexError
- else:
- self.SMProperty.SetInputConnection(idx, value.SMProxy, value.Port)
- self._UpdateProperty()
-
- def __getitem__(self, idx):
- """Returns the range [min, max) of elements. Raises an IndexError
- exception if an argument is out of bounds."""
- if isinstance(idx, slice):
- indices = idx.indices(len(self))
- retVal = []
- for i in range(*indices):
- port = None
- if self.SMProperty.GetProxy(i):
- port = OutputPort(_getPyProxy(self.SMProperty.GetProxy(i)),\
- self.SMProperty.GetOutputPortForConnection(i))
- retVal.append(port)
- return retVal
- elif idx >= len(self) or idx < 0:
- raise IndexError
- return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\
- self.SMProperty.GetOutputPortForConnection(idx))
-
- def append(self, value):
- """Appends the given proxy to the property values.
- Accepts Proxy or OutputPort objects."""
- self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
- self._UpdateProperty()
-
- def GetData(self):
- """Returns all elements as either a list of OutputPort objects or
- a single OutputPort object."""
- property = self.SMProperty
- if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
- return self[0:len(self)]
- else:
- if property.GetNumberOfProxies() > 0:
- return OutputPort(_getPyProxy(property.GetProxy(0)),\
- self.SMProperty.GetOutputPortForConnection(0))
- return None
-
- def SetData(self, values):
- """Allows setting of all values at once. Requires a single value,
- a tuple or list. Accepts Proxy or OutputPort objects."""
- if isinstance(values, str):
- ProxyProperty.SetData(self, values)
- return
- if not isinstance(values, tuple) and \
- not isinstance(values, list):
- values = (values,)
- self.SMProperty.RemoveAllProxies()
- for value in values:
- if value:
- self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
- self._UpdateProperty()
-
- def _UpdateProperty(self):
- "Pushes the value of this property to the server."
- ProxyProperty._UpdateProperty(self)
- iter = PropertyIterator(self.Proxy)
- for prop in iter:
- if isinstance(prop, ArraySelectionProperty):
- prop.UpdateDefault()
-
-
-class DataInformation(object):
- """DataInformation is a contained for meta-data associated with an
- output data.
-
- DataInformation is a python wrapper around a vtkPVDataInformation.
- In addition to proving all methods of a vtkPVDataInformation, it provides
- a few convenience methods.
-
- Please note that some of the methods accessible through the DataInformation
- class are not listed by help() because the DataInformation objects forward
- unresolved attributes to the underlying object. To get the full list,
- see also dir(proxy.DataInformation).
- See also the doxygen based documentation of the vtkPVDataInformation C++
- class.
- """
- def __init__(self, dataInformation, proxy, idx):
- """Default constructor. Requires a vtkPVDataInformation, a source proxy
- and an output port id."""
- self.DataInformation = dataInformation
- self.Proxy = proxy
- self.Idx = idx
-
- def Update(self):
- """****Deprecated**** There is no reason anymore to use this method
- explicitly, it is called automatically when one gets any value from the
- data information object.
- Update the data information if necessary. Note that this
- does not cause execution of the underlying object. In certain
- cases, you may have to call UpdatePipeline() on the proxy."""
- if self.Proxy:
- self.Proxy.GetDataInformation(self.Idx)
-
- def GetDataSetType(self):
- """Returns the dataset type as defined in vtkDataObjectTypes."""
- self.Update()
- if not self.DataInformation:
- raise RuntimeError, "No data information is available"
- if self.DataInformation.GetCompositeDataSetType() > -1:
- return self.DataInformation.GetCompositeDataSetType()
- return self.DataInformation.GetDataSetType()
-
- def GetDataSetTypeAsString(self):
- """Returns the dataset type as a user-friendly string. This is
- not the same as the enumaration used by VTK"""
- return vtk.vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType())
-
- def __getattr__(self, name):
- """Forwards unknown attribute requests to the underlying
- vtkPVInformation."""
- if not self.DataInformation:
- raise AttributeError("class has no attribute %s" % name)
- return None
- self.Update()
- return getattr(self.DataInformation, name)
-
-class ArrayInformation(object):
- """Meta-information associated with an array. Use the Name
- attribute to get the array name.
-
- Please note that some of the methods accessible through the ArrayInformation
- class are not listed by help() because the ArrayInformation objects forward
- unresolved attributes to the underlying object.
- See the doxygen based documentation of the vtkPVArrayInformation C++
- class for a full list.
- """
- def __init__(self, proxy, field, name):
- self.Proxy = proxy
- self.FieldData = field
- self.Name = name
-
- def __getattr__(self, name):
- """Forward unknown methods to vtkPVArrayInformation"""
- array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
- if not array: return None
- return getattr(array, name)
-
- def __repr__(self):
- """Returns a user-friendly representation string."""
- return "Array: " + self.Name
-
- def GetRange(self, component=0):
- """Given a component, returns its value range as a tuple of 2 values."""
- array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
- range = array.GetComponentRange(component)
- return (range[0], range[1])
-
-class FieldDataInformationIterator(object):
- """Iterator for FieldDataInformation"""
-
- def __init__(self, info, items=False):
- self.FieldDataInformation = info
- self.index = 0
- self.items = items
-
- def __iter__(self):
- return self
-
- def next(self):
- if self.index >= self.FieldDataInformation.GetNumberOfArrays():
- raise StopIteration
-
- self.index += 1
- ai = self.FieldDataInformation[self.index-1]
- if self.items:
- return (ai.GetName(), ai)
- else:
- return ai
-
-
-class FieldDataInformation(object):
- """Meta-data for a field of an output object (point data, cell data etc...).
- Provides easy access to the arrays using the slice interface:
- > narrays = len(field_info)
- > for i in range(narrays):
- > array_info = field_info[i]
-
- Full slice interface is supported:
- > arrays = field_info[0:5:3]
- where arrays is a list.
-
- Array access by name is also possible:
- > array_info = field_info['Temperature']
-
- The number of arrays can also be accessed using the NumberOfArrays
- property.
- """
- def __init__(self, proxy, idx, field):
- self.Proxy = proxy
- self.OutputPort = idx
- self.FieldData = field
-
- def GetFieldData(self):
- """Convenience method to get the underlying
- vtkPVDataSetAttributesInformation"""
- return getattr(self.Proxy.GetDataInformation(self.OutputPort), "Get%sInformation" % self.FieldData)()
-
- def GetNumberOfArrays(self):
- """Returns the number of arrays."""
- self.Proxy.UpdatePipeline()
- return self.GetFieldData().GetNumberOfArrays()
-
- def GetArray(self, idx):
- """Given an index or a string, returns an array information.
- Raises IndexError if the index is out of bounds."""
- self.Proxy.UpdatePipeline()
- if not self.GetFieldData().GetArrayInformation(idx):
- return None
- if isinstance(idx, str):
- return ArrayInformation(self.Proxy, self, idx)
- elif idx >= len(self) or idx < 0:
- raise IndexError
- return ArrayInformation(self.Proxy, self, self.GetFieldData().GetArrayInformation(idx).GetName())
-
- def __len__(self):
- """Returns the number of arrays."""
- return self.GetNumberOfArrays()
-
- def __getitem__(self, idx):
- """Implements the [] operator. Accepts an array name."""
- if isinstance(idx, slice):
- indices = idx.indices(self.GetNumberOfArrays())
- retVal = []
- for i in range(*indices):
- retVal.append(self.GetArray(i))
- return retVal
- return self.GetArray(idx)
-
- def keys(self):
- """Implementation of the dictionary API"""
- kys = []
- narrays = self.GetNumberOfArrays()
- for i in range(narrays):
- kys.append(self.GetArray(i).GetName())
- return kys
-
- def values(self):
- """Implementation of the dictionary API"""
- vals = []
- narrays = self.GetNumberOfArrays()
- for i in range(narrays):
- vals.append(self.GetArray(i))
- return vals
-
- def iteritems(self):
- """Implementation of the dictionary API"""
- return FieldDataInformationIterator(self, True)
-
- def items(self):
- """Implementation of the dictionary API"""
- itms = []
- narrays = self.GetNumberOfArrays()
- for i in range(narrays):
- ai = self.GetArray(i)
- itms.append((ai.GetName(), ai))
- return itms
-
- def has_key(self, key):
- """Implementation of the dictionary API"""
- if self.GetArray(key):
- return True
- return False
-
- def __iter__(self):
- """Implementation of the dictionary API"""
- return FieldDataInformationIterator(self)
-
- def __getattr__(self, name):
- """Forwards unknown attributes to the underlying
- vtkPVDataSetAttributesInformation"""
- array = self.GetArray(name)
- if array: return array
- raise AttributeError("class has no attribute %s" % name)
- return None
-
- NumberOfArrays = property(GetNumberOfArrays, None, None, "Returns the number of arrays.")
-
-def OutputPort(proxy, outputPort=0):
- if not Proxy:
- return None
- if isinstance(outputPort, str):
- outputPort = proxy.GetOutputPortIndex(outputPort)
- if outputPort >= proxy.GetNumberOfOutputPorts():
- return None
- if proxy.Port == outputPort:
- return proxy
- newinstance = _getPyProxy(proxy.SMProxy, outputPort)
- newinstance.Port = outputPort
- newinstance._Proxy__Properties = proxy._Proxy__Properties
- return newinstance
-
-class ProxyManager(object):
- """When running scripts from the python shell in the ParaView application,
- registering proxies with the proxy manager is the only mechanism to
- notify the graphical user interface (GUI) that a proxy
- exists. Therefore, unless a proxy is registered, it will not show up in
- the user interface. Also, the proxy manager is the only way to get
- access to proxies created using the GUI. Proxies created using the GUI
- are automatically registered under an appropriate group (sources,
- filters, representations and views). To get access to these objects,
- you can use proxyManager.GetProxy(group, name). The name is the same
- as the name shown in the pipeline browser.
-
- This class is a python wrapper for vtkSMProxyManager. Note that the
- underlying vtkSMProxyManager is a singleton. All instances of this
- class will refer to the same object. In addition to all methods provided by
- vtkSMProxyManager (all unknown attribute requests are forwarded
- to the vtkSMProxyManager), this class provides several convenience
- methods.
-
- Please note that some of the methods accessible through the ProxyManager
- class are not listed by help() because the ProxyManager objects forwards
- unresolved attributes to the underlying object. To get the full list,
- see also dir(proxy.SMProxyManager). See also the doxygen based documentation
- of the vtkSMProxyManager C++ class.
- """
-
- def __init__(self, session=None):
- """Constructor. Assigned self.SMProxyManager to
- vtkSMProxyManager.GetProxyManager()."""
- global ActiveConnection
- if not session:
- session = ActiveConnection.Session
- self.SMProxyManager = session.GetSessionProxyManager()
-
- def RegisterProxy(self, group, name, aProxy):
- """Registers a proxy (either SMProxy or proxy) with the
- server manager"""
- if isinstance(aProxy, Proxy):
- self.SMProxyManager.RegisterProxy(group, name, aProxy.SMProxy)
- else:
- self.SMProxyManager.RegisterProxy(group, name, aProxy)
-
- def NewProxy(self, group, name):
- """Creates a new proxy of given group and name and returns an SMProxy.
- Note that this is a server manager object. You should normally create
- proxies using the class objects. For example:
- obj = servermanager.sources.SphereSource()"""
- if not self.SMProxyManager:
- return None
- aProxy = self.SMProxyManager.NewProxy(group, name, "NULL")
- if not aProxy:
- return None
- aProxy.UnRegister(None)
- return aProxy
-
- def GetProxy(self, group, name):
- """Returns a Proxy registered under a group and name"""
- if not self.SMProxyManager:
- return None
- aProxy = self.SMProxyManager.GetProxy(group, name)
- if not aProxy:
- return None
- return _getPyProxy(aProxy)
-
- def GetPrototypeProxy(self, group, name):
- """Returns a prototype proxy given a group and name. This is an
- SMProxy. This is a low-level method. You should not normally
- have to call it."""
- if not self.SMProxyManager:
- return None
- aProxy = self.SMProxyManager.GetPrototypeProxy(group, name)
- if not aProxy:
- return None
- return aProxy
-
- def GetProxiesInGroup(self, groupname):
- """Returns a map of proxies in a particular group."""
- proxies = {}
- iter = self.NewGroupIterator(groupname)
- for aProxy in iter:
- proxies[(iter.GetKey(), aProxy.GetGlobalIDAsString())] = aProxy
- return proxies
-
- def UnRegisterProxy(self, groupname, proxyname, aProxy):
- """Unregisters a proxy."""
- if not self.SMProxyManager:
- return
- if aProxy != None and isinstance(aProxy,Proxy):
- aProxy = aProxy.SMProxy
- if aProxy:
- self.SMProxyManager.UnRegisterProxy(groupname, proxyname, aProxy)
-
- def GetProxies(self, groupname, proxyname):
- """Returns all proxies registered under the given group with the
- given name. Note that it is possible to register more than one
- proxy with the same name in the same group. Because the proxies
- are different, there is no conflict. Use this method instead of
- GetProxy() if you know that there are more than one proxy registered
- with this name."""
- if not self.SMProxyManager:
- return []
- collection = vtk.vtkCollection()
- result = []
- self.SMProxyManager.GetProxies(groupname, proxyname, collection)
- for i in range(0, collection.GetNumberOfItems()):
- aProxy = _getPyProxy(collection.GetItemAsObject(i))
- if aProxy:
- result.append(aProxy)
-
- return result
-
- def __iter__(self):
- """Returns a new ProxyIterator."""
- iter = ProxyIterator()
- iter.Begin()
- return iter
-
- def NewGroupIterator(self, group_name):
- """Returns a ProxyIterator for a group. The resulting object
- can be used to traverse the proxies that are in the given
- group."""
- iter = self.__iter__()
- iter.SetModeToOneGroup()
- iter.Begin(group_name)
- return iter
-
- def NewDefinitionIterator(self, groupname=None):
- """Returns an iterator that can be used to iterate over
- all groups and types of proxies that the proxy manager
- can create."""
- iter = None
- if groupname != None:
- iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewSingleGroupIterator(groupname,0))
- else:
- iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewIterator(0))
-
- return iter
-
- def __ConvertArgumentsAndCall(self, *args):
- newArgs = []
- for arg in args:
- if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
- newArgs.append(arg.SMProxy)
- else:
- newArgs.append(arg)
- func = getattr(self.SMProxyManager, self.__LastAttrName)
- retVal = func(*newArgs)
- if type(retVal) is type(self.SMProxyManager) and retVal.IsA("vtkSMProxy"):
- return _getPyProxy(retVal)
- else:
- return retVal
-
- def __getattr__(self, name):
- """Returns attribute from the ProxyManager"""
- try:
- pmAttr = getattr(self.SMProxyManager, name)
- self.__LastAttrName = name
- return self.__ConvertArgumentsAndCall
- except:
- pass
- return getattr(self.SMProxyManager, name)
-
- def LoadState(self, filename, loader = None):
- self.SMProxyManager.LoadXMLState(filename, loader)
-
- def SaveState(self, filename):
- self.SMProxyManager.SaveXMLState(filename)
-
-class PropertyIterator(object):
- """Wrapper for a vtkSMPropertyIterator class to satisfy
- the python iterator protocol. Note that the list of
- properties can also be obtained from the class object's
- dictionary.
- See the doxygen documentation for vtkSMPropertyIterator C++
- class for details.
- """
-
- def __init__(self, aProxy):
- self.SMIterator = aProxy.NewPropertyIterator()
- if self.SMIterator:
- self.SMIterator.UnRegister(None)
- self.SMIterator.Begin()
- self.Key = None
- self.PropertyLabel = None
- self.Proxy = aProxy
-
- def __iter__(self):
- return self
-
- def next(self):
- if not self.SMIterator:
- raise StopIteration
-
- if self.SMIterator.IsAtEnd():
- self.Key = None
- raise StopIteration
- self.Key = self.SMIterator.GetKey()
- self.PropertyLabel = self.SMIterator.GetPropertyLabel()
- self.SMIterator.Next()
- return self.Proxy.GetProperty(self.Key)
-
- def GetProxy(self):
- """Returns the proxy for the property last returned by the call to
- 'next()'"""
- return self.Proxy
-
- def GetKey(self):
- """Returns the key for the property last returned by the call to
- 'next()' """
- return self.Key
-
- def GetProperty(self):
- """Returns the property last returned by the call to 'next()' """
- return self.Proxy.GetProperty(self.Key)
-
- def __getattr__(self, name):
- """returns attributes from the vtkSMPropertyIterator."""
- return getattr(self.SMIterator, name)
-
-class ProxyDefinitionIterator(object):
- """Wrapper for a vtkPVProxyDefinitionIterator class to satisfy
- the python iterator protocol.
- See the doxygen documentation of the vtkPVProxyDefinitionIterator
- C++ class for more information."""
- def __init__(self, iter):
- self.SMIterator = iter
- if self.SMIterator:
- self.SMIterator.UnRegister(None)
- self.SMIterator.InitTraversal()
- self.Group = None
- self.Key = None
-
- def __iter__(self):
- return self
-
- def next(self):
- if self.SMIterator.IsDoneWithTraversal():
- self.Group = None
- self.Key = None
- raise StopIteration
- self.Group = self.SMIterator.GetGroupName()
- self.Key = self.SMIterator.GetProxyName()
- self.SMIterator.GoToNextItem()
- return {"group": self.Group, "key":self.Key }
-
- def GetProxyName(self):
- """Returns the key for the proxy definition last returned by the call
- to 'next()' """
- return self.Key
-
- def GetGroup(self):
- """Returns the group for the proxy definition last returned by the
- call to 'next()' """
- return self.Group
-
- def __getattr__(self, name):
- """returns attributes from the vtkPVProxyDefinitionIterator."""
- return getattr(self.SMIterator, name)
-
-
-class ProxyIterator(object):
- """Wrapper for a vtkSMProxyIterator class to satisfy the
- python iterator protocol.
- See the doxygen documentation of vtkSMProxyIterator C++ class for
- more information.
- """
- def __init__(self):
- self.SMIterator = vtkSMProxyIterator()
- self.SMIterator.SetSession(ActiveConnection.Session)
- self.SMIterator.Begin()
- self.AProxy = None
- self.Group = None
- self.Key = None
-
- def __iter__(self):
- return self
-
- def next(self):
- if self.SMIterator.IsAtEnd():
- self.AProxy = None
- self.Group = None
- self.Key = None
- raise StopIteration
- return None
- self.AProxy = _getPyProxy(self.SMIterator.GetProxy())
- self.Group = self.SMIterator.GetGroup()
- self.Key = self.SMIterator.GetKey()
- self.SMIterator.Next()
- return self.AProxy
-
- def GetProxy(self):
- """Returns the proxy last returned by the call to 'next()'"""
- return self.AProxy
-
- def GetKey(self):
- """Returns the key for the proxy last returned by the call to
- 'next()' """
- return self.Key
-
- def GetGroup(self):
- """Returns the group for the proxy last returned by the call to
- 'next()' """
- return self.Group
-
- def __getattr__(self, name):
- """returns attributes from the vtkSMProxyIterator."""
- return getattr(self.SMIterator, name)
-
-# Caution: Observers must be global methods otherwise we run into memory
-# leak when the interpreter get reset from the C++ layer.
-def _update_definitions(caller, event):
- updateModules(ActiveConnection.Modules)
-
-class Connection(object):
- """
- This is a python representation for a session/connection.
- """
- def __init__(self, connectionId, session):
- """Default constructor. Creates a Connection with the given
- ID, all other data members initialized to None."""
- global MultiServerConnections
- global ActiveConnection
- self.ID = connectionId
- self.Session = session
- self.Modules = PVModule()
- self.Alive = True
- self.DefinitionObserverTag = 0
- self.CustomDefinitionObserverTag = 0
- if MultiServerConnections == None and ActiveConnection:
- raise RuntimeError, "Concurrent connections not supported!"
- if MultiServerConnections != None and not self in MultiServerConnections:
- MultiServerConnections.append(self)
- ActiveConnection = self
- __InitAfterConnect__(self)
- __exposeActiveModules__()
-
- def __eq__(self, other):
- "Returns true if the connection ids are the same."
- return (self.ID == other.ID)
-
- def __repr__(self):
- """User friendly string representation"""
- return "Connection (%s) [%d]" % (self.Session.GetURI(), self.ID)
-
- def GetURI(self):
- """Get URI of the connection"""
- return self.Session.GetURI()
-
- def IsRemote(self):
- """Returns True if the connection to a remote server, False if
- it is local (built-in)"""
- if self.Session.IsA("vtkSMSessionClient"):
- return True
- return False
-
- def GetNumberOfDataPartitions(self):
- """Returns the number of partitions on the data server for this
- connection"""
- return self.Session.GetServerInformation().GetNumberOfProcesses()
-
- def AttachDefinitionUpdater(self):
- """Attach observer to automatically update modules when needed."""
- # VTN: Observers are not supported
- # ProxyDefinitionsUpdated = 2000
-## self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions)
- # CompoundProxyDefinitionsUpdated = 2001
-## self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions)
- pass
-
- def close(self):
- if self.DefinitionObserverTag:
- self.Session.GetProxyDefinitionManager().RemoveObserver(self.DefinitionObserverTag)
- self.Session.GetProxyDefinitionManager().RemoveObserver(self.CustomDefinitionObserverTag)
- self.Session = None
- self.Modules = None
- self.Alive = False
-
- def __del__(self):
- if self.Alive:
- self.close()
-
-def SaveState(filename):
- """Given a state filename, saves the state of objects registered
- with the proxy manager."""
- pm = ProxyManager()
- pm.SaveState(filename)
-
-def LoadState(filename, connection=None):
- """Given a state filename and an optional connection, loads the server
- manager state."""
- if not connection:
- connection = ActiveConnection
- if not connection:
- raise RuntimeError, "Cannot load state without a connection"
- pm = ProxyManager()
- pm.LoadState(filename, None)
- views = GetRenderViews()
- for view in views:
- # Make sure that the client window size matches the
- # ViewSize property. In paraview, the GUI takes care
- # of this.
- if view.GetClassName() == "vtkSMIceTDesktopRenderViewProxy":
- view.GetRenderWindow().SetSize(view.ViewSize[0], \
- view.ViewSize[1])
-
-def InitFromGUI():
- """
- Method used to initialize the Python Shell from the ParaView GUI.
- """
- global fromGUI, ActiveConnection
- if not fromGUI:
- print "from paraview.simple import *"
- fromGUI = True
- # ToggleProgressPrinting() ### FIXME COLLABORATION
- enableMultiServer(vtkProcessModule.GetProcessModule().GetMultipleSessionsSupport())
- iter = vtkProcessModule.GetProcessModule().NewSessionIterator();
- iter.InitTraversal()
- ActiveConnection = None
- activeSession = vtkSMProxyManager.GetProxyManager().GetActiveSession()
- tmpActiveConnection = None
- while not iter.IsDoneWithTraversal():
- c = Connection(iter.GetCurrentSessionId(), iter.GetCurrentSession())
- if c.Session == activeSession:
- tmpActiveConnection = c
- iter.GoToNextItem()
- iter.UnRegister(None)
- if tmpActiveConnection:
- ActiveConnection = tmpActiveConnection
-
-def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=22221):
- """
- Use this function call to create a new session. On success,
- it returns a vtkSMSession object that abstracts the connection.
- Otherwise, it returns None.
- There are several ways in which this function can be called:
- * When called with no arguments, it creates a new session
- to the built-in server on the client itself.
- * When called with ds_host and ds_port arguments, it
- attempts to connect to a server(data and render server on the same server)
- on the indicated host:port.
- * When called with ds_host, ds_port, rs_host, rs_port, it
- creates a new connection to the data server on ds_host:ds_port and to the
- render server on rs_host: rs_port.
- """
- if ds_host == None:
- session = vtkSMSession()
- elif rs_host == None:
- session = vtkSMSessionClient()
- session.Connect("cs://%s:%d" % (ds_host, ds_port))
- else:
- session = vtkSMSessionClient()
- session.Connect("cdsrs://%s:%d/%s:%d" % (ds_host, ds_port, rs_host, rs_port))
- id = vtkProcessModule.GetProcessModule().RegisterSession(session)
- connection = Connection(id, session)
- return connection
-
-def ReverseConnect(port=11111):
- """
- Use this function call to create a new session. On success,
- it returns a Session object that abstracts the connection.
- Otherwise, it returns None.
- In reverse connection mode, the client waits for a connection
- from the server (client has to be started first). The server
- then connects to the client (run pvserver with -rc and -ch
- option).
- The optional port specified the port to listen to.
- """
- session = vtkSMSessionClient()
- session.Connect("csrc://hostname:" + port)
- id = vtkProcessModule.GetProcessModule().RegisterSession(session)
- connection = Connection(id, session)
- return connection
-
-def Disconnect(session=None):
- """Disconnects the connection. Make sure to clear the proxy manager
- first."""
- global ActiveConnection
- global MultiServerConnections
- global fromGUI
- if fromGUI:
- # Let the UI know that we want to disconnect
- ActiveConnection.Session.InvokeEvent('ExitEvent')
- return
- if ActiveConnection and (not session or session == ActiveConnection.Session):
- session = ActiveConnection.Session
- if MultiServerConnections:
- MultiServerConnections.remove(ActiveConnection)
- ActiveConnection.close()
- ActiveConnection = None
- switchActiveConnection()
- else:
- ActiveConnection.close()
- ActiveConnection = None
- elif MultiServerConnections:
- for connection in MultiServerConnections:
- if connection.Session == session:
- connection.close()
- MultiServerConnections.remove(connection)
- if session:
- vtkProcessModule.GetProcessModule().UnRegisterSession(session)
- return
-
-def CreateProxy(xml_group, xml_name, session=None):
- """Creates a proxy. If session is set, the proxy's session is
- set accordingly. If session is None, the current Session is used, if
- present. You should not have to use method normally. Instantiate the
- appropriate class from the appropriate module, for example:
- sph = servermanager.sources.SphereSource()"""
- global ActiveConnection
- if not session:
- session = ActiveConnection.Session
- if not session:
- raise RuntimeError, "Cannot create objects without a session."
- pxm = ProxyManager(session)
- return pxm.NewProxy(xml_group, xml_name)
-
-def GetRenderView(connection=None):
- """Return the render view in use. If more than one render view is in
- use, return the first one."""
-
- render_module = None
- for aProxy in ProxyManager():
- if aProxy.IsA("vtkSMRenderViewProxy"):
- render_module = aProxy
- break
- return render_module
-
-def GetRenderViews(connection=None):
- """Returns the set of all render views."""
- render_modules = []
- for aProxy in ProxyManager():
- if aProxy.IsA("vtkSMRenderViewProxy"):
- render_modules.append(aProxy)
- return render_modules
-
-def GetContextViews(connection=None):
- """Returns the set of all context views."""
- context_modules = []
- for aProxy in ProxyManager():
- if aProxy.IsA("vtkSMContextViewProxy"):
- context_modules.append(aProxy)
- return context_modules
-
-def CreateRenderView(session=None, **extraArgs):
- """Creates a render window on the particular session. If session
- is not specified, then the active session is used, if available.
-
- This method can also be used to initialize properties by passing
- keyword arguments where the key is the name of the property. In addition
- registrationGroup and registrationName (optional) can be specified (as
- keyword arguments) to automatically register the proxy with the proxy
- manager."""
- return _create_view("RenderView", session, **extraArgs)
-
-def _create_view(view_xml_name, session=None, **extraArgs):
- """Creates a view on the particular session. If session
- is not specified, then the active session is used, if available.
- This method can also be used to initialize properties by passing
- keyword arguments where the key is the name of the property."""
- if not session:
- session = ActiveConnection.Session
- if not session:
- raise RuntimeError, "Cannot create view without session."
- pxm = ProxyManager()
- view_module = None
- if view_xml_name:
- view_module = CreateProxy("views", view_xml_name, session)
- if not view_module:
- return None
- extraArgs['proxy'] = view_module
- python_proxy_name = _make_name_valid(view_module.GetXMLName())
- proxy = rendering.__dict__[python_proxy_name](**extraArgs)
- return proxy
-
-def GetRepresentation(aProxy, view):
- for rep in view.Representations:
- #VSV: ==
- try: isRep = rep.Input.IsSame(aProxy)
- except: isRep = False
- if isRep: return rep
- return None
-
-def CreateRepresentation(aProxy, view, **extraArgs):
- """Creates a representation for the proxy and adds it to the render
- module.
-
- This method can also be used to initialize properties by passing
- keyword arguments where the key is the name of the property.In addition
- registrationGroup and registrationName (optional) can be specified (as
- keyword arguments) to automatically register the proxy with the proxy
- manager.
-
- This method tries to create the best possible representation for the given
- proxy in the given view. Additionally, the user can specify proxyName
- (optional) to create a representation of a particular type."""
-
- global rendering
- if not aProxy:
- raise RuntimeError, "proxy argument cannot be None."
- if not view:
- raise RuntimeError, "view argument cannot be None."
- if "proxyName" in extraArgs:
- display = CreateProxy("representations", extraArgs['proxyName'], None)
- del extraArgs['proxyName']
- else:
- display = view.SMProxy.CreateDefaultRepresentation(aProxy.SMProxy, 0)
- if display:
- display.UnRegister(None)
- if not display:
- return None
- extraArgs['proxy'] = display
- proxy = rendering.__dict__[display.GetXMLName()](**extraArgs)
- proxy.Input = aProxy
- proxy.UpdateVTKObjects()
- view.Representations.append(proxy)
- return proxy
-
-class _ModuleLoader(object):
- def find_module(self, fullname, path=None):
- if vtkPVPythonModule.HasModule(fullname):
- return self
- else:
- return None
- def load_module(self, fullname):
- import imp
- moduleInfo = vtkPVPythonModule.GetModule(fullname)
- if not moduleInfo:
- raise ImportError
- module = sys.modules.setdefault(fullname, imp.new_module(fullname))
- module.__file__ = "<%s>" % moduleInfo.GetFullName()
- module.__loader__ = self
- if moduleInfo.GetIsPackage:
- module.__path__ = moduleInfo.GetFullName()
- code = compile(moduleInfo.GetSource(), module.__file__, 'exec')
- exec code in module.__dict__
- return module
-
-def LoadXML(xmlstring):
- """DEPRECATED. Given a server manager XML as a string, parse and process it."""
- raise RuntimeError, "Deprecated. Use LoadPlugin(...) instead."
-
-
-def LoadPlugin(filename, remote=True, connection=None):
- """ Given a filename and a session (optional, otherwise uses
- ActiveConnection), loads a plugin. It then updates the sources,
- filters and rendering modules."""
-
- if not connection:
- connection = ActiveConnection
- if not connection:
- raise RuntimeError, "Cannot load a plugin without a connection."
- plm = vtkSMProxyManager.GetProxyManager().GetPluginManager()
-
- if remote:
- status = plm.LoadRemotePlugin(filename, connection.Session)
- else:
- status = plm.LoadLocalPlugin(filename)
-
- # shouldn't the extension check happend before attempting to load the plugin?
- if not status:
- raise RuntimeError, "Problem loading plugin %s" % (filename)
- else:
- # we should never have to call this. The modules should update automatically.
- updateModules(connection.Modules)
-
-
-def Fetch(input, arg1=None, arg2=None, idx=0):
- """
- A convenience method that moves data from the server to the client,
- optionally performing some operation on the data as it moves.
- The input argument is the name of the (proxy for a) source or filter
- whose output is needed on the client.
-
- You can use Fetch to do three things:
-
- If arg1 is None (the default) then all of the data is brought to the client.
- In parallel runs an appropriate append Filter merges the
- data on each processor into one data object. The filter chosen will be
- vtkAppendPolyData for vtkPolyData, vtkAppendRectilinearGrid for
- vtkRectilinearGrid, vtkMultiBlockDataGroupFilter for vtkCompositeData,
- and vtkAppendFilter for anything else.
-
- If arg1 is an integer then one particular processor's output is brought to
- the client. In serial runs the arg is ignored. If you have a filter that
- computes results in parallel and brings them to the root node, then set
- arg to be 0.
-
- If arg1 and arg2 are a algorithms, for example vtkMinMax, the algorithm
- will be applied to the data to obtain some result. Here arg1 will be
- applied pre-gather and arg2 will be applied post-gather. In parallel
- runs the algorithm will be run on each processor to make intermediate
- results and then again on the root processor over all of the
- intermediate results to create a global result.
-
- Optional argument idx is used to specify the output port number to fetch the
- data from. Default is port 0.
- """
-
- import types
-
- reducer = filters.ReductionFilter(Input=OutputPort(input,idx))
-
- #create the pipeline that reduces and transmits the data
- if arg1 == None:
- cdinfo = input.GetDataInformation(idx).GetCompositeDataInformation()
- if cdinfo.GetDataIsComposite():
- print "use composite data append"
- reducer.PostGatherHelperName = "vtkMultiBlockDataGroupFilter"
-
- elif input.GetDataInformation(idx).GetDataClassName() == "vtkPolyData":
- print "use append poly data filter"
- reducer.PostGatherHelperName = "vtkAppendPolyData"
-
- elif input.GetDataInformation(idx).GetDataClassName() == "vtkRectilinearGrid":
- print "use append rectilinear grid filter"
- reducer.PostGatherHelperName = "vtkAppendRectilinearGrid"
-
- elif input.GetDataInformation(idx).IsA("vtkDataSet"):
- print "use unstructured append filter"
- reducer.PostGatherHelperName = "vtkAppendFilter"
-
- elif type(arg1) is types.IntType:
- reducer.PassThrough = arg1
-
- else:
- reducer.PreGatherHelper = arg1
- reducer.PostGatherHelper = arg2
-
- # reduce
- reducer.UpdatePipeline()
- dataInfo = reducer.GetDataInformation(0)
- dataType = dataInfo.GetDataSetType()
- if dataInfo.GetCompositeDataSetType() > 0:
- dataType = dataInfo.GetCompositeDataSetType()
-
- fetcher = filters.ClientServerMoveData(Input=reducer)
- fetcher.OutputDataType = dataType
- fetcher.WholeExtent = dataInfo.GetExtent()[:]
- #fetch
- fetcher.UpdatePipeline()
-
- op = fetcher.GetClientSideObject().GetOutputDataObject(0)
- opc = op.NewInstance()
- opc.ShallowCopy(op)
- opc.UnRegister(None)
- return opc
-
-def AnimateReader(reader, view, filename=None):
- """This is a utility function that, given a reader and a view
- animates over all time steps of the reader. If the optional
- filename is provided, a movie is created (type depends on the
- extension of the filename."""
- if not reader:
- raise RuntimeError, "No reader was specified, cannot animate."
- if not view:
- raise RuntimeError, "No view was specified, cannot animate."
- # Create an animation scene
- scene = animation.AnimationScene()
-
- # We need to have the reader and the view registered with
- # the time keeper. This is how the scene gets its time values.
- try:
- tk = ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
- scene.TimeKeeper = tk
- except IndexError:
- tk = misc.TimeKeeper()
- scene.TimeKeeper = tk
-
- if not reader in tk.TimeSources:
- tk.TimeSources.append(reader)
- if not view in tk.Views:
- tk.Views.append(view)
-
-
- # with 1 view
- scene.ViewModules = [view]
- # Update the reader to get the time information
- reader.UpdatePipelineInformation()
- # Animate from 1st time step to last
- scene.StartTime = reader.TimestepValues.GetData()[0]
- scene.EndTime = reader.TimestepValues.GetData()[-1]
-
- # Each frame will correspond to a time step
- scene.PlayMode = 2 #Snap To Timesteps
-
- # Create a special animation cue for time.
- cue = animation.TimeAnimationCue()
- cue.AnimatedProxy = view
- cue.AnimatedPropertyName = "ViewTime"
- scene.Cues = [cue]
-
- if filename:
- writer = vtkSMAnimationSceneImageWriter()
- writer.SetFileName(filename)
- writer.SetFrameRate(1)
- writer.SetAnimationScene(scene.SMProxy)
-
- # Now save the animation.
- if not writer.Save():
- raise RuntimeError, "Saving of animation failed!"
- else:
- scene.Play()
- return scene
-
-def GetProgressPrintingIsEnabled():
- return progressObserverTag is not None
-
-def SetProgressPrintingEnabled(value):
- """Is not supported because of not supported observers"""
- pass
-
-def ToggleProgressPrinting():
- """Turn on/off printing of progress. See SetProgressPrintingEnabled."""
- SetProgressPrintingEnabled(not GetProgressPrintingIsEnabled())
-
-def Finalize():
- """Although not required, this can be called at exit to cleanup."""
- global progressObserverTag
- # Make sure to remove the observer
- if progressObserverTag:
- ToggleProgressPrinting()
- vtkInitializationHelper.Finalize()
-
-# Internal methods
-
-def _getPyProxy(smproxy, outputPort=0):
- """Returns a python wrapper for a server manager proxy. This method
- first checks if there is already such an object by looking in the
- _pyproxies group and returns it if found. Otherwise, it creates a
- new one. Proxies register themselves in _pyproxies upon creation."""
- if not smproxy:
- return None
- if (smproxy, outputPort) in _pyproxies:
- return _pyproxies[(smproxy, outputPort)]()
-
- xmlName = smproxy.GetXMLName()
- if smproxy.GetXMLLabel():
- xmlName = smproxy.GetXMLLabel()
- classForProxy = _findClassForProxy(_make_name_valid(xmlName), smproxy.GetXMLGroup())
- if classForProxy:
- retVal = classForProxy(proxy=smproxy, port=outputPort)
- else:
- retVal = Proxy(proxy=smproxy, port=outputPort)
- return retVal
-
-def _makeUpdateCameraMethod(rv):
- """ This internal method is used to create observer methods """
- if not hasattr(rv(), "BlockUpdateCamera"):
- rv().add_attribute("BlockUpdateCamera", False)
- def UpdateCamera(obj, string):
- if not rv().BlockUpdateCamera:
- # used to avoid some nasty recursion that occurs when interacting in
- # the GUI.
- rv().BlockUpdateCamera = True
- rv().SynchronizeCameraProperties()
- rv().BlockUpdateCamera = False
- return UpdateCamera
-
-def _createInitialize(group, name):
- """Internal method to create an Initialize() method for the sub-classes
- of Proxy"""
- pgroup = group
- pname = name
- def aInitialize(self, connection=None, update=True):
- if not connection:
- connection = ActiveConnection
- if not connection:
- raise RuntimeError,\
- 'Cannot create a proxy without a session.'
- if not connection.Session.GetProxyDefinitionManager().HasDefinition(pgroup, pname):
- error_msg = "The connection does not provide any definition for %s." % pname
- raise RuntimeError, error_msg
- self.InitializeFromProxy(\
- CreateProxy(pgroup, pname, connection.Session), update)
- return aInitialize
-
-def _createGetProperty(pName):
- """Internal method to create a GetXXX() method where XXX == pName."""
- propName = pName
- def getProperty(self):
- return self.GetPropertyValue(propName)
- return getProperty
-
-def _createSetProperty(pName):
- """Internal method to create a SetXXX() method where XXX == pName."""
- propName = pName
- def setProperty(self, value):
- return self.SetPropertyWithName(propName, value)
- return setProperty
-
-def _findClassForProxy(xmlName, xmlGroup):
- """Given the xmlName for a proxy, returns a Proxy class. Note
- that if there are duplicates, the first one is returned."""
- global sources, filters, writers, rendering, animation, implicit_functions,\
- piecewise_functions, extended_sources, misc
- if not xmlName:
- return None
- if xmlGroup == "sources":
- return sources.__dict__[xmlName]
- elif xmlGroup == "filters":
- return filters.__dict__[xmlName]
- elif xmlGroup == "implicit_functions":
- return implicit_functions.__dict__[xmlName]
- elif xmlGroup == "piecewise_functions":
- return piecewise_functions.__dict__[xmlName]
- elif xmlGroup == "writers":
- return writers.__dict__[xmlName]
- elif xmlGroup == "extended_sources":
- return extended_sources.__dict__[xmlName]
- elif xmlName in rendering.__dict__:
- return rendering.__dict__[xmlName]
- elif xmlName in animation.__dict__:
- return animation.__dict__[xmlName]
- elif xmlName in misc.__dict__:
- return misc.__dict__[xmlName]
- else:
- return None
-
-def _printProgress(caller, event):
- """The default event handler for progress. Prints algorithm
- name and 1 '.' per 10% progress."""
- global currentAlgorithm, currentProgress
-
- pm = vtkProcessModule.GetProcessModule()
- progress = pm.GetLastProgress() / 10
- # If we got a 100% as the first thing, ignore
- # This is to get around the fact that some vtk
- # algorithms report 100% more than once (which is
- # a bug)
- if not currentAlgorithm and progress == 10:
- return
- alg = pm.GetLastProgressName()
- if alg != currentAlgorithm and alg:
- if currentAlgorithm:
- while currentProgress <= 10:
- import sys
- sys.stdout.write(".")
- currentProgress += 1
- print "]"
- currentProgress = 0
- print alg, ": [ ",
- currentAlgorithm = alg
- while currentProgress <= progress:
- import sys
- sys.stdout.write(".")
- #sys.stdout.write("%d " % pm.GetLastProgress())
- currentProgress += 1
- if progress == 10:
- print "]"
- currentAlgorithm = None
- currentProgress = 0
-
-def updateModules(m):
- """Called when a plugin is loaded, this method updates
- the proxy class object in all known modules."""
-
- createModule("sources", m.sources)
- createModule("filters", m.filters)
- createModule("writers", m.writers)
- createModule("representations", m.rendering)
- createModule("views", m.rendering)
- createModule("lookup_tables", m.rendering)
- createModule("textures", m.rendering)
- createModule('cameramanipulators', m.rendering)
- createModule("animation", m.animation)
- createModule("misc", m.misc)
- createModule('animation_keyframes', m.animation)
- createModule('implicit_functions', m.implicit_functions)
- createModule('piecewise_functions', m.piecewise_functions)
- createModule("extended_sources", m.extended_sources)
- createModule("incremental_point_locators", m.misc)
-
-def _createModules(m):
- """Called when the module is loaded, this creates sub-
- modules for all know proxy groups."""
-
- m.sources = createModule('sources')
- m.filters = createModule('filters')
- m.writers = createModule('writers')
- m.rendering = createModule('representations')
- createModule('views', m.rendering)
- createModule("lookup_tables", m.rendering)
- createModule("textures", m.rendering)
- createModule('cameramanipulators', m.rendering)
- m.animation = createModule('animation')
- createModule('animation_keyframes', m.animation)
- m.implicit_functions = createModule('implicit_functions')
- m.piecewise_functions = createModule('piecewise_functions')
- m.extended_sources = createModule("extended_sources")
- m.misc = createModule("misc")
- createModule("incremental_point_locators", m.misc)
-
-class PVModule(object):
- pass
-
-def _make_name_valid(name):
- """Make a string into a valid Python variable name."""
- if not name:
- return None
- import string
- valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
- name = str().join([c for c in name if c in valid_chars])
- if not name[0].isalpha():
- name = 'a' + name
- return name
-
-def createModule(groupName, mdl=None):
- """Populates a module with proxy classes defined in the given group.
- If mdl is not specified, it also creates the module"""
- global ActiveConnection
-
- if not ActiveConnection:
- raise RuntimeError, "Please connect to a server using \"Connect\""
-
- pxm = ProxyManager()
- # Use prototypes to find all proxy types.
- pxm.InstantiateGroupPrototypes(groupName)
-
- debug = False
- if not mdl:
- debug = True
- mdl = PVModule()
- definitionIter = pxm.NewDefinitionIterator(groupName)
- for i in definitionIter:
- proxyName = i['key']
- proto = pxm.GetPrototypeProxy(groupName, proxyName)
- if not proto:
- print "Error while loading %s/%s %s"%(groupName, i['group'], proxyName)
- continue
- pname = proxyName
- if proto.GetXMLLabel():
- pname = proto.GetXMLLabel()
- pname = _make_name_valid(pname)
- if not pname:
- continue
- if pname in mdl.__dict__:
- if debug:
- print "Warning: %s is being overwritten. This may point to an issue in the ParaView configuration files" % pname
- cdict = {}
- # Create an Initialize() method for this sub-class.
- cdict['Initialize'] = _createInitialize(groupName, proxyName)
- iter = PropertyIterator(proto)
- # Add all properties as python properties.
- for prop in iter:
- propName = iter.GetKey()
- if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
- or prop.GetIsInternal():
- continue
- names = [propName]
- names = [iter.PropertyLabel]
-
- propDoc = None
- if prop.GetDocumentation():
- propDoc = prop.GetDocumentation().GetDescription()
- for name in names:
- name = _make_name_valid(name)
- if name:
- cdict[name] = property(_createGetProperty(propName),
- _createSetProperty(propName),
- None,
- propDoc)
- # Add the documentation as the class __doc__
- if proto.GetDocumentation() and \
- proto.GetDocumentation().GetDescription():
- doc = proto.GetDocumentation().GetDescription()
- else:
- doc = Proxy.__doc__
- cdict['__doc__'] = doc
- # Create the new type
- if proto.GetXMLName() == "ExodusIIReader":
- superclasses = (ExodusIIReaderProxy,)
- elif proto.IsA("vtkSMSourceProxy"):
- superclasses = (SourceProxy,)
- elif proto.IsA("vtkSMViewLayoutProxy"):
- superclasses = (ViewLayoutProxy,)
- else:
- superclasses = (Proxy,)
-
- cobj = type(pname, superclasses, cdict)
- # Add it to the modules dictionary
- mdl.__dict__[pname] = cobj
- return mdl
-
-
-def __determineGroup(proxy):
- """Internal method"""
- if not proxy:
- return None
- xmlgroup = proxy.GetXMLGroup()
- xmlname = proxy.GetXMLName()
- if xmlgroup == "sources":
- if xmlname in ["BlockSelectionSource",
- "FrustumSelectionSource",
- "GlobalIDSelectionSource",
- "PedigreeIDSelectionSource",
- "IDSelectionSource",
- "CompositeDataIDSelectionSource",
- "HierarchicalDataIDSelectionSource",
- "ThresholdSelectionSource",
- "LocationSelectionSource"]:
- return "selection_sources"
- return "sources"
- elif xmlgroup == "filters":
- return "sources"
- elif xmlgroup == "representations":
- if xmlname == "ScalarBarWidgetRepresentation":
- return "scalar_bars"
- return "representations"
- elif xmlgroup == "animation_keyframes":
- return "animation"
- return xmlgroup
-
-__nameCounter = {}
-def __determineName(proxy, group):
- global __nameCounter
- name = _make_name_valid(proxy.GetXMLLabel())
- if not name:
- return None
- if not __nameCounter.has_key(name):
- __nameCounter[name] = 1
- val = 1
- else:
- __nameCounter[name] += 1
- val = __nameCounter[name]
- return "%s%d" % (name, val)
-
-def __getName(proxy, group):
- pxm = ProxyManager(proxy.GetSession())
- if isinstance(proxy, Proxy):
- proxy = proxy.SMProxy
- return pxm.GetProxyName(group, proxy)
-
-class MissingRegistrationInformation(Exception):
- """Exception for missing registration information. Raised when a name or group
- is not specified or when a group cannot be deduced."""
- pass
-
-class MissingProxy(Exception):
- """Exception fired when the requested proxy is missing."""
- pass
-
-def Register(proxy, **extraArgs):
- """Registers a proxy with the proxy manager. If no 'registrationGroup' is
- specified, then the group is inferred from the type of the proxy.
- 'registrationName' may be specified to register with a particular name
- otherwise a default name will be created."""
- # TODO: handle duplicate registration
- if "registrationGroup" in extraArgs:
- registrationGroup = extraArgs["registrationGroup"]
- else:
- registrationGroup = __determineGroup(proxy)
-
- if "registrationName" in extraArgs:
- registrationName = extraArgs["registrationName"]
- else:
- registrationName = __determineName(proxy, registrationGroup)
- if registrationGroup and registrationName:
- pxm = ProxyManager()
- pxm.RegisterProxy(registrationGroup, registrationName, proxy)
- else:
- raise MissingRegistrationInformation, "Registration error %s %s." % (registrationGroup, registrationName)
- return (registrationGroup, registrationName)
-
-def UnRegister(proxy, **extraArgs):
- """UnRegisters proxies registered using Register()."""
- if "registrationGroup" in extraArgs:
- registrationGroup = extraArgs["registrationGroup"]
- else:
- registrationGroup = __determineGroup(proxy)
-
- if "registrationName" in extraArgs:
- registrationName = extraArgs["registrationName"]
- else:
- registrationName = __getName(proxy, registrationGroup)
-
- if registrationGroup and registrationName:
- pxm = ProxyManager()
- pxm.UnRegisterProxy(registrationGroup, registrationName, proxy)
- else:
- raise RuntimeError, "UnRegistration error."
- return (registrationGroup, registrationName)
-
-def demo1():
- """This simple demonstration creates a sphere, renders it and delivers
- it to the client using Fetch. It returns a tuple of (data, render
- view)"""
- if not ActiveConnection:
- Connect()
- ss = sources.Sphere(Radius=2, ThetaResolution=32)
- shr = filters.Shrink(Input=OutputPort(ss,0))
- cs = sources.Cone()
- app = filters.AppendDatasets()
- app.Input = [shr, cs]
- rv = CreateRenderView()
- rep = CreateRepresentation(app, rv)
- rv.ResetCamera()
- rv.StillRender()
- data = Fetch(ss)
-
- return (data, rv)
-
-def demo2(fname="/Users/berk/Work/ParaViewData/Data/disk_out_ref.ex2"):
- """This method demonstrates the user of a reader, representation and
- view. It also demonstrates how meta-data can be obtained using proxies.
- Make sure to pass the full path to an exodus file. Also note that certain
- parameters are hard-coded for disk_out_ref.ex2 which can be found
- in ParaViewData. This method returns the render view."""
- if not ActiveConnection:
- Connect()
- # Create the exodus reader and specify a file name
- reader = sources.ExodusIIReader(FileName=fname)
- # Get the list of point arrays.
- arraySelection = reader.PointVariables
- print arraySelection.Available
- # Select all arrays
- arraySelection.SetData(arraySelection.Available)
-
- # Next create a default render view appropriate for the session type.
- rv = CreateRenderView()
- # Create the matching representation
- rep = CreateRepresentation(reader, rv)
- rep.Representation = 1 # Wireframe
- # Black background is not pretty
- rv.Background = [0.4, 0.4, 0.6]
- rv.StillRender()
- # Reset the camera to include the whole thing
- rv.ResetCamera()
- rv.StillRender()
- # Change the elevation of the camera. See VTK documentation of vtkCamera
- # for camera parameters.
- c = rv.GetActiveCamera()
- c.Elevation(45)
- rv.StillRender()
- # Now that the reader execute, let's get some information about it's
- # output.
- pdi = reader[0].PointData
- # This prints a list of all read point data arrays as well as their
- # value ranges.
- print 'Number of point arrays:', len(pdi)
- for i in range(len(pdi)):
- ai = pdi[i]
- print "----------------"
- print "Array:", i, ai.Name, ":"
- numComps = ai.GetNumberOfComponents()
- print "Number of components:", numComps
- for j in range(numComps):
- print "Range:", ai.GetRange(j)
- # White is boring. Let's color the geometry using a variable.
- # First create a lookup table. This object controls how scalar
- # values are mapped to colors. See VTK documentation for
- # details.
- lt = rendering.PVLookupTable()
- # Assign it to the representation
- rep.LookupTable = lt
- # Color by point array called Pres
- rep.ColorAttributeType = 0 # point data
- rep.ColorArrayName = "Pres"
- # Add to RGB points. These are tuples of 4 values. First one is
- # the scalar values, the other 3 the RGB values. This list has
- # 2 points: Pres: 0.00678, color: blue, Pres: 0.0288, color: red
- lt.RGBPoints = [0.00678, 0, 0, 1, 0.0288, 1, 0, 0]
- lt.ColorSpace = 1 # HSV
- rv.StillRender()
- return rv
-
-def demo3():
- """This method demonstrates the use of servermanager with numpy as
- well as pylab for plotting. It creates an artificial data sources,
- probes it with a line, delivers the result to the client using Fetch
- and plots it using pylab. This demo requires numpy and pylab installed.
- It returns a tuple of (data, render view)."""
- import paraview.numpy_support
- import pylab
-
- if not ActiveConnection:
- Connect()
- # Create a synthetic data source
- source = sources.Wavelet()
- # Let's get some information about the data. First, for the
- # source to execute
- source.UpdatePipeline()
-
- di = source.GetDataInformation()
- print "Data type:", di.GetPrettyDataTypeString()
- print "Extent:", di.GetExtent()
- print "Array name:", \
- source[0].PointData[0].Name
-
- rv = CreateRenderView()
-
- rep1 = CreateRepresentation(source, rv)
- rep1.Representation = 3 # outline
-
- # Let's apply a contour filter
- cf = filters.Contour(Input=source, ContourValues=[200])
-
- # Select the array to contour by
- #cf.SelectInputScalars = 'RTData'
-
- rep2 = CreateRepresentation(cf, rv)
-
- rv.Background = (0.4, 0.4, 0.6)
- # Reset the camera to include the whole thing
- rv.StillRender()
- rv.ResetCamera()
- rv.StillRender()
-
- # Now, let's probe the data
- probe = filters.ResampleWithDataset(Input=source)
- # with a line
- line = sources.Line(Resolution=60)
- # that spans the dataset
- bounds = di.GetBounds()
- print "Bounds: ", bounds
- line.Point1 = bounds[0:6:2]
- line.Point2 = bounds[1:6:2]
-
- probe.Source = line
-
- # Render with the line
- rep3 = CreateRepresentation(line, rv)
- rv.StillRender()
-
- # Now deliver it to the client. Remember, this is for small data.
- data = Fetch(probe)
- # Convert it to a numpy array
- data = paraview.numpy_support.vtk_to_numpy(
- data.GetPointData().GetArray("RTData"))
- # Plot it using matplotlib
- pylab.plot(data)
- pylab.show()
-
- return (data, rv, probe)
-
-def demo4(fname="/Users/berk/Work/ParaViewData/Data/can.ex2"):
- """This method demonstrates the user of AnimateReader for
- creating animations."""
- if not ActiveConnection:
- Connect()
- reader = sources.ExodusIIReader(FileName=fname)
- view = CreateRenderView()
- repr = CreateRepresentation(reader, view)
- view.StillRender()
- view.ResetCamera()
- view.StillRender()
- c = view.GetActiveCamera()
- c.Elevation(95)
- return AnimateReader(reader, view)
-
-
-def demo5():
- """ Simple sphere animation"""
- if not ActiveConnection:
- Connect()
- sphere = sources.Sphere()
- view = CreateRenderView()
- repr = CreateRepresentation(sphere, view)
-
- view.StillRender()
- view.ResetCamera()
- view.StillRender()
-
- # Create an animation scene
- scene = animation.AnimationScene()
- # Add 1 view
- scene.ViewModules = [view]
-
- # Create a cue to animate the StartTheta property
- cue = animation.KeyFrameAnimationCue()
- cue.AnimatedProxy = sphere
- cue.AnimatedPropertyName = "StartTheta"
- # Add it to the scene's cues
- scene.Cues = [cue]
-
- # Create 2 keyframes for the StartTheta track
- keyf0 = animation.CompositeKeyFrame()
- keyf0.Type = 2 # Set keyframe interpolation type to Ramp.
- # At time = 0, value = 0
- keyf0.KeyTime = 0
- keyf0.KeyValues= [0]
-
- keyf1 = animation.CompositeKeyFrame()
- # At time = 1.0, value = 200
- keyf1.KeyTime = 1.0
- keyf1.KeyValues= [200]
-
- # Add keyframes.
- cue.KeyFrames = [keyf0, keyf1]
-
- scene.Play()
- return scene
-
-ASSOCIATIONS = { 'POINTS' : 0, 'CELLS' : 1, 'VERTICES' : 4, 'EDGES' : 5, 'ROWS' : 6}
-
-# Users can set the active connection which will be used by API
-# to create proxies etc when no connection argument is passed.
-# Connect() automatically sets this if it is not already set.
-ActiveConnection = None
-
-# Fields for multi-server support
-MultiServerConnections = None
-
-# API for multi-server support
-def enableMultiServer(multiServer=True):
- """This method enable the current servermanager to support several
- connections. Once we enable the multi-server support, the user can create
- as many connection as he want and switch from one to another in order to
- create and manage proxy."""
- global MultiServerConnections, ActiveConnection
- if not multiServer and MultiServerConnections:
- raise RuntimeError, "Once we enable Multi-Server support we can not get back"
- MultiServerConnections = []
- if ActiveConnection:
- MultiServerConnections.append(ActiveConnection)
-
-def switchActiveConnection(newActiveConnection=None):
- """Switch active connection to be the provided one or if none just pick the
- other one"""
- global MultiServerConnections, ActiveConnection
- if MultiServerConnections == None:
- raise RuntimeError, "enableMultiServer() must be called before"
-
- # Manage the case when no connection is provided
- if newActiveConnection:
- ActiveConnection = newActiveConnection
- __exposeActiveModules__()
- # Update active session for ParaView
- if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session:
- vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session)
- return ActiveConnection
- else:
- for connection in MultiServerConnections:
- if connection != ActiveConnection:
- ActiveConnection = connection
- __exposeActiveModules__()
- # Update active session for ParaView
- if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session:
- vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session)
- return ActiveConnection
- return None
-
-# Needs to be called when paraview module is loaded from python instead
-# of pvpython, pvbatch or GUI.
-if not vtkProcessModule.GetProcessModule():
-# pvoptions = None Not applicable for SALOME Python console
-# if paraview.options.batch:
-# pvoptions = vtkPVOptions();
-# pvoptions.SetProcessType(0x40)
-# if paraview.options.symmetric:
-# pvoptions.SetSymmetricMPIMode(True)
- vtkInitializationHelper.Initialize(sys.executable,
- vtkProcessModule.PROCESS_CLIENT, pvoptions)
-
-# Initialize progress printing. Can be turned off by calling
-# ToggleProgressPrinting() again.
-progressObserverTag = None
-currentAlgorithm = False
-currentProgress = 0
-fromGUI = False
-ToggleProgressPrinting()
-
-_pyproxies = {}
-
-# Create needed sub-modules
-# We can no longer create modules, unless we have connected to a server.
-# _createModules()
-
-# Set up our custom importer (if possible)
-loader = _ModuleLoader()
-sys.meta_path.append(loader)
-
-def __InitAfterConnect__(connection):
- """
- This function is called everytime after a server connection is made.
- Since the ProxyManager and all proxy definitions are changed every time a
- new connection is made, we re-create all the modules
- """
- _createModules(connection.Modules)
- ## VSV fromFilter is alwais False for SALOME because it can't be changed from ParaView code
- #if not paraview.fromFilter:
- # fromFilter is set when this module is imported from the programmable
- # filter
-# global _defUpdater
-# _defUpdater = __DefinitionUpdater()
- connection.AttachDefinitionUpdater()
- pass
-
-def __exposeActiveModules__():
- """Update servermanager submodules to point to the current
- ActiveConnection.Modules.*"""
- # Expose all active module to the current servermanager module
- if ActiveConnection:
- for m in [mName for mName in dir(ActiveConnection.Modules) if mName[0] != '_' ]:
- exec "global %s;%s = ActiveConnection.Modules.%s" % (m,m,m)
-
-# Definitions for working in SALOME GUI mode
-#aParams = myParavis.GetConnectionParameters()
-#ActiveConnection = Connect()
-##Connection(aParams[0])
-#ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5])
-#ToggleProgressPrinting()
-#fromGUI = True
+for name in dir(servermanager):
+ if name != "__file__":
+ globals()[name] = getattr(servermanager, name)
+del servermanager
InitFromGUI()
-
-if hasattr(sys, "ps1"):
- # session is interactive.
- print vtkSMProxyManager.GetParaViewSourceVersion();
-
-def GetConnectionFromId(id):
- for connection in MultiServerConnections:
- if connection.ID == id:
- return connection
- return None
-
-def GetConnectionFromSession(session):
- for connection in MultiServerConnections:
- if connection.Session == session:
- return connection
- return None
-
-def GetConnectionAt(index):
- return MultiServerConnections[index]
-
-def GetNumberOfConnections():
- return len(MultiServerConnections)
-
-#VTN: Problem during execution
-#atexit.register(vtkPythonProgrammableFilter.DeleteGlobalPythonInterpretor)
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-r"""simple is a module for using paraview server manager in Python. It
-provides a simple convenience layer to functionality provided by the
-C++ classes wrapped to Python as well as the servermanager module.
-
-A simple example:
- from paraview.simple import *
-
- # Create a new sphere proxy on the active connection and register it
- # in the sources group.
- sphere = Sphere(ThetaResolution=16, PhiResolution=32)
-
- # Apply a shrink filter
- shrink = Shrink(sphere)
-
- # Turn the visiblity of the shrink object on.
- Show(shrink)
-
- # Render the scene
- Render()
+r""" This module is a direct forward to the initial
+'simple' module of ParaView.
"""
-import paravisSM
-
-servermanager = paravisSM
-
-def enableMultiServer():
- servermanager.enableMultiServer()
-
-def switchActiveConnection(newActiveConnection=None, ns=None):
- if not ns:
- ns = globals()
- _remove_functions(ns)
- servermanager.switchActiveConnection(newActiveConnection)
- _add_functions(ns)
-
-def Disconnect(ns=None, force=True):
- if servermanager.ActiveConnection and (force or servermanager.MultiServerConnections == None):
- if ns:
- _remove_functions(ns)
- _remove_functions(globals())
- if not servermanager.fromGUI:
- servermanager.ProxyManager().DisableStateUpdateNotification()
- servermanager.ProxyManager().UnRegisterProxies()
- active_objects.view = None
- active_objects.source = None
- servermanager.Disconnect()
- if not servermanager.fromGUI:
- import gc
- gc.collect()
-
-def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
- """Creates a connection to a server. Example usage:
- > Connect("amber") # Connect to a single server at default port
- > Connect("amber", 12345) # Connect to a single server at port 12345
- > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair"""
- Disconnect(globals(), False)
- connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
- _add_functions(globals())
-
- servermanager.ProxyManager().DisableStateUpdateNotification()
- servermanager.ProxyManager().UpdateFromRemote()
- tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
- if not tk:
- try:
- tk = servermanager.misc.TimeKeeper()
- servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
- except AttributeError:
- print "Error: Could not create TimeKeeper"
-
- scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
- if not scene:
- try:
- scene = AnimationScene()
- scene.TimeKeeper = tk
- except NameError:
- print "Error: Could not create AnimationScene"
-
- servermanager.ProxyManager().EnableStateUpdateNotification()
- servermanager.ProxyManager().TriggerStateUpdate()
-
- return connection
-
-def ReverseConnect(port=11111):
- """Create a reverse connection to a server. Listens on port and waits for
- an incoming connection from the server."""
- Disconnect(globals(), False)
- connection = servermanager.ReverseConnect(port)
- _add_functions(globals())
-
- servermanager.ProxyManager().DisableStateUpdateNotification()
- servermanager.ProxyManager().UpdateFromRemote()
- tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
- if not tk:
- tk = servermanager.misc.TimeKeeper()
- servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
-
- scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
- if not scene:
- scene = AnimationScene()
- scene.TimeKeeper = tk
-
- servermanager.ProxyManager().EnableStateUpdateNotification()
- servermanager.ProxyManager().TriggerStateUpdate()
-
- return connection
-
-def _create_view(view_xml_name):
- "Creates and returns a 3D render view."
- view = servermanager._create_view(view_xml_name)
- servermanager.ProxyManager().RegisterProxy("views", \
- "my_view%d" % _funcs_internals.view_counter, view)
- active_objects.view = view
- _funcs_internals.view_counter += 1
-
- tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
- views = tk.Views
- if not view in views:
- views.append(view)
- try:
- scene = GetAnimationScene()
- if not view in scene.ViewModules:
- scene.ViewModules.append(view)
- except servermanager.MissingProxy:
- pass
- return view
-
-def CreateRenderView():
- return _create_view("RenderView")
-
-def CreateXYPlotView():
- return _create_view("XYChartView")
-
-def CreateBarChartView():
- return _create_view("XYBarChartView")
-
-def CreateComparativeRenderView():
- return _create_view("ComparativeRenderView")
-
-def CreateComparativeXYPlotView():
- return _create_view("ComparativeXYPlotView")
-
-def CreateComparativeBarChartView():
- return _create_view("ComparativeBarChartView")
-
-def CreateParallelCoordinatesChartView():
- return _create_view("ParallelCoordinatesChartView")
-
-def Create2DRenderView():
- return _create_view("2DRenderView")
-
-def OpenDataFile(filename, **extraArgs):
- """Creates a reader to read the give file, if possible.
- This uses extension matching to determine the best reader possible.
- If a reader cannot be identified, then this returns None."""
- session = servermanager.ActiveConnection.Session
- reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory()
- if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
- reader_factor.RegisterPrototypes(session, "sources")
- first_file = filename
- if type(filename) == list:
- first_file = filename[0]
- if not reader_factor.TestFileReadability(first_file, session):
- msg = "File not readable: %s " % first_file
- raise RuntimeError, msg
- if not reader_factor.CanReadFile(first_file, session):
- msg = "File not readable. No reader found for '%s' " % first_file
- raise RuntimeError, msg
- prototype = servermanager.ProxyManager().GetPrototypeProxy(
- reader_factor.GetReaderGroup(), reader_factor.GetReaderName())
- xml_name = paraview.make_name_valid(prototype.GetXMLLabel())
- reader_func = _create_func(xml_name, servermanager.sources)
- if prototype.GetProperty("FileNames"):
- reader = reader_func(FileNames=filename, **extraArgs)
- else :
- reader = reader_func(FileName=filename, **extraArgs)
- return reader
-
-def CreateWriter(filename, proxy=None, **extraArgs):
- """Creates a writer that can write the data produced by the source proxy in
- the given file format (identified by the extension). If no source is
- provided, then the active source is used. This doesn't actually write the
- data, it simply creates the writer and returns it."""
- if not filename:
- raise RuntimeError, "filename must be specified"
- session = servermanager.ActiveConnection.Session
- writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory()
- if writer_factory.GetNumberOfRegisteredPrototypes() == 0:
- writer_factory.RegisterPrototypes(session, "writers")
- if not proxy:
- proxy = GetActiveSource()
- if not proxy:
- raise RuntimeError, "Could not locate source to write"
- writer_proxy = writer_factory.CreateWriter(filename, proxy.SMProxy, proxy.Port)
- return servermanager._getPyProxy(writer_proxy)
-
-def GetRenderView():
- """Returns the active view if there is one. Else creates and returns a new view."""
- view = active_objects.view
- if not view:
- # it's possible that there's no active view, but a render view exists.
- # If so, locate that and return it (before trying to create a new one).
- view = servermanager.GetRenderView()
- if not view:
- view = CreateRenderView()
- return view
-
-def GetRenderViews():
- """Returns all render views as a list."""
- return servermanager.GetRenderViews()
-
-def GetRepresentation(proxy=None, view=None):
- """Given a pipeline object and view, returns the corresponding representation object.
- If pipeline object and view are not specified, active objects are used."""
- if not view:
- view = active_objects.view
- if not proxy:
- proxy = active_objects.source
- rep = servermanager.GetRepresentation(proxy, view)
- if not rep:
- rep = servermanager.CreateRepresentation(proxy, view)
- servermanager.ProxyManager().RegisterProxy("representations", \
- "my_representation%d" % _funcs_internals.rep_counter, rep)
- _funcs_internals.rep_counter += 1
- return rep
-
-def GetDisplayProperties(proxy=None, view=None):
- """Given a pipeline object and view, returns the corresponding representation object.
- If pipeline object and/or view are not specified, active objects are used."""
- return GetRepresentation(proxy, view)
-
-def Show(proxy=None, view=None, **params):
- """Turns the visibility of a given pipeline object on in the given view.
- If pipeline object and/or view are not specified, active objects are used."""
- if proxy == None:
- proxy = GetActiveSource()
- if proxy == None:
- raise RuntimeError, "Show() needs a proxy argument or that an active source is set."
- if not view and not active_objects.view:
- CreateRenderView()
- rep = GetDisplayProperties(proxy, view)
- if rep == None:
- raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel()
- for param in params.keys():
- setattr(rep, param, params[param])
- rep.Visibility = 1
- return rep
-
-def Hide(proxy=None, view=None):
- """Turns the visibility of a given pipeline object off in the given view.
- If pipeline object and/or view are not specified, active objects are used."""
- rep = GetDisplayProperties(proxy, view)
- rep.Visibility = 0
-
-def Render(view=None):
- """Renders the given view (default value is active view)"""
- if not view:
- view = active_objects.view
- view.StillRender()
- if _funcs_internals.first_render:
- # Not all views have a ResetCamera method
- try:
- view.ResetCamera()
- view.StillRender()
- except AttributeError: pass
- _funcs_internals.first_render = False
- return view
-
-def ResetCamera(view=None):
- """Resets the settings of the camera to preserver orientation but include
- the whole scene. If an argument is not provided, the active view is
- used."""
- if not view:
- view = active_objects.view
- if hasattr(view, "ResetCamera"):
- view.ResetCamera()
- if hasattr(view, "ResetDisplay"):
- view.ResetDisplay()
- Render(view)
-
-def _DisableFirstRenderCameraReset():
- """Disable the first render camera reset. Normally a ResetCamera is called
- automatically when Render is called for the first time after importing
- this module."""
- _funcs_internals.first_render = False
-
-def SetProperties(proxy=None, **params):
- """Sets one or more properties of the given pipeline object. If an argument
- is not provided, the active source is used. Pass a list of property_name=value
- pairs to this function to set property values. For example:
- SetProperties(Center=[1, 2, 3], Radius=3.5)
- """
- if not proxy:
- proxy = active_objects.source
- for param in params.keys():
- if not hasattr(proxy, param):
- raise AttributeError("object has no property %s" % param)
- setattr(proxy, param, params[param])
-
-def GetProperty(*arguments, **keywords):
- """Get one property of the given pipeline object. If keywords are used,
- you can set the proxy and the name of the property that you want to get
- like in the following example :
- GetProperty({proxy=sphere, name="Radius"})
- If it's arguments that are used, then you have two case:
- - if only one argument is used that argument will be
- the property name.
- - if two arguments are used then the first one will be
- the proxy and the second one the property name.
- Several example are given below:
- GetProperty({name="Radius"})
- GetProperty({proxy=sphereProxy, name="Radius"})
- GetProperty( sphereProxy, "Radius" )
- GetProperty( "Radius" )
- """
- name = None
- proxy = None
- for key in keywords:
- if key == "name":
- name = keywords[key]
- if key == "proxy":
- proxy = keywords[key]
- if len(arguments) == 1 :
- name = arguments[0]
- if len(arguments) == 2 :
- proxy = arguments[0]
- name = arguments[1]
- if not name:
- raise RuntimeError, "Expecting at least a property name as input. Otherwise keyword could be used to set 'proxy' and property 'name'"
- if not proxy:
- proxy = active_objects.source
- return proxy.GetProperty(name)
-
-def SetDisplayProperties(proxy=None, view=None, **params):
- """Sets one or more display properties of the given pipeline object. If an argument
- is not provided, the active source is used. Pass a list of property_name=value
- pairs to this function to set property values. For example:
- SetProperties(Color=[1, 0, 0], LineWidth=2)
- """
- rep = GetDisplayProperties(proxy, view)
- SetProperties(rep, **params)
-
-def SetViewProperties(view=None, **params):
- """Sets one or more properties of the given view. If an argument
- is not provided, the active view is used. Pass a list of property_name=value
- pairs to this function to set property values. For example:
- SetProperties(Background=[1, 0, 0], UseImmediateMode=0)
- """
- if not view:
- view = active_objects.view
- SetProperties(view, **params)
-
-def RenameSource(newName, proxy=None):
- """Renames the given source. If the given proxy is not registered
- in the sources group this method will have no effect. If no source is
- provided, the active source is used."""
- if not proxy:
- proxy = active_objects.source
- pxm = servermanager.ProxyManager()
- oldName = pxm.GetProxyName("sources", proxy)
- if oldName:
- pxm.RegisterProxy("sources", newName, proxy)
- pxm.UnRegisterProxy("sources", oldName, proxy)
-
-def FindSource(name):
- return servermanager.ProxyManager().GetProxy("sources", name)
-
-def GetSources():
- """Given the name of a source, return its Python object."""
- return servermanager.ProxyManager().GetProxiesInGroup("sources")
-
-def GetRepresentations():
- """Returns all representations (display properties)."""
- return servermanager.ProxyManager().GetProxiesInGroup("representations")
-
-def UpdatePipeline(time=None, proxy=None):
- """Updates (executes) the given pipeline object for the given time as
- necessary (i.e. if it did not already execute). If no source is provided,
- the active source is used instead."""
- if not proxy:
- proxy = active_objects.source
- if time:
- proxy.UpdatePipeline(time)
- else:
- proxy.UpdatePipeline()
-
-def Delete(proxy=None):
- """Deletes the given pipeline object or the active source if no argument
- is specified."""
- if not proxy:
- proxy = active_objects.source
- # Unregister any helper proxies stored by a vtkSMProxyListDomain
- for prop in proxy:
- listdomain = prop.GetDomain('proxy_list')
- if listdomain:
- if listdomain.GetClassName() != 'vtkSMProxyListDomain':
- continue
- group = "pq_helper_proxies." + proxy.GetGlobalIDAsString()
- for i in xrange(listdomain.GetNumberOfProxies()):
- pm = servermanager.ProxyManager()
- iproxy = listdomain.GetProxy(i)
- name = pm.GetProxyName(group, iproxy)
- if iproxy and name:
- pm.UnRegisterProxy(group, name, iproxy)
-
- # Remove source/view from time keeper
- tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
- if isinstance(proxy, servermanager.SourceProxy):
- try:
- idx = tk.TimeSources.index(proxy)
- del tk.TimeSources[idx]
- except ValueError:
- pass
- else:
- try:
- idx = tk.Views.index(proxy)
- del tk.Views[idx]
- except ValueError:
- pass
- servermanager.UnRegister(proxy)
-
- # If this is a representation, remove it from all views.
- if proxy.SMProxy.IsA("vtkSMRepresentationProxy") or \
- proxy.SMProxy.IsA("vtkSMNewWidgetRepresentationProxy"):
- for view in GetRenderViews():
- view.Representations.remove(proxy)
- # If this is a source, remove the representation iff it has no consumers
- # Also change the active source if necessary
- elif proxy.SMProxy.IsA("vtkSMSourceProxy"):
- sources = servermanager.ProxyManager().GetProxiesInGroup("sources")
- for i in range(proxy.GetNumberOfConsumers()):
- if proxy.GetConsumerProxy(i) in sources:
- raise RuntimeError("Source has consumers. It cannot be deleted " +
- "until all consumers are deleted.")
- #VSV:==
- if proxy.IsSame(GetActiveSource()):
- if hasattr(proxy, "Input") and proxy.Input:
- if isinstance(proxy.Input, servermanager.Proxy):
- SetActiveSource(proxy.Input)
- else:
- SetActiveSource(proxy.Input[0])
- else: SetActiveSource(None)
- for rep in GetRepresentations().values():
- #VSV:==
- if rep.Input.IsSame(proxy):
- Delete(rep)
- # Change the active view if necessary
- elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"):
- ##VSV:==
- if proxy.IsSame(GetActiveView()):
- if len(GetRenderViews()) > 0:
- SetActiveView(GetRenderViews()[0])
- else:
- SetActiveView(None)
-
-def CreateLookupTable(**params):
- """Create and return a lookup table. Optionally, parameters can be given
- to assign to the lookup table.
- """
- lt = servermanager.rendering.PVLookupTable()
- servermanager.Register(lt)
- SetProperties(lt, **params)
- return lt
-
-def CreatePiecewiseFunction(**params):
- """Create and return a piecewise function. Optionally, parameters can be
- given to assign to the piecewise function.
- """
- pfunc = servermanager.piecewise_functions.PiecewiseFunction()
- servermanager.Register(pfunc)
- SetProperties(pfunc, **params)
- return pfunc
-
-def GetLookupTableForArray(arrayname, num_components, **params):
- """Used to get an existing lookuptable for a array or to create one if none
- exists. Keyword arguments can be passed in to initialize the LUT if a new
- one is created."""
- proxyName = "%d.%s.PVLookupTable" % (int(num_components), arrayname)
- lut = servermanager.ProxyManager().GetProxy("lookup_tables", proxyName)
- if lut:
- return lut
- # No LUT exists for this array, create a new one.
- # TODO: Change this to go a LookupTableManager that is shared with the GUI,
- # so that the GUI and python end up create same type of LUTs. For now,
- # python will create a Blue-Red LUT, unless overridden by params.
- lut = servermanager.rendering.PVLookupTable(
- ColorSpace="HSV", RGBPoints=[0, 0, 0, 1, 1, 1, 0, 0])
- SetProperties(lut, **params)
- servermanager.Register(lut, registrationName=proxyName)
- return lut
-
-def CreateScalarBar(**params):
- """Create and return a scalar bar widget. The returned widget may
- be added to a render view by appending it to the view's representations
- The widget must have a valid lookup table before it is added to a view.
- It is possible to pass the lookup table (and other properties) as arguments
- to this method:
-
- lt = MakeBlueToRedLt(3.5, 7.5)
- bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
- GetRenderView().Representations.append(bar)
-
- By default the returned widget is selectable and resizable.
- """
- sb = servermanager.rendering.ScalarBarWidgetRepresentation()
- servermanager.Register(sb)
- sb.Selectable = 1
- sb.Resizable = 1
- sb.Enabled = 1
- sb.Title = "Scalars"
- SetProperties(sb, **params)
- return sb
-
-# TODO: Change this to take the array name and number of components. Register
-# the lt under the name ncomp.array_name
-def MakeBlueToRedLT(min, max):
- # Define RGB points. These are tuples of 4 values. First one is
- # the scalar values, the other 3 the RGB values.
- rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
- return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
-
-def _find_writer(filename):
- """Internal function."""
- extension = None
- parts = filename.split('.')
- if len(parts) > 1:
- extension = parts[-1]
- else:
- raise RuntimeError, "Filename has no extension, please specify a write"
-
- if extension == 'png':
- return 'vtkPNGWriter'
- elif extension == 'bmp':
- return 'vtkBMPWriter'
- elif extension == 'ppm':
- return 'vtkPNMWriter'
- elif extension == 'tif' or extension == 'tiff':
- return 'vtkTIFFWriter'
- elif extension == 'jpg' or extension == 'jpeg':
- return 'vtkJPEGWriter'
- else:
- raise RuntimeError, "Cannot infer filetype from extension:", extension
-
-def AddCameraLink(viewProxy, viewProxyOther, linkName):
- """Create a camera link between two view proxies. A name must be given
- so that the link can be referred to by name. If a link with the given
- name already exists it will be removed first."""
- if not viewProxyOther: viewProxyOther = GetActiveView()
- link = servermanager.vtkSMCameraLink()
- link.AddLinkedProxy(viewProxy.SMProxy, 1)
- link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
- link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
- link.AddLinkedProxy(viewProxy.SMProxy, 2)
- RemoveCameraLink(linkName)
- servermanager.ProxyManager().RegisterLink(linkName, link)
-
-def RemoveCameraLink(linkName):
- """Remove a camera link with the given name."""
- servermanager.ProxyManager().UnRegisterLink(linkName)
-
-def WriteImage(filename, view=None, **params):
- """Saves the given view (or the active one if none is given) as an
- image. Optionally, you can specify the writer and the magnification
- using the Writer and Magnification named arguments. For example:
- WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)
- If no writer is provided, the type is determined from the file extension.
- Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
- The writer is a VTK class that is capable of writing images.
- Magnification is used to determine the size of the written image. The size
- is obtained by multiplying the size of the view with the magnification.
- Rendering may be done using tiling to obtain the correct size without
- resizing the view."""
- if not view:
- view = active_objects.view
- writer = None
- if params.has_key('Writer'):
- writer = params['Writer']
- mag = 1
- if params.has_key('Magnification'):
- mag = int(params['Magnification'])
- if not writer:
- writer = _find_writer(filename)
- view.WriteImage(filename, writer, mag)
-
-def AnimateReader(reader=None, view=None, filename=None):
- """This is a utility function that, given a reader and a view
- animates over all time steps of the reader. If the optional
- filename is provided, a movie is created (type depends on the
- extension of the filename."""
- if not reader:
- reader = active_objects.source
- if not view:
- view = active_objects.view
-
- return servermanager.AnimateReader(reader, view, filename)
-
-
-def _create_func(key, module):
- """Internal function."""
-
- def CreateObject(*input, **params):
- """This function creates a new proxy. For pipeline objects that accept inputs,
- all non-keyword arguments are assumed to be inputs. All keyword arguments are
- assumed to be property,value pairs and are passed to the new proxy."""
-
- # Instantiate the actual object from the given module.
- px = module.__dict__[key]()
-
- # Make sure non-keyword arguments are valid
- for inp in input:
- if inp != None and not isinstance(inp, servermanager.Proxy):
- if px.GetProperty("Input") != None:
- raise RuntimeError, "Expecting a proxy as input."
- else:
- raise RuntimeError, "This function does not accept non-keyword arguments."
-
- # Assign inputs
- if px.GetProperty("Input") != None:
- if len(input) > 0:
- px.Input = input
- else:
- # If no input is specified, try the active pipeline object
- if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
- px.Input = active_objects.get_selected_sources()
- elif active_objects.source:
- px.Input = active_objects.source
- else:
- if len(input) > 0:
- raise RuntimeError, "This function does not expect an input."
-
- registrationName = None
- for nameParam in ['registrationName', 'guiName']:
- if nameParam in params:
- registrationName = params[nameParam]
- del params[nameParam]
-
- # Pass all the named arguments as property,value pairs
- for param in params.keys():
- setattr(px, param, params[param])
-
- try:
- # Register the proxy with the proxy manager.
- if registrationName:
- group, name = servermanager.Register(px, registrationName=registrationName)
- else:
- group, name = servermanager.Register(px)
-
-
- # Register pipeline objects with the time keeper. This is used to extract time values
- # from sources. NOTE: This should really be in the servermanager controller layer.
- if group == "sources":
- has_tk = True
- try:
- tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
- except IndexError:
- has_tk = False
- if has_tk:
- sources = tk.TimeSources
- if not px in sources:
- sources.append(px)
-
- active_objects.source = px
- except servermanager.MissingRegistrationInformation:
- pass
-
- return px
-
- return CreateObject
-
-def _create_doc(new, old):
- """Internal function."""
- import string
- res = ""
- for doc in (new, old):
- ts = []
- strpd = doc.split('\n')
- for s in strpd:
- ts.append(s.lstrip())
- res += string.join(ts)
- res += '\n'
- return res
-
-def _func_name_valid(name):
- """Internal function."""
- valid = True
- for c in name:
- if c == '(' or c ==')':
- valid = False
- break
- return valid
-
-def _add_functions(g):
- activeModule = servermanager.ActiveConnection.Modules
- for m in [activeModule.filters, activeModule.sources,
- activeModule.writers, activeModule.animation]:
- dt = m.__dict__
- for key in dt.keys():
- cl = dt[key]
- if not isinstance(cl, str):
- if not key in g and _func_name_valid(key):
- g[key] = _create_func(key, m)
- exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key
-
-def _remove_functions(g):
- list = []
- if servermanager.ActiveConnection:
- list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_']
-
- for m in list:
- dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__
- for key in dt.keys():
- cl = dt[key]
- if not isinstance(cl, str) and g.has_key(key):
- g.pop(key)
- #print "remove %s function" % key
-
-def GetActiveView():
- """Returns the active view."""
- return active_objects.view
-
-def SetActiveView(view):
- """Sets the active view."""
- active_objects.view = view
-
-def GetActiveSource():
- """Returns the active source."""
- return active_objects.source
-
-def SetActiveSource(source):
- """Sets the active source."""
- active_objects.source = source
-
-def GetActiveCamera():
- """Returns the active camera for the active view. The returned object
- is an instance of vtkCamera."""
- return GetActiveView().GetActiveCamera()
-
-def GetAnimationScene():
- """Returns the application-wide animation scene. ParaView has only one
- global animation scene. This method provides access to that. Users are
- free to create additional animation scenes directly, but those scenes
- won't be shown in the ParaView GUI."""
- animation_proxies = servermanager.ProxyManager().GetProxiesInGroup("animation")
- scene = None
- for aProxy in animation_proxies.values():
- if aProxy.GetXMLName() == "AnimationScene":
- scene = aProxy
- break
- if not scene:
- raise servermanager.MissingProxy, "Could not locate global AnimationScene."
- return scene
-
-def WriteAnimation(filename, **params):
- """Writes the current animation as a file. Optionally one can specify
- arguments that qualify the saved animation files as keyword arguments.
- Accepted options are as follows:
- * Magnification (integer) : set the maginification factor for the saved
- animation.
- * Quality (0 [worst] or 1 or 2 [best]) : set the quality of the generated
- movie (if applicable).
- * Subsampling (integer) : setting whether the movie encoder should use
- subsampling of the chrome planes or not, if applicable. Since the human
- eye is more sensitive to brightness than color variations, subsampling
- can be useful to reduce the bitrate. Default value is 0.
- * BackgroundColor (3-tuple of doubles) : set the RGB background color to
- use to fill empty spaces in the image.
- * FrameRate (double): set the frame rate (if applicable)."""
- scene = GetAnimationScene()
- # ensures that the TimeKeeper track is created.
- GetTimeTrack()
- iw = servermanager.vtkSMAnimationSceneImageWriter()
- iw.SetAnimationScene(scene.SMProxy)
- iw.SetFileName(filename)
- if params.has_key("Magnification"):
- iw.SetMagnification(int(params["Magnification"]))
- if params.has_key("Quality"):
- iw.SetQuality(int(params["Quality"]))
- if params.has_key("Subsampling"):
- iw.SetSubsampling(int(params["Subsampling"]))
- if params.has_key("BackgroundColor"):
- iw.SetBackgroundColor(params["BackgroundColor"])
- if params.has_key("FrameRate"):
- iw.SetFrameRate(float(params["FrameRate"]))
- iw.Save()
-
-def _GetRepresentationAnimationHelper(sourceproxy):
- """Internal method that returns the representation animation helper for a
- source proxy. It creates a new one if none exists."""
- # ascertain that proxy is a source proxy
- if not sourceproxy in GetSources().values():
- return None
- for proxy in servermanager.ProxyManager():
- if proxy.GetXMLName() == "RepresentationAnimationHelper" and\
- proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy):
- return proxy
- # create a new helper
- proxy = servermanager.misc.RepresentationAnimationHelper(
- Source=sourceproxy)
- servermanager.ProxyManager().RegisterProxy(
- "pq_helper_proxies.%s" % sourceproxy.GetGlobalIDAsString(),
- "RepresentationAnimationHelper", proxy)
- return proxy
-
-def GetAnimationTrack(propertyname_or_property, index=None, proxy=None):
- """Returns an animation cue for the property. If one doesn't exist then a
- new one will be created.
- Typical usage:
- track = GetAnimationTrack("Center", 0, sphere) or
- track = GetAnimationTrack(sphere.GetProperty("Radius")) or
-
- # this returns the track to animate visibility of the active source in
- # all views.
- track = GetAnimationTrack("Visibility")
-
- For animating properties on implicit planes etc., use the following
- signatures:
- track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or
- track = GetAnimationTrack("Origin", 0, slice.SliceType)
-
- """
- if not proxy:
- proxy = GetActiveSource()
- if not isinstance(proxy, servermanager.Proxy):
- raise TypeError, "proxy must be a servermanager.Proxy instance"
- if isinstance(propertyname_or_property, str):
- propertyname = propertyname_or_property
- elif isinstance(propertyname_or_property, servermanager.Property):
- prop = propertyname_or_property
- propertyname = prop.Name
- proxy = prop.Proxy
- else:
- raise TypeError, "propertyname_or_property must be a string or servermanager.Property"
-
- # To handle the case where the property is actually a "display" property, in
- # which case we are actually animating the "RepresentationAnimationHelper"
- # associated with the source.
- if propertyname in ["Visibility", "Opacity"]:
- proxy = _GetRepresentationAnimationHelper(proxy)
- if not proxy or not proxy.GetProperty(propertyname):
- raise AttributeError, "Failed to locate property %s" % propertyname
-
- scene = GetAnimationScene()
- for cue in scene.Cues:
- try:
- if cue.AnimatedProxy.IsSame(proxy) and\
- cue.AnimatedPropertyName == propertyname:
- if index == None or index.IsSame(cue.AnimatedElement): ##index == cue.AnimatedElement:
- return cue
- except AttributeError:
- pass
-
- # matching animation track wasn't found, create a new one.
- cue = KeyFrameAnimationCue()
- cue.AnimatedProxy = proxy
- cue.AnimatedPropertyName = propertyname
- if index != None:
- cue.AnimatedElement = index
- scene.Cues.append(cue)
- return cue
-
-def GetCameraTrack(view=None):
- """Returns the camera animation track for the given view. If no view is
- specified, active view will be used. If no exisiting camera animation track
- is found, a new one will be created."""
- if not view:
- view = GetActiveView()
- if not view:
- raise ValueError, "No view specified"
- scene = GetAnimationScene()
- for cue in scene.Cues:
- if cue.AnimatedProxy.IsSame(view) and\
- cue.GetXMLName() == "CameraAnimationCue":
- return cue
- # no cue was found, create a new one.
- cue = CameraAnimationCue()
- cue.AnimatedProxy = view
- scene.Cues.append(cue)
- return cue
-
-def GetTimeTrack():
- """Returns the animation track used to control the time requested from all
- readers/filters during playback.
- This is the "TimeKeeper - Time" track shown in ParaView's 'Animation View'.
- If none exists, a new one will be created."""
- scene = GetAnimationScene()
- tk = scene.TimeKeeper
- for cue in scene.Cues:
- if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy.IsSame(tk)\
- and cue.AnimatedPropertyName == "Time":
- return cue
- # no cue was found, create a new one.
- cue = TimeAnimationCue()
- cue.AnimatedProxy = tk
- cue.AnimatedPropertyName = "Time"
- scene.Cues.append(cue)
- return cue
-
-def LoadXML(xmlstring, ns=None):
- """Given a server manager XML as a string, parse and process it.
- If you loaded the simple module with from paraview.simple import *,
- make sure to pass globals() as the second arguments:
- LoadXML(xmlstring, globals())
- Otherwise, the new functions will not appear in the global namespace."""
- if not ns:
- ns = globals()
- servermanager.LoadXML(xmlstring)
- _add_functions(ns)
-
-def LoadPlugin(filename, remote=True, ns=None):
- """Loads a ParaView plugin and updates this module with new constructors
- if any. The remote argument (default to True) is to specify whether
- the plugin will be loaded on client (remote=False) or on server (remote=True).
- If you loaded the simple module with from paraview.simple import *,
- make sure to pass globals() as an argument:
- LoadPlugin("myplugin", False, globals()), to load on client;
- LoadPlugin("myplugin", True, globals()), to load on server;
- LoadPlugin("myplugin", ns=globals()), to load on server.
- Otherwise, the new functions will not appear in the global namespace."""
-
- if not ns:
- ns = globals()
- servermanager.LoadPlugin(filename, remote)
- _add_functions(ns)
-
-def LoadDistributedPlugin(pluginname, remote=True, ns=None):
- """Loads a plugin that's distributed with the executable. This uses the
- information known about plugins distributed with ParaView to locate the
- shared library for the plugin to load. Raises a RuntimeError if the plugin
- was not found."""
- if not servermanager.ActiveConnection:
- raise RuntimeError, "Cannot load a plugin without a session."
- plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager()
- if remote:
- session = servermanager.ActiveConnection.Session
- info = plm.GetRemoteInformation(session)
- else:
- info = plm.GetLocalInformation()
- for cc in range(0, info.GetNumberOfPlugins()):
- if info.GetPluginName(cc) == pluginname:
- return LoadPlugin(info.GetPluginFileName(cc), remote, ns)
- raise RuntimeError, "Plugin '%s' not found" % pluginname
-
-def GetLayouts():
- """Returns the layout proxies on the active session.
- Layout proxies are used to place views in a grid."""
- return servermanager.ProxyManager().GetProxiesInGroup("layouts")
-
-def GetLayout(view=None):
- """Return the layout containing the give view, if any.
- If no view is specified, active view is used.
- """
- if not view:
- view = GetActiveView()
- if not view:
- raise RuntimeError, "No active view was found."
- layouts = GetLayouts()
- for layout in layouts.values():
- if layout.GetViewLocation(view) != -1:
- return layout
- return None
-
-
-def SelectCells(query=None, proxy=None):
- """Select cells satisfying the query. If query is None, then all cells are
- selected. If proxy is None, then the active source is used."""
- if not proxy:
- proxy = GetActiveSource()
- if not proxy:
- raise RuntimeError, "No active source was found."
-
- if not query:
- # This ends up being true for all cells.
- query = "id >= 0"
-
- # Note, selSource is not registered with the proxy manager.
- selSource = servermanager.sources.SelectionQuerySource()
- selSource.FieldType = "CELL"
- selSource.QueryString = str(query)
- proxy.SMProxy.SetSelectionInput(proxy.Port, selSource.SMProxy, 0)
- return selSource
-
-def ClearSelection(proxy=None):
- """Clears the selection on the active source."""
- if not proxy:
- proxy = GetActiveSource()
- if not proxy:
- raise RuntimeError, "No active source was found."
- proxy.SMProxy.SetSelectionInput(proxy.Port, None, 0)
-
-class ActiveObjects(object):
- """This class manages the active objects (source and view). The active
- objects are shared between Python and the user interface. This class
- is for internal use. Use the Set/Get methods for setting and getting
- active objects."""
- def __get_selection_model(self, name, session=None):
- "Internal method."
- if session and not servermanager.ActiveConnection.Session.IsSame(session):
- raise RuntimeError, "Try to set an active object with invalid active connection."
- pxm = servermanager.ProxyManager(session)
- model = pxm.GetSelectionModel(name)
- if not model:
- model = servermanager.vtkSMProxySelectionModel()
- pxm.RegisterSelectionModel(name, model)
- return model
-
- def set_view(self, view):
- "Sets the active view."
- active_view_model = self.__get_selection_model("ActiveView")
- if view:
- active_view_model = self.__get_selection_model("ActiveView", view.GetSession())
- active_view_model.SetCurrentProxy(view.SMProxy, 0)
- else:
- active_view_model = self.__get_selection_model("ActiveView")
- active_view_model.SetCurrentProxy(None, 0)
-
- def get_view(self):
- "Returns the active view."
- return servermanager._getPyProxy(
- self.__get_selection_model("ActiveView").GetCurrentProxy())
-
- def set_source(self, source):
- "Sets the active source."
- active_sources_model = self.__get_selection_model("ActiveSources")
- if source:
- # 3 == CLEAR_AND_SELECT
- active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession())
- active_sources_model.SetCurrentProxy(source.SMProxy, 3)
- else:
- active_sources_model = self.__get_selection_model("ActiveSources")
- active_sources_model.SetCurrentProxy(None, 3)
-
- def __convert_proxy(self, px):
- "Internal method."
- if not px:
- return None
- if px.IsA("vtkSMSourceProxy"):
- return servermanager._getPyProxy(px)
- else:
- return servermanager.OutputPort(
- servermanager._getPyProxy(px.GetSourceProxy()),
- px.GetPortIndex())
-
- def get_source(self):
- "Returns the active source."
- return self.__convert_proxy(
- self.__get_selection_model("ActiveSources").GetCurrentProxy())
-
- def get_selected_sources(self):
- "Returns the set of sources selected in the pipeline browser."
- model = self.__get_selection_model("ActiveSources")
- proxies = []
- for i in xrange(model.GetNumberOfSelectedProxies()):
- proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
- return proxies
-
- view = property(get_view, set_view)
- source = property(get_source, set_source)
-
-class _funcs_internals:
- """Internal class."""
- first_render = True
- view_counter = 0
- rep_counter = 0
-
-def demo1():
- """Simple demo that create the following pipeline
- sphere - shrink - \
- - append
- cone - /
- """
- # Create a sphere of radius = 2, theta res. = 32
- # This object becomes the active source.
- ss = Sphere(Radius=2, ThetaResolution=32)
- # Apply the shrink filter. The Input property is optional. If Input
- # is not specified, the filter is applied to the active source.
- shr = Shrink(Input=ss)
- # Create a cone source.
- cs = Cone()
- # Append cone and shrink
- app = AppendDatasets()
- app.Input = [shr, cs]
- # Show the output of the append filter. The argument is optional
- # as the app filter is now the active object.
- Show(app)
- # Render the default view.
- Render()
-
-def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"):
- """This demo shows the use of readers, data information and display
- properties."""
-
- # Create the exodus reader and specify a file name
- reader = ExodusIIReader(FileName=fname)
- # Get the list of point arrays.
- avail = reader.PointVariables.Available
- print avail
- # Select all arrays
- reader.PointVariables = avail
-
- # Turn on the visibility of the reader
- Show(reader)
- # Set representation to wireframe
- SetDisplayProperties(Representation = "Wireframe")
- # Black background is not pretty
- SetViewProperties(Background = [0.4, 0.4, 0.6])
- Render()
- # Change the elevation of the camera. See VTK documentation of vtkCamera
- # for camera parameters.
- # NOTE: THIS WILL BE SIMPLER
- GetActiveCamera().Elevation(45)
- Render()
- # Now that the reader executed, let's get some information about it's
- # output.
- pdi = reader[0].PointData
- # This prints a list of all read point data arrays as well as their
- # value ranges.
- print 'Number of point arrays:', len(pdi)
- for i in range(len(pdi)):
- ai = pdi[i]
- print "----------------"
- print "Array:", i, " ", ai.Name, ":"
- numComps = ai.GetNumberOfComponents()
- print "Number of components:", numComps
- for j in range(numComps):
- print "Range:", ai.GetRange(j)
- # White is boring. Let's color the geometry using a variable.
- # First create a lookup table. This object controls how scalar
- # values are mapped to colors. See VTK documentation for
- # details.
- # Map min (0.00678) to blue, max (0.0288) to red
- SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
- # Color by point array called Pres
- SetDisplayProperties(ColorAttributeType = "POINT_DATA")
- SetDisplayProperties(ColorArrayName = "Pres")
- Render()
-
-def PrintTrace():
- print paravisSM.myParavis.GetTrace()
-
-def SaveTrace(fileName):
- paravisSM.myParavis.SaveTrace(fileName)
-
-
-if not servermanager.ActiveConnection:
- Connect()
-else:
- _add_functions(globals())
-
-def ImportFile(theFileName):
- paravisSM.ImportFile(theFileName)
-
-active_objects = ActiveObjects()
-active_objects.view = GetRenderView()
+from paraview import simple
+
+for name in dir(simple):
+ if name != "__file__":
+ globals()[name] = getattr(simple, name)
+del simple
+
+print "Connecting to PVServer ..."
+try:
+ # TODO: this should be improved (retrieval from the engine)
+ Connect('localhost')
+except Exception as e:
+ print "*******************************************"
+ print "*******************************************"
+ print "Could not connect to PVServer on localhost!"
+ print "*******************************************"
+ print "*******************************************"
+ raise e
+++ /dev/null
-0a1,19
-> # Copyright (C) 2010-2013 CEA/DEN, EDF R&D
-> #
-> # This library is free software; you can redistribute it and/or
-> # modify it under the terms of the GNU Lesser General Public
-> # License as published by the Free Software Foundation; either
-> # version 2.1 of the License.
-> #
-> # This library is distributed in the hope that it will be useful,
-> # but WITHOUT ANY WARRANTY; without even the implied warranty of
-> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-> # Lesser General Public License for more details.
-> #
-> # You should have received a copy of the GNU Lesser General Public
-> # License along with this library; if not, write to the Free Software
-> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-> #
-> # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-> #
->
-29,43d47
-< #==============================================================================
-< #
-< # Program: ParaView
-< # Module: servermanager.py
-< #
-< # Copyright (c) Kitware, Inc.
-< # All rights reserved.
-< # See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
-< #
-< # This software is distributed WITHOUT ANY WARRANTY without even
-< # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-< # PURPOSE. See the above copyright notice for more information.
-< #
-< #==============================================================================
-< import paraview, re, os, os.path, new, sys, vtk
-45,53c49,54
-< if not paraview.compatibility.minor:
-< paraview.compatibility.major = 3
-< if not paraview.compatibility.major:
-< paraview.compatibility.minor = 5
-<
-< from vtkPVClientServerCorePython import *
-< from vtkPVServerImplementationPython import *
-< from vtkPVServerManagerPython import *
-< from vtkPVCommonPython import *
----
->
->
-> import re, os, new, sys
-> from paravis import *
->
->
-61,62c62
-< if paraview.compatibility.GetVersion() >= 3.5 and \
-< smproperty.IsA("vtkSMStringVectorProperty"):
----
-> if smproperty.IsA("vtkSMStringVectorProperty"):
-251,252c251,253
-< return self.SMProxy == other.SMProxy
-< return self.SMProxy == other
----
-> ## VSV using IsSame instead ==
-> return self.SMProxy.IsSame(other.SMProxy)
-> return self.SMProxy.IsSame(other)
-347,350c348,351
-< if not c.HasObserver("ModifiedEvent"):
-< self.ObserverTag =c.AddObserver("ModifiedEvent", \
-< _makeUpdateCameraMethod(weakref.ref(self)))
-< self.Observed = c
----
-> # VSV: Observers are not supported
-> ## if not c.HasObserver("ModifiedEvent"):
-> ## self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self)))
-> ## self.Observed = c
-454,472c455,472
-< if paraview.compatibility.GetVersion() >= 3.5:
-< def FileNameChanged(self):
-< "Called when the filename changes. Selects all variables."
-< SourceProxy.FileNameChanged(self)
-< self.SelectAllVariables()
-<
-< def SelectAllVariables(self):
-< "Select all available variables for reading."
-< for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
-< 'ElementVariables', 'GlobalVariables'):
-< f = getattr(self, prop)
-< f.SelectAll()
-<
-< def DeselectAllVariables(self):
-< "Deselects all variables."
-< for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
-< 'ElementVariables', 'GlobalVariables'):
-< f = getattr(self, prop)
-< f.DeselectAll()
----
-> def FileNameChanged(self):
-> "Called when the filename changes. Selects all variables."
-> SourceProxy.FileNameChanged(self)
-> self.SelectAllVariables()
->
-> def SelectAllVariables(self):
-> "Select all available variables for reading."
-> for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
-> 'ElementVariables', 'GlobalVariables'):
-> f = getattr(self, prop)
-> f.SelectAll()
->
-> def DeselectAllVariables(self):
-> "Deselects all variables."
-> for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
-> 'ElementVariables', 'GlobalVariables'):
-> f = getattr(self, prop)
-> f.DeselectAll()
-1110c1110,1111
-< if proxy == px:
----
-> ## VSV: ==
-> if proxy.IsSame(px):
-1329,1332d1329
-< if paraview.compatibility.GetVersion() <= 3.4:
-< def Range(self, component=0):
-< return self.GetRange(component)
-<
-1526c1523
-< aProxy = self.SMProxyManager.NewProxy(group, name)
----
-> aProxy = self.SMProxyManager.NewProxy(group, name, "NULL")
-1838a1836
-> # VTN: Observers are not supported
-1840c1838
-< self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions)
----
-> ## self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions)
-1842c1840
-< self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions)
----
-> ## self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions)
-2056c2054,2055
-< try: isRep = rep.Input == aProxy
----
-> #VSV: ==
-> try: isRep = rep.Input.IsSame(aProxy)
-2287,2303c2286,2287
-< """Turn on/off printing of progress (by default, it is on). You can
-< always turn progress off and add your own observer to the process
-< module to handle progress in a custom way. See _printProgress for
-< an example event observer."""
-< global progressObserverTag
-<
-< # If value is true and progress printing is currently off...
-< if value and not GetProgressPrintingIsEnabled():
-< if fromGUI:
-< raise RuntimeError("Printing progress in the GUI is not supported.")
-< progressObserverTag = vtkProcessModule.GetProcessModule().AddObserver(\
-< "ProgressEvent", _printProgress)
-<
-< # If value is false and progress printing is currently on...
-< elif GetProgressPrintingIsEnabled():
-< vtkProcessModule.GetProcessModule().RemoveObserver(progressObserverTag)
-< progressObserverTag = None
----
-> """Is not supported because of not supported observers"""
-> pass
-2330,2332c2314,2315
-< if paraview.compatibility.GetVersion() >= 3.5:
-< if smproxy.GetXMLLabel():
-< xmlName = smproxy.GetXMLLabel()
----
-> if smproxy.GetXMLLabel():
-> xmlName = smproxy.GetXMLLabel()
-2375,2378c2358
-< if paraview.compatibility.GetVersion() >= 3.5:
-< return self.GetPropertyValue(propName)
-< else:
-< return self.GetProperty(propName)
----
-> return self.GetPropertyValue(propName)
-2494c2474,2482
-< return paraview.make_name_valid(name)
----
-> """Make a string into a valid Python variable name."""
-> if not name:
-> return None
-> import string
-> valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
-> name = str().join([c for c in name if c in valid_chars])
-> if not name[0].isalpha():
-> name = 'a' + name
-> return name
-2520,2521c2508
-< if paraview.compatibility.GetVersion() >= 3.5 and\
-< proto.GetXMLLabel():
----
-> if proto.GetXMLLabel():
-2536,2539c2523,2525
-< if paraview.compatibility.GetVersion() >= 3.5:
-< if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
-< or prop.GetIsInternal():
-< continue
----
-> if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
-> or prop.GetIsInternal():
-> continue
-2541,2542c2527
-< if paraview.compatibility.GetVersion() >= 3.5:
-< names = [iter.PropertyLabel]
----
-> names = [iter.PropertyLabel]
-2681,2690c2666,2669
-< if paraview.compatibility.GetVersion() <= 3.4:
-< ss = sources.SphereSource(Radius=2, ThetaResolution=32)
-< shr = filters.ShrinkFilter(Input=OutputPort(ss,0))
-< cs = sources.ConeSource()
-< app = filters.Append()
-< else:
-< ss = sources.Sphere(Radius=2, ThetaResolution=32)
-< shr = filters.Shrink(Input=OutputPort(ss,0))
-< cs = sources.Cone()
-< app = filters.AppendDatasets()
----
-> ss = sources.Sphere(Radius=2, ThetaResolution=32)
-> shr = filters.Shrink(Input=OutputPort(ss,0))
-> cs = sources.Cone()
-> app = filters.AppendDatasets()
-2711,2714c2690
-< if paraview.compatibility.GetVersion() <= 3.4:
-< arraySelection = reader.PointResultArrayStatus
-< else:
-< arraySelection = reader.PointVariables
----
-> arraySelection = reader.PointVariables
-2748,2751c2724
-< if paraview.compatibility.GetVersion() <= 3.4:
-< print "Range:", ai.Range(j)
-< else:
-< print "Range:", ai.GetRange(j)
----
-> print "Range:", ai.GetRange(j)
-2782,2785c2755
-< if paraview.compatibility.GetVersion() <= 3.4:
-< source = sources.RTAnalyticSource()
-< else:
-< source = sources.Wavelet()
----
-> source = sources.Wavelet()
-2816,2823c2786,2788
-< if paraview.compatibility.GetVersion() <= 3.4:
-< probe = filters.Probe(Input=source)
-< # with a line
-< line = sources.LineSource(Resolution=60)
-< else:
-< probe = filters.ResampleWithDataset(Input=source)
-< # with a line
-< line = sources.Line(Resolution=60)
----
-> probe = filters.ResampleWithDataset(Input=source)
-> # with a line
-> line = sources.Line(Resolution=60)
-2867,2870c2832
-< if paraview.compatibility.GetVersion() <= 3.4:
-< sphere = sources.SphereSource()
-< else:
-< sphere = sources.Sphere()
----
-> sphere = sources.Sphere()
-2960,2965c2922,2927
-< pvoptions = None
-< if paraview.options.batch:
-< pvoptions = vtkPVOptions();
-< pvoptions.SetProcessType(0x40)
-< if paraview.options.symmetric:
-< pvoptions.SetSymmetricMPIMode(True)
----
-> # pvoptions = None Not applicable for SALOME Python console
-> # if paraview.options.batch:
-> # pvoptions = vtkPVOptions();
-> # pvoptions.SetProcessType(0x40)
-> # if paraview.options.symmetric:
-> # pvoptions.SetSymmetricMPIMode(True)
-2994,2995c2956,2957
-<
-< if not paraview.fromFilter:
----
-> ## VSV fromFilter is alwais False for SALOME because it can't be changed from ParaView code
-> #if not paraview.fromFilter:
-2998,2999c2960,2963
-< connection.AttachDefinitionUpdater()
-< pass
----
-> # global _defUpdater
-> # _defUpdater = __DefinitionUpdater()
-> connection.AttachDefinitionUpdater()
-> pass
-3008a2973,2982
-> # Definitions for working in SALOME GUI mode
-> #aParams = myParavis.GetConnectionParameters()
-> #ActiveConnection = Connect()
-> ##Connection(aParams[0])
-> #ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5])
-> #ToggleProgressPrinting()
-> #fromGUI = True
->
-> InitFromGUI()
->
+++ /dev/null
-0a1,19
-> # Copyright (C) 2010-2013 CEA/DEN, EDF R&D
-> #
-> # This library is free software; you can redistribute it and/or
-> # modify it under the terms of the GNU Lesser General Public
-> # License as published by the Free Software Foundation; either
-> # version 2.1 of the License.
-> #
-> # This library is distributed in the hope that it will be useful,
-> # but WITHOUT ANY WARRANTY; without even the implied warranty of
-> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-> # Lesser General Public License for more details.
-> #
-> # You should have received a copy of the GNU Lesser General Public
-> # License along with this library; if not, write to the Free Software
-> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-> #
-> # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-> #
->
-21,34d39
-< #==============================================================================
-< #
-< # Program: ParaView
-< # Module: simple.py
-< #
-< # Copyright (c) Kitware, Inc.
-< # All rights reserved.
-< # See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
-< #
-< # This software is distributed WITHOUT ANY WARRANTY; without even
-< # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-< # PURPOSE. See the above copyright notice for more information.
-< #
-< #==============================================================================
-36,39c41
-< import paraview
-< paraview.compatibility.major = 3
-< paraview.compatibility.minor = 5
-< import servermanager
----
-> import paravisSM
-41,42c43
-< def enableMultiServer():
-< servermanager.enableMultiServer()
----
-> servermanager = paravisSM
-44,56c45,46
-< def switchActiveConnection(newActiveConnection=None, ns=None):
-< if not ns:
-< ns = globals()
-< _remove_functions(ns)
-< servermanager.switchActiveConnection(newActiveConnection)
-< _add_functions(ns)
-<
-< def Disconnect(ns=None, force=True):
-< if servermanager.ActiveConnection and (force or servermanager.MultiServerConnections == None):
-< if ns:
-< _remove_functions(ns)
-< _remove_functions(globals())
-< servermanager.ProxyManager().DisableStateUpdateNotification()
----
-> def _disconnect():
-> if servermanager.ActiveConnection:
-61d50
-< servermanager.Disconnect()
-62a52
-> servermanager.Disconnect()
-69,70c59,60
-< Disconnect(globals(), False)
-< connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
----
-> _disconnect()
-> session = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
-73,88c63,67
-< servermanager.ProxyManager().DisableStateUpdateNotification()
-< servermanager.ProxyManager().UpdateFromRemote()
-< tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
-< if not tk:
-< tk = servermanager.misc.TimeKeeper()
-< servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
-<
-< scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
-< if not scene:
-< scene = AnimationScene()
-< scene.TimeKeeper = tk
-<
-< servermanager.ProxyManager().EnableStateUpdateNotification()
-< servermanager.ProxyManager().TriggerStateUpdate()
-<
-< return connection
----
-> tk = servermanager.misc.TimeKeeper()
-> servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", tk)
-> scene = AnimationScene()
-> scene.TimeKeeper = tk
-> return session
-93,94c72,73
-< Disconnect(globals(), False)
-< connection = servermanager.ReverseConnect(port)
----
-> _disconnect()
-> session = servermanager.ReverseConnect(port)
-96,112c75,79
-<
-< servermanager.ProxyManager().DisableStateUpdateNotification()
-< servermanager.ProxyManager().UpdateFromRemote()
-< tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
-< if not tk:
-< tk = servermanager.misc.TimeKeeper()
-< servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
-<
-< scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
-< if not scene:
-< scene = AnimationScene()
-< scene.TimeKeeper = tk
-<
-< servermanager.ProxyManager().EnableStateUpdateNotification()
-< servermanager.ProxyManager().TriggerStateUpdate()
-<
-< return connection
----
-> tk = servermanager.misc.TimeKeeper()
-> servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", tk)
-> scene = AnimationScene()
-> scene.TimeKeeper = tk
-> return session
-121c88
-<
----
->
-161a129,131
-> reader_factor = servermanager.ProxyManager().GetReaderFactory()
-> if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
-> reader_factor.RegisterPrototypes("sources")
-163,165d132
-< reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory()
-< if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
-< reader_factor.RegisterPrototypes(session, "sources")
-170,171c137
-< msg = "File not readable: %s " % first_file
-< raise RuntimeError, msg
----
-> raise RuntimeError, "File not readable: %s " % first_file
-173,174c139
-< msg = "File not readable. No reader found for '%s' " % first_file
-< raise RuntimeError, msg
----
-> raise RuntimeError, "File not readable. No reader found for '%s' " % first_file
-192,193c157
-< session = servermanager.ActiveConnection.Session
-< writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory()
----
-> writer_factory = servermanager.ProxyManager().GetWriterFactory()
-195c159
-< writer_factory.RegisterPrototypes(session, "writers")
----
-> writer_factory.RegisterPrototypes("writers")
-441c405,406
-< if proxy == GetActiveSource():
----
-> #VSV:==
-> if proxy.IsSame(GetActiveSource()):
-449c414,415
-< if rep.Input == proxy:
----
-> #VSV:==
-> if rep.Input.IsSame(proxy):
-453c419,420
-< if proxy == GetActiveView():
----
-> ##VSV:==
-> if proxy.IsSame(GetActiveView()):
-691,693c658,659
-< activeModule = servermanager.ActiveConnection.Modules
-< for m in [activeModule.filters, activeModule.sources,
-< activeModule.writers, activeModule.animation]:
----
-> for m in [servermanager.filters, servermanager.sources,
-> servermanager.writers, servermanager.animation]:
-699d664
-< #print "add %s function" % key
-703,715d667
-< def _remove_functions(g):
-< list = []
-< if servermanager.ActiveConnection:
-< list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_']
-<
-< for m in list:
-< dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__
-< for key in dt.keys():
-< cl = dt[key]
-< if not isinstance(cl, str) and g.has_key(key):
-< g.pop(key)
-< #print "remove %s function" % key
-<
-844c796
-< if cue.AnimatedProxy == proxy and\
----
-> if cue.AnimatedProxy.IsSame(proxy) and\
-846c798
-< if index == None or index == cue.AnimatedElement:
----
-> if index == None or index.IsSame(cue.AnimatedElement): ##index == cue.AnimatedElement:
-870c822
-< if cue.AnimatedProxy == view and\
----
-> if cue.AnimatedProxy.IsSame(view) and\
-887c839
-< if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy == tk\
----
-> if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy.IsSame(tk)\
-929,931c881
-< if not servermanager.ActiveConnection:
-< raise RuntimeError, "Cannot load a plugin without a session."
-< plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager()
----
-> plm = servermanager.ProxyManager().GetSession().GetPluginManager()
-933,934c883
-< session = servermanager.ActiveConnection.Session
-< info = plm.GetRemoteInformation(session)
----
-> info = plm.GetRemoteInformation()
-942,959d890
-< def GetLayouts():
-< """Returns the layout proxies on the active session.
-< Layout proxies are used to place views in a grid."""
-< return servermanager.ProxyManager().GetProxiesInGroup("layouts")
-<
-< def GetLayout(view=None):
-< """Return the layout containing the give view, if any.
-< If no view is specified, active view is used.
-< """
-< if not view:
-< view = GetActiveView()
-< if not view:
-< raise RuntimeError, "No active view was found."
-< layouts = GetLayouts()
-< for layout in layouts.values():
-< if layout.GetViewLocation(view) != -1:
-< return layout
-< return None
-966c897
-< def __get_selection_model(self, name, session=None):
----
-> def __get_selection_model(self, name):
-968,970c899
-< if session and session != servermanager.ActiveConnection.Session:
-< raise RuntimeError, "Try to set an active object with invalid active connection."
-< pxm = servermanager.ProxyManager(session)
----
-> pxm = servermanager.ProxyManager()
-979c908
-< active_view_model = self.__get_selection_model("ActiveView")
----
-> active_view_model = self.__get_selection_model("ActiveView")
-981d909
-< active_view_model = self.__get_selection_model("ActiveView", view.GetSession())
-984d911
-< active_view_model = self.__get_selection_model("ActiveView")
-994c921
-< active_sources_model = self.__get_selection_model("ActiveSources")
----
-> active_sources_model = self.__get_selection_model("ActiveSources")
-997d923
-< active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession())
-1000d925
-< active_sources_model = self.__get_selection_model("ActiveSources")
-1107a1033,1041
-> def PrintTrace():
-> print paravisSM.myParavis.GetTrace()
->
-> def SaveTrace(fileName):
-> paravisSM.myParavis.SaveTrace(fileName)
->
->
-> _add_functions(globals())
->
-1110,1111d1043
-< else:
-< _add_functions(globals())
-1113c1045,1046
-< active_objects = ActiveObjects()
----
-> def ImportFile(theFileName):
-> paravisSM.ImportFile(theFileName)
-1115,1129c1048,1049
-< def _switchToActiveConnectionCallback(caller, event):
-< if servermanager:
-< session = servermanager.vtkSMProxyManager.GetProxyManager().GetActiveSession()
-< if session and ((not servermanager.ActiveConnection) or session != servermanager.ActiveConnection.Session):
-< switchActiveConnection(servermanager.GetConnectionFromSession(session))
-<
-< class ActiveSessionObserver:
-< def __init__(self):
-< self.ObserverTag = servermanager.vtkSMProxyManager.GetProxyManager().AddObserver(9753, _switchToActiveConnectionCallback)
-<
-< def __del__(self):
-< if servermanager:
-< servermanager.vtkSMProxyManager.GetProxyManager().RemoveObserver(self.ObserverTag)
-<
-< active_session_observer = ActiveSessionObserver()
----
-> active_objects = ActiveObjects()
-> active_objects.view = GetRenderView()