Back to index

salome-paravis  6.5.0
pvsimple.py
Go to the documentation of this file.
00001 # Copyright (C) 2010-2012  CEA/DEN, EDF R&D
00002 #
00003 # This library is free software; you can redistribute it and/or
00004 # modify it under the terms of the GNU Lesser General Public
00005 # License as published by the Free Software Foundation; either
00006 # version 2.1 of the License.
00007 #
00008 # This library is distributed in the hope that it will be useful,
00009 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00011 # Lesser General Public License for more details.
00012 #
00013 # You should have received a copy of the GNU Lesser General Public
00014 # License along with this library; if not, write to the Free Software
00015 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00016 #
00017 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00018 #
00019 
00020 r"""simple is a module for using paraview server manager in Python. It 
00021 provides a simple convenience layer to functionality provided by the
00022 C++ classes wrapped to Python as well as the servermanager module.
00023 
00024 A simple example:
00025   from paraview.simple import *
00026 
00027   # Create a new sphere proxy on the active connection and register it
00028   # in the sources group.
00029   sphere = Sphere(ThetaResolution=16, PhiResolution=32)
00030 
00031   # Apply a shrink filter
00032   shrink = Shrink(sphere)
00033   
00034   # Turn the visiblity of the shrink object on.
00035   Show(shrink)
00036   
00037   # Render the scene
00038   Render()
00039 """
00040 
00041 import paravisSM
00042 
00043 servermanager = paravisSM
00044 
00045 def _disconnect():
00046     if servermanager.ActiveConnection:
00047         servermanager.ProxyManager().UnRegisterProxies()
00048         active_objects.view = None
00049         active_objects.source = None
00050         import gc
00051         gc.collect()
00052         servermanager.Disconnect()
00053 
00054 def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
00055     """Creates a connection to a server. Example usage:
00056     > Connect("amber") # Connect to a single server at default port
00057     > Connect("amber", 12345) # Connect to a single server at port 12345
00058     > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair"""
00059     _disconnect()
00060     session = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
00061     _add_functions(globals())
00062 
00063     tk =  servermanager.misc.TimeKeeper()
00064     servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", tk)
00065     scene = AnimationScene()
00066     scene.TimeKeeper = tk
00067     return session
00068 
00069 def ReverseConnect(port=11111):
00070     """Create a reverse connection to a server.  Listens on port and waits for
00071     an incoming connection from the server."""
00072     _disconnect()
00073     session = servermanager.ReverseConnect(port)
00074     _add_functions(globals())
00075     tk =  servermanager.misc.TimeKeeper()
00076     servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", tk)
00077     scene = AnimationScene()
00078     scene.TimeKeeper = tk
00079     return session
00080 
00081 def _create_view(view_xml_name):
00082     "Creates and returns a 3D render view."
00083     view = servermanager._create_view(view_xml_name)
00084     servermanager.ProxyManager().RegisterProxy("views", \
00085       "my_view%d" % _funcs_internals.view_counter, view)
00086     active_objects.view = view
00087     _funcs_internals.view_counter += 1
00088     
00089     tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
00090     views = tk.Views
00091     if not view in views:
00092         views.append(view)
00093     try:
00094         scene = GetAnimationScene()
00095         if not view in scene.ViewModules:
00096             scene.ViewModules.append(view)
00097     except servermanager.MissingProxy:
00098         pass
00099     return view
00100 
00101 def CreateRenderView():
00102     return _create_view("RenderView")
00103 
00104 def CreateXYPlotView():
00105     return _create_view("XYChartView")
00106 
00107 def CreateBarChartView():
00108     return _create_view("XYBarChartView")
00109 
00110 def CreateComparativeRenderView():
00111     return _create_view("ComparativeRenderView")
00112 
00113 def CreateComparativeXYPlotView():
00114     return _create_view("ComparativeXYPlotView")
00115  
00116 def CreateComparativeBarChartView():
00117     return _create_view("ComparativeBarChartView")
00118 
00119 def CreateParallelCoordinatesChartView():
00120     return _create_view("ParallelCoordinatesChartView")
00121 
00122 def Create2DRenderView():
00123     return _create_view("2DRenderView")
00124 
00125 def OpenDataFile(filename, **extraArgs):
00126     """Creates a reader to read the give file, if possible.
00127        This uses extension matching to determine the best reader possible.
00128        If a reader cannot be identified, then this returns None."""
00129     reader_factor = servermanager.ProxyManager().GetReaderFactory()
00130     if  reader_factor.GetNumberOfRegisteredPrototypes() == 0:
00131       reader_factor.RegisterPrototypes("sources")
00132     session = servermanager.ActiveConnection.Session
00133     first_file = filename
00134     if type(filename) == list:
00135         first_file = filename[0]
00136     if not reader_factor.TestFileReadability(first_file, session):
00137         raise RuntimeError, "File not readable: %s " % first_file
00138     if not reader_factor.CanReadFile(first_file, session):
00139         raise RuntimeError, "File not readable. No reader found for '%s' " % first_file
00140     prototype = servermanager.ProxyManager().GetPrototypeProxy(
00141       reader_factor.GetReaderGroup(), reader_factor.GetReaderName())
00142     xml_name = paraview.make_name_valid(prototype.GetXMLLabel())
00143     reader_func = _create_func(xml_name, servermanager.sources)
00144     if prototype.GetProperty("FileNames"):
00145       reader = reader_func(FileNames=filename, **extraArgs)
00146     else :
00147       reader = reader_func(FileName=filename, **extraArgs)
00148     return reader
00149 
00150 def CreateWriter(filename, proxy=None, **extraArgs):
00151     """Creates a writer that can write the data produced by the source proxy in
00152        the given file format (identified by the extension). If no source is
00153        provided, then the active source is used. This doesn't actually write the
00154        data, it simply creates the writer and returns it."""
00155     if not filename:
00156        raise RuntimeError, "filename must be specified"
00157     writer_factory = servermanager.ProxyManager().GetWriterFactory()
00158     if writer_factory.GetNumberOfRegisteredPrototypes() == 0:
00159         writer_factory.RegisterPrototypes("writers")
00160     if not proxy:
00161         proxy = GetActiveSource()
00162     if not proxy:
00163         raise RuntimeError, "Could not locate source to write"
00164     writer_proxy = writer_factory.CreateWriter(filename, proxy.SMProxy, proxy.Port)
00165     return servermanager._getPyProxy(writer_proxy)
00166 
00167 def GetRenderView():
00168     """Returns the active view if there is one. Else creates and returns a new view."""
00169     view = active_objects.view
00170     if not view:
00171         # it's possible that there's no active view, but a render view exists.
00172         # If so, locate that and return it (before trying to create a new one).
00173         view = servermanager.GetRenderView()
00174     if not view:
00175         view = CreateRenderView()
00176     return view
00177 
00178 def GetRenderViews():
00179     """Returns all render views as a list."""
00180     return servermanager.GetRenderViews()
00181 
00182 def GetRepresentation(proxy=None, view=None):
00183     """Given a pipeline object and view, returns the corresponding representation object.
00184     If pipeline object and view are not specified, active objects are used."""
00185     if not view:
00186         view = active_objects.view
00187     if not proxy:
00188         proxy = active_objects.source
00189     rep = servermanager.GetRepresentation(proxy, view)
00190     if not rep:
00191         rep = servermanager.CreateRepresentation(proxy, view)
00192         servermanager.ProxyManager().RegisterProxy("representations", \
00193           "my_representation%d" % _funcs_internals.rep_counter, rep)
00194         _funcs_internals.rep_counter += 1
00195     return rep
00196     
00197 def GetDisplayProperties(proxy=None, view=None):
00198     """Given a pipeline object and view, returns the corresponding representation object.
00199     If pipeline object and/or view are not specified, active objects are used."""
00200     return GetRepresentation(proxy, view)
00201     
00202 def Show(proxy=None, view=None, **params):
00203     """Turns the visibility of a given pipeline object on in the given view.
00204     If pipeline object and/or view are not specified, active objects are used."""
00205     if proxy == None:
00206         proxy = GetActiveSource()
00207     if proxy == None:
00208         raise RuntimeError, "Show() needs a proxy argument or that an active source is set."
00209     if not view and not active_objects.view:
00210         CreateRenderView()
00211     rep = GetDisplayProperties(proxy, view)
00212     if rep == None:
00213         raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel()
00214     for param in params.keys():
00215         setattr(rep, param, params[param])
00216     rep.Visibility = 1
00217     return rep
00218 
00219 def Hide(proxy=None, view=None):
00220     """Turns the visibility of a given pipeline object off in the given view.
00221     If pipeline object and/or view are not specified, active objects are used."""
00222     rep = GetDisplayProperties(proxy, view)
00223     rep.Visibility = 0
00224 
00225 def Render(view=None):
00226     """Renders the given view (default value is active view)"""
00227     if not view:
00228         view = active_objects.view
00229     view.StillRender()
00230     if _funcs_internals.first_render:
00231         # Not all views have a ResetCamera method
00232         try:
00233             view.ResetCamera()
00234             view.StillRender()
00235         except AttributeError: pass
00236         _funcs_internals.first_render = False
00237     return view
00238         
00239 def ResetCamera(view=None):
00240     """Resets the settings of the camera to preserver orientation but include
00241     the whole scene. If an argument is not provided, the active view is
00242     used."""
00243     if not view:
00244         view = active_objects.view
00245     if hasattr(view, "ResetCamera"):
00246         view.ResetCamera()
00247     if hasattr(view, "ResetDisplay"):
00248         view.ResetDisplay()
00249     Render(view)
00250 
00251 def _DisableFirstRenderCameraReset():
00252     """Disable the first render camera reset.  Normally a ResetCamera is called
00253     automatically when Render is called for the first time after importing
00254     this module."""
00255     _funcs_internals.first_render = False
00256 
00257 def SetProperties(proxy=None, **params):
00258     """Sets one or more properties of the given pipeline object. If an argument
00259     is not provided, the active source is used. Pass a list of property_name=value
00260     pairs to this function to set property values. For example:
00261      SetProperties(Center=[1, 2, 3], Radius=3.5)
00262     """
00263     if not proxy:
00264         proxy = active_objects.source
00265     for param in params.keys():
00266         if not hasattr(proxy, param):
00267             raise AttributeError("object has no property %s" % param)
00268         setattr(proxy, param, params[param])
00269 
00270 def GetProperty(*arguments, **keywords):
00271     """Get one property of the given pipeline object. If keywords are used,
00272        you can set the proxy and the name of the property that you want to get
00273        like in the following example :
00274             GetProperty({proxy=sphere, name="Radius"})
00275        If it's arguments that are used, then you have two case:
00276          - if only one argument is used that argument will be
00277            the property name.
00278          - if two arguments are used then the first one will be
00279            the proxy and the second one the property name.
00280        Several example are given below:
00281            GetProperty({name="Radius"})
00282            GetProperty({proxy=sphereProxy, name="Radius"})
00283            GetProperty( sphereProxy, "Radius" )
00284            GetProperty( "Radius" )
00285     """
00286     name = None
00287     proxy = None
00288     for key in keywords:
00289         if key == "name":
00290             name = keywords[key]
00291         if key == "proxy":
00292             proxy = keywords[key]
00293     if len(arguments) == 1 :
00294         name = arguments[0]
00295     if len(arguments) == 2 :
00296         proxy = arguments[0]
00297         name  = arguments[1]
00298     if not name:
00299         raise RuntimeError, "Expecting at least a property name as input. Otherwise keyword could be used to set 'proxy' and property 'name'"
00300     if not proxy:
00301         proxy = active_objects.source
00302     return proxy.GetProperty(name)
00303 
00304 def SetDisplayProperties(proxy=None, view=None, **params):
00305     """Sets one or more display properties of the given pipeline object. If an argument
00306     is not provided, the active source is used. Pass a list of property_name=value
00307     pairs to this function to set property values. For example:
00308      SetProperties(Color=[1, 0, 0], LineWidth=2)
00309     """
00310     rep = GetDisplayProperties(proxy, view)
00311     SetProperties(rep, **params)
00312 
00313 def SetViewProperties(view=None, **params):
00314     """Sets one or more properties of the given view. If an argument
00315     is not provided, the active view is used. Pass a list of property_name=value
00316     pairs to this function to set property values. For example:
00317      SetProperties(Background=[1, 0, 0], UseImmediateMode=0)
00318     """
00319     if not view:
00320         view = active_objects.view
00321     SetProperties(view, **params)
00322 
00323 def RenameSource(newName, proxy=None):
00324     """Renames the given source.  If the given proxy is not registered
00325     in the sources group this method will have no effect.  If no source is
00326     provided, the active source is used."""
00327     if not proxy:
00328         proxy = active_objects.source
00329     pxm = servermanager.ProxyManager()
00330     oldName = pxm.GetProxyName("sources", proxy)
00331     if oldName:
00332       pxm.RegisterProxy("sources", newName, proxy)
00333       pxm.UnRegisterProxy("sources", oldName, proxy)
00334 
00335 def FindSource(name):
00336     return servermanager.ProxyManager().GetProxy("sources", name)
00337 
00338 def GetSources():
00339     """Given the name of a source, return its Python object."""
00340     return servermanager.ProxyManager().GetProxiesInGroup("sources")
00341 
00342 def GetRepresentations():
00343     """Returns all representations (display properties)."""
00344     return servermanager.ProxyManager().GetProxiesInGroup("representations")
00345 
00346 def UpdatePipeline(time=None, proxy=None):
00347     """Updates (executes) the given pipeline object for the given time as
00348     necessary (i.e. if it did not already execute). If no source is provided,
00349     the active source is used instead."""
00350     if not proxy:
00351         proxy = active_objects.source
00352     if time:
00353         proxy.UpdatePipeline(time)
00354     else:
00355         proxy.UpdatePipeline()
00356 
00357 def Delete(proxy=None):
00358     """Deletes the given pipeline object or the active source if no argument
00359     is specified."""
00360     if not proxy:
00361         proxy = active_objects.source
00362     # Unregister any helper proxies stored by a vtkSMProxyListDomain
00363     for prop in proxy:
00364         listdomain = prop.GetDomain('proxy_list')
00365         if listdomain:
00366             if listdomain.GetClassName() != 'vtkSMProxyListDomain':
00367                 continue
00368             group = "pq_helper_proxies." + proxy.GetGlobalIDAsString()
00369             for i in xrange(listdomain.GetNumberOfProxies()):
00370                 pm = servermanager.ProxyManager()
00371                 iproxy = listdomain.GetProxy(i)
00372                 name = pm.GetProxyName(group, iproxy)
00373                 if iproxy and name:
00374                     pm.UnRegisterProxy(group, name, iproxy)
00375                     
00376     # Remove source/view from time keeper
00377     tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
00378     if isinstance(proxy, servermanager.SourceProxy):
00379         try:
00380             idx = tk.TimeSources.index(proxy)
00381             del tk.TimeSources[idx]
00382         except ValueError:
00383             pass
00384     else:
00385         try:
00386             idx = tk.Views.index(proxy)
00387             del tk.Views[idx]
00388         except ValueError:
00389             pass
00390     servermanager.UnRegister(proxy)
00391     
00392     # If this is a representation, remove it from all views.
00393     if proxy.SMProxy.IsA("vtkSMRepresentationProxy") or \
00394         proxy.SMProxy.IsA("vtkSMNewWidgetRepresentationProxy"):
00395         for view in GetRenderViews():
00396             view.Representations.remove(proxy)
00397     # If this is a source, remove the representation iff it has no consumers
00398     # Also change the active source if necessary
00399     elif proxy.SMProxy.IsA("vtkSMSourceProxy"):
00400         sources = servermanager.ProxyManager().GetProxiesInGroup("sources")
00401         for i in range(proxy.GetNumberOfConsumers()):
00402             if proxy.GetConsumerProxy(i) in sources:
00403                 raise RuntimeError("Source has consumers. It cannot be deleted " +
00404                   "until all consumers are deleted.")
00405         #VSV:==
00406         if proxy.IsSame(GetActiveSource()):
00407             if hasattr(proxy, "Input") and proxy.Input:
00408                 if isinstance(proxy.Input, servermanager.Proxy):
00409                     SetActiveSource(proxy.Input)
00410                 else:
00411                     SetActiveSource(proxy.Input[0])
00412             else: SetActiveSource(None)
00413         for rep in GetRepresentations().values():
00414             #VSV:==
00415             if rep.Input.IsSame(proxy):
00416                 Delete(rep)
00417     # Change the active view if necessary
00418     elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"):
00419         ##VSV:==
00420         if proxy.IsSame(GetActiveView()):
00421             if len(GetRenderViews()) > 0:
00422                 SetActiveView(GetRenderViews()[0])
00423             else:
00424                 SetActiveView(None)
00425 
00426 def CreateLookupTable(**params):
00427     """Create and return a lookup table.  Optionally, parameters can be given
00428     to assign to the lookup table.
00429     """
00430     lt = servermanager.rendering.PVLookupTable()
00431     servermanager.Register(lt)
00432     SetProperties(lt, **params)
00433     return lt
00434 
00435 def CreatePiecewiseFunction(**params):
00436     """Create and return a piecewise function.  Optionally, parameters can be
00437     given to assign to the piecewise function.
00438     """
00439     pfunc = servermanager.piecewise_functions.PiecewiseFunction()
00440     servermanager.Register(pfunc)
00441     SetProperties(pfunc, **params)
00442     return pfunc
00443 
00444 def GetLookupTableForArray(arrayname, num_components, **params):
00445     """Used to get an existing lookuptable for a array or to create one if none
00446     exists. Keyword arguments can be passed in to initialize the LUT if a new
00447     one is created."""
00448     proxyName = "%d.%s.PVLookupTable" % (int(num_components), arrayname)
00449     lut = servermanager.ProxyManager().GetProxy("lookup_tables", proxyName)
00450     if lut:
00451         return lut
00452     # No LUT exists for this array, create a new one.
00453     # TODO: Change this to go a LookupTableManager that is shared with the GUI,
00454     # so that the GUI and python end up create same type of LUTs. For now,
00455     # python will create a Blue-Red LUT, unless overridden by params.
00456     lut = servermanager.rendering.PVLookupTable(
00457             ColorSpace="HSV", RGBPoints=[0, 0, 0, 1, 1, 1, 0, 0])
00458     SetProperties(lut, **params)
00459     servermanager.Register(lut, registrationName=proxyName)
00460     return lut
00461 
00462 def CreateScalarBar(**params):
00463     """Create and return a scalar bar widget.  The returned widget may
00464     be added to a render view by appending it to the view's representations
00465     The widget must have a valid lookup table before it is added to a view.
00466     It is possible to pass the lookup table (and other properties) as arguments
00467     to this method:
00468     
00469     lt = MakeBlueToRedLt(3.5, 7.5)
00470     bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
00471     GetRenderView().Representations.append(bar)
00472     
00473     By default the returned widget is selectable and resizable.
00474     """
00475     sb = servermanager.rendering.ScalarBarWidgetRepresentation()
00476     servermanager.Register(sb)
00477     sb.Selectable = 1
00478     sb.Resizable = 1
00479     sb.Enabled = 1
00480     sb.Title = "Scalars"
00481     SetProperties(sb, **params)
00482     return sb
00483 
00484 # TODO: Change this to take the array name and number of components. Register 
00485 # the lt under the name ncomp.array_name
00486 def MakeBlueToRedLT(min, max):
00487     # Define RGB points. These are tuples of 4 values. First one is
00488     # the scalar values, the other 3 the RGB values. 
00489     rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
00490     return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
00491     
00492 def _find_writer(filename):
00493     """Internal function."""
00494     extension = None
00495     parts = filename.split('.')
00496     if len(parts) > 1:
00497         extension = parts[-1]
00498     else:
00499         raise RuntimeError, "Filename has no extension, please specify a write"
00500         
00501     if extension == 'png':
00502         return 'vtkPNGWriter'
00503     elif extension == 'bmp':
00504         return 'vtkBMPWriter'
00505     elif extension == 'ppm':
00506         return 'vtkPNMWriter'
00507     elif extension == 'tif' or extension == 'tiff':
00508         return 'vtkTIFFWriter'
00509     elif extension == 'jpg' or extension == 'jpeg':
00510         return 'vtkJPEGWriter'
00511     else:
00512         raise RuntimeError, "Cannot infer filetype from extension:", extension
00513 
00514 def AddCameraLink(viewProxy, viewProxyOther, linkName):
00515     """Create a camera link between two view proxies.  A name must be given
00516     so that the link can be referred to by name.  If a link with the given
00517     name already exists it will be removed first."""
00518     if not viewProxyOther: viewProxyOther = GetActiveView()
00519     link = servermanager.vtkSMCameraLink()
00520     link.AddLinkedProxy(viewProxy.SMProxy, 1)
00521     link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
00522     link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
00523     link.AddLinkedProxy(viewProxy.SMProxy, 2)
00524     RemoveCameraLink(linkName)
00525     servermanager.ProxyManager().RegisterLink(linkName, link)
00526 
00527 def RemoveCameraLink(linkName):
00528     """Remove a camera link with the given name."""
00529     servermanager.ProxyManager().UnRegisterLink(linkName)
00530 
00531 def WriteImage(filename, view=None, **params):
00532     """Saves the given view (or the active one if none is given) as an
00533     image. Optionally, you can specify the writer and the magnification
00534     using the Writer and Magnification named arguments. For example:
00535      WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)
00536     If no writer is provided, the type is determined from the file extension.
00537     Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
00538     The writer is a VTK class that is capable of writing images.
00539     Magnification is used to determine the size of the written image. The size
00540     is obtained by multiplying the size of the view with the magnification.
00541     Rendering may be done using tiling to obtain the correct size without
00542     resizing the view."""
00543     if not view:
00544         view = active_objects.view
00545     writer = None
00546     if params.has_key('Writer'):
00547         writer = params['Writer']
00548     mag = 1
00549     if params.has_key('Magnification'):
00550         mag = int(params['Magnification'])
00551     if not writer:
00552         writer = _find_writer(filename)
00553     view.WriteImage(filename, writer, mag)
00554 
00555 def AnimateReader(reader=None, view=None, filename=None):
00556     """This is a utility function that, given a reader and a view
00557     animates over all time steps of the reader. If the optional
00558     filename is provided, a movie is created (type depends on the
00559     extension of the filename."""
00560     if not reader:
00561         reader = active_objects.source
00562     if not view:
00563         view = active_objects.view
00564         
00565     return servermanager.AnimateReader(reader, view, filename)
00566 
00567 
00568 def _create_func(key, module):
00569     """Internal function."""
00570 
00571     def CreateObject(*input, **params):
00572         """This function creates a new proxy. For pipeline objects that accept inputs,
00573         all non-keyword arguments are assumed to be inputs. All keyword arguments are
00574         assumed to be property,value pairs and are passed to the new proxy."""
00575 
00576         # Instantiate the actual object from the given module.
00577         px = module.__dict__[key]()
00578 
00579         # Make sure non-keyword arguments are valid
00580         for inp in input:
00581             if inp != None and not isinstance(inp, servermanager.Proxy):
00582                 if px.GetProperty("Input") != None:
00583                     raise RuntimeError, "Expecting a proxy as input."
00584                 else:
00585                     raise RuntimeError, "This function does not accept non-keyword arguments."
00586 
00587         # Assign inputs
00588         if px.GetProperty("Input") != None:
00589             if len(input) > 0:
00590                 px.Input = input
00591             else:
00592                 # If no input is specified, try the active pipeline object
00593                 if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
00594                     px.Input = active_objects.get_selected_sources()
00595                 elif active_objects.source:
00596                     px.Input = active_objects.source
00597         else:
00598             if len(input) > 0:
00599                 raise RuntimeError, "This function does not expect an input."
00600 
00601         registrationName = None
00602         for nameParam in ['registrationName', 'guiName']:
00603           if nameParam in params:
00604               registrationName = params[nameParam]
00605               del params[nameParam]
00606 
00607         # Pass all the named arguments as property,value pairs
00608         for param in params.keys():
00609             setattr(px, param, params[param])
00610 
00611         try:
00612             # Register the proxy with the proxy manager.
00613             if registrationName:
00614                 group, name = servermanager.Register(px, registrationName=registrationName)
00615             else:
00616                 group, name = servermanager.Register(px)
00617 
00618 
00619             # Register pipeline objects with the time keeper. This is used to extract time values
00620             # from sources. NOTE: This should really be in the servermanager controller layer.
00621             if group == "sources":
00622                 tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
00623                 sources = tk.TimeSources
00624                 if not px in sources:
00625                     sources.append(px)
00626 
00627                 active_objects.source = px
00628         except servermanager.MissingRegistrationInformation:
00629             pass
00630 
00631         return px
00632 
00633     return CreateObject
00634 
00635 def _create_doc(new, old):
00636     """Internal function."""
00637     import string
00638     res = ""
00639     for doc in (new, old):
00640         ts = []
00641         strpd = doc.split('\n')
00642         for s in strpd:
00643             ts.append(s.lstrip())
00644         res += string.join(ts)
00645         res += '\n'
00646     return res
00647     
00648 def _func_name_valid(name):
00649     """Internal function."""
00650     valid = True
00651     for c in name:
00652         if c == '(' or c ==')':
00653             valid = False
00654             break
00655     return valid
00656 
00657 def _add_functions(g):
00658     for m in [servermanager.filters, servermanager.sources,
00659               servermanager.writers, servermanager.animation]:
00660         dt = m.__dict__
00661         for key in dt.keys():
00662             cl = dt[key]
00663             if not isinstance(cl, str):
00664                 if not key in g and _func_name_valid(key):
00665                     g[key] = _create_func(key, m)
00666                     exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key
00667 
00668 def GetActiveView():
00669     """Returns the active view."""
00670     return active_objects.view
00671     
00672 def SetActiveView(view):
00673     """Sets the active view."""
00674     active_objects.view = view
00675     
00676 def GetActiveSource():
00677     """Returns the active source."""
00678     return active_objects.source
00679     
00680 def SetActiveSource(source):
00681     """Sets the active source."""
00682     active_objects.source = source
00683     
00684 def GetActiveCamera():
00685     """Returns the active camera for the active view. The returned object
00686     is an instance of vtkCamera."""
00687     return GetActiveView().GetActiveCamera()
00688 
00689 def GetAnimationScene():
00690     """Returns the application-wide animation scene. ParaView has only one
00691     global animation scene. This method provides access to that. Users are
00692     free to create additional animation scenes directly, but those scenes
00693     won't be shown in the ParaView GUI."""
00694     animation_proxies = servermanager.ProxyManager().GetProxiesInGroup("animation")
00695     scene = None
00696     for aProxy in animation_proxies.values():
00697         if aProxy.GetXMLName() == "AnimationScene":
00698             scene = aProxy
00699             break
00700     if not scene:
00701         raise servermanager.MissingProxy, "Could not locate global AnimationScene."
00702     return scene
00703 
00704 def WriteAnimation(filename, **params):
00705     """Writes the current animation as a file. Optionally one can specify
00706     arguments that qualify the saved animation files as keyword arguments.
00707     Accepted options are as follows:
00708     * Magnification (integer) : set the maginification factor for the saved
00709       animation.
00710     * Quality (0 [worst] or 1 or 2 [best]) : set the quality of the generated
00711       movie (if applicable).
00712     * Subsampling (integer) : setting whether the movie encoder should use
00713       subsampling of the chrome planes or not, if applicable. Since the human
00714       eye is more sensitive to brightness than color variations, subsampling
00715       can be useful to reduce the bitrate. Default value is 0.
00716     * BackgroundColor (3-tuple of doubles) : set the RGB background color to
00717       use to fill empty spaces in the image.
00718     * FrameRate (double): set the frame rate (if applicable)."""
00719     scene = GetAnimationScene()
00720     # ensures that the TimeKeeper track is created.
00721     GetTimeTrack()
00722     iw = servermanager.vtkSMAnimationSceneImageWriter()
00723     iw.SetAnimationScene(scene.SMProxy)
00724     iw.SetFileName(filename)
00725     if params.has_key("Magnification"):
00726         iw.SetMagnification(int(params["Magnification"]))
00727     if params.has_key("Quality"):
00728         iw.SetQuality(int(params["Quality"]))
00729     if params.has_key("Subsampling"):
00730         iw.SetSubsampling(int(params["Subsampling"]))
00731     if params.has_key("BackgroundColor"):
00732         iw.SetBackgroundColor(params["BackgroundColor"])
00733     if params.has_key("FrameRate"):
00734         iw.SetFrameRate(float(params["FrameRate"]))
00735     iw.Save()
00736 
00737 def _GetRepresentationAnimationHelper(sourceproxy):
00738     """Internal method that returns the representation animation helper for a
00739        source proxy. It creates a new one if none exists."""
00740     # ascertain that proxy is a source proxy
00741     if not sourceproxy in GetSources().values():
00742         return None
00743     for proxy in servermanager.ProxyManager():
00744         if proxy.GetXMLName() == "RepresentationAnimationHelper" and\
00745            proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy):
00746              return proxy
00747     # create a new helper
00748     proxy = servermanager.misc.RepresentationAnimationHelper(
00749       Source=sourceproxy)
00750     servermanager.ProxyManager().RegisterProxy(
00751       "pq_helper_proxies.%s" % sourceproxy.GetGlobalIDAsString(),
00752       "RepresentationAnimationHelper", proxy)
00753     return proxy
00754 
00755 def GetAnimationTrack(propertyname_or_property, index=None, proxy=None):
00756     """Returns an animation cue for the property. If one doesn't exist then a
00757     new one will be created.
00758     Typical usage:
00759         track = GetAnimationTrack("Center", 0, sphere) or
00760         track = GetAnimationTrack(sphere.GetProperty("Radius")) or
00761 
00762         # this returns the track to animate visibility of the active source in
00763         # all views.
00764         track = GetAnimationTrack("Visibility")
00765 
00766      For animating properties on implicit planes etc., use the following
00767      signatures:
00768         track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or
00769         track = GetAnimationTrack("Origin", 0, slice.SliceType)
00770 
00771     """
00772     if not proxy:
00773         proxy = GetActiveSource()
00774     if not isinstance(proxy, servermanager.Proxy):
00775         raise TypeError, "proxy must be a servermanager.Proxy instance"
00776     if isinstance(propertyname_or_property, str):
00777         propertyname = propertyname_or_property
00778     elif isinstance(propertyname_or_property, servermanager.Property):
00779         prop = propertyname_or_property
00780         propertyname = prop.Name
00781         proxy = prop.Proxy
00782     else:
00783         raise TypeError, "propertyname_or_property must be a string or servermanager.Property"
00784 
00785     # To handle the case where the property is actually a "display" property, in
00786     # which case we are actually animating the "RepresentationAnimationHelper"
00787     # associated with the source.
00788     if propertyname in ["Visibility", "Opacity"]:
00789         proxy = _GetRepresentationAnimationHelper(proxy)
00790     if not proxy or not proxy.GetProperty(propertyname):
00791         raise AttributeError, "Failed to locate property %s" % propertyname
00792 
00793     scene = GetAnimationScene()
00794     for cue in scene.Cues:
00795         try:
00796             if cue.AnimatedProxy.IsSame(proxy) and\
00797                cue.AnimatedPropertyName == propertyname:
00798                 if index == None or index.IsSame(cue.AnimatedElement): ##index == cue.AnimatedElement:
00799                     return cue
00800         except AttributeError:
00801             pass
00802 
00803     # matching animation track wasn't found, create a new one.
00804     cue = KeyFrameAnimationCue()
00805     cue.AnimatedProxy = proxy
00806     cue.AnimatedPropertyName = propertyname
00807     if index != None:
00808         cue.AnimatedElement = index
00809     scene.Cues.append(cue)
00810     return cue
00811 
00812 def GetCameraTrack(view=None):
00813     """Returns the camera animation track for the given view. If no view is
00814     specified, active view will be used. If no exisiting camera animation track
00815     is found, a new one will be created."""
00816     if not view:
00817         view = GetActiveView()
00818     if not view:
00819         raise ValueError, "No view specified"
00820     scene = GetAnimationScene()
00821     for cue in scene.Cues:
00822         if cue.AnimatedProxy.IsSame(view) and\
00823            cue.GetXMLName() == "CameraAnimationCue":
00824             return cue
00825     # no cue was found, create a new one.
00826     cue = CameraAnimationCue()
00827     cue.AnimatedProxy = view
00828     scene.Cues.append(cue)
00829     return cue
00830 
00831 def GetTimeTrack():
00832     """Returns the animation track used to control the time requested from all
00833     readers/filters during playback.
00834     This is the "TimeKeeper - Time" track shown in ParaView's 'Animation View'.
00835     If none exists, a new one will be created."""
00836     scene = GetAnimationScene()
00837     tk = scene.TimeKeeper
00838     for cue in scene.Cues:
00839         if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy.IsSame(tk)\
00840             and cue.AnimatedPropertyName == "Time":
00841             return cue
00842     # no cue was found, create a new one.
00843     cue = TimeAnimationCue()
00844     cue.AnimatedProxy = tk
00845     cue.AnimatedPropertyName = "Time"
00846     scene.Cues.append(cue)
00847     return cue
00848 
00849 def LoadXML(xmlstring, ns=None):
00850     """Given a server manager XML as a string, parse and process it.
00851     If you loaded the simple module with from paraview.simple import *,
00852     make sure to pass globals() as the second arguments:
00853     LoadXML(xmlstring, globals())
00854     Otherwise, the new functions will not appear in the global namespace."""
00855     if not ns:
00856         ns = globals()
00857     servermanager.LoadXML(xmlstring)
00858     _add_functions(ns)
00859 
00860 def LoadPlugin(filename, remote=True, ns=None):
00861     """Loads a ParaView plugin and updates this module with new constructors
00862     if any. The remote argument (default to True) is to specify whether 
00863     the plugin will be loaded on client (remote=False) or on server (remote=True).
00864     If you loaded the simple module with from paraview.simple import *,
00865     make sure to pass globals() as an argument:
00866     LoadPlugin("myplugin", False, globals()), to load on client;
00867     LoadPlugin("myplugin", True, globals()), to load on server; 
00868     LoadPlugin("myplugin", ns=globals()), to load on server.
00869     Otherwise, the new functions will not appear in the global namespace."""
00870     
00871     if not ns:
00872         ns = globals()
00873     servermanager.LoadPlugin(filename, remote)
00874     _add_functions(ns)
00875 
00876 def LoadDistributedPlugin(pluginname, remote=True, ns=None):
00877     """Loads a plugin that's distributed with the executable. This uses the
00878     information known about plugins distributed with ParaView to locate the
00879     shared library for the plugin to load. Raises a RuntimeError if the plugin
00880     was not found."""
00881     plm = servermanager.ProxyManager().GetSession().GetPluginManager()
00882     if remote:
00883         info = plm.GetRemoteInformation()
00884     else:
00885         info = plm.GetLocalInformation()
00886     for cc in range(0, info.GetNumberOfPlugins()):
00887         if info.GetPluginName(cc) == pluginname:
00888             return LoadPlugin(info.GetPluginFileName(cc), remote, ns)
00889     raise RuntimeError, "Plugin '%s' not found" % pluginname
00890 
00891 
00892 class ActiveObjects(object):
00893     """This class manages the active objects (source and view). The active
00894     objects are shared between Python and the user interface. This class
00895     is for internal use. Use the Set/Get methods for setting and getting
00896     active objects."""
00897     def __get_selection_model(self, name):
00898         "Internal method."
00899         pxm = servermanager.ProxyManager()
00900         model = pxm.GetSelectionModel(name)
00901         if not model:
00902             model = servermanager.vtkSMProxySelectionModel()
00903             pxm.RegisterSelectionModel(name, model)
00904         return model
00905 
00906     def set_view(self, view):
00907         "Sets the active view."
00908         active_view_model = self.__get_selection_model("ActiveView") 
00909         if view:
00910             active_view_model.SetCurrentProxy(view.SMProxy, 0)
00911         else:
00912             active_view_model.SetCurrentProxy(None, 0)
00913 
00914     def get_view(self):
00915         "Returns the active view."
00916         return servermanager._getPyProxy(
00917             self.__get_selection_model("ActiveView").GetCurrentProxy())
00918 
00919     def set_source(self, source):
00920         "Sets the active source."
00921         active_sources_model = self.__get_selection_model("ActiveSources") 
00922         if source:
00923             # 3 == CLEAR_AND_SELECT
00924             active_sources_model.SetCurrentProxy(source.SMProxy, 3)
00925         else:
00926             active_sources_model.SetCurrentProxy(None, 3)
00927 
00928     def __convert_proxy(self, px):
00929         "Internal method."
00930         if not px:
00931             return None
00932         if px.IsA("vtkSMSourceProxy"):
00933             return servermanager._getPyProxy(px)
00934         else:
00935             return servermanager.OutputPort(
00936               servermanager._getPyProxy(px.GetSourceProxy()),
00937               px.GetPortIndex())
00938         
00939     def get_source(self):
00940         "Returns the active source."
00941         return self.__convert_proxy(
00942           self.__get_selection_model("ActiveSources").GetCurrentProxy())
00943 
00944     def get_selected_sources(self):
00945         "Returns the set of sources selected in the pipeline browser."
00946         model = self.__get_selection_model("ActiveSources")
00947         proxies = []
00948         for i in xrange(model.GetNumberOfSelectedProxies()):
00949             proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
00950         return proxies
00951 
00952     view = property(get_view, set_view)
00953     source = property(get_source, set_source)
00954 
00955 class _funcs_internals:
00956     """Internal class."""
00957     first_render = True
00958     view_counter = 0
00959     rep_counter = 0
00960 
00961 def demo1():
00962     """Simple demo that create the following pipeline
00963     sphere - shrink - \
00964                        - append
00965     cone            - /
00966     """
00967     # Create a sphere of radius = 2, theta res. = 32
00968     # This object becomes the active source.
00969     ss = Sphere(Radius=2, ThetaResolution=32)
00970     # Apply the shrink filter. The Input property is optional. If Input
00971     # is not specified, the filter is applied to the active source.
00972     shr = Shrink(Input=ss)
00973     # Create a cone source.
00974     cs = Cone()
00975     # Append cone and shrink
00976     app = AppendDatasets()
00977     app.Input = [shr, cs]
00978     # Show the output of the append filter. The argument is optional
00979     # as the app filter is now the active object.
00980     Show(app)
00981     # Render the default view.
00982     Render()
00983 
00984 def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"):
00985     """This demo shows the use of readers, data information and display
00986     properties."""
00987     
00988     # Create the exodus reader and specify a file name
00989     reader = ExodusIIReader(FileName=fname)
00990     # Get the list of point arrays.
00991     avail = reader.PointVariables.Available
00992     print avail
00993     # Select all arrays
00994     reader.PointVariables = avail
00995 
00996     # Turn on the visibility of the reader
00997     Show(reader)
00998     # Set representation to wireframe
00999     SetDisplayProperties(Representation = "Wireframe")
01000     # Black background is not pretty
01001     SetViewProperties(Background = [0.4, 0.4, 0.6])
01002     Render()
01003     # Change the elevation of the camera. See VTK documentation of vtkCamera
01004     # for camera parameters.
01005     # NOTE: THIS WILL BE SIMPLER
01006     GetActiveCamera().Elevation(45)
01007     Render()
01008     # Now that the reader executed, let's get some information about it's
01009     # output.
01010     pdi = reader[0].PointData
01011     # This prints a list of all read point data arrays as well as their
01012     # value ranges.
01013     print 'Number of point arrays:', len(pdi)
01014     for i in range(len(pdi)):
01015         ai = pdi[i]
01016         print "----------------"
01017         print "Array:", i, " ", ai.Name, ":"
01018         numComps = ai.GetNumberOfComponents()
01019         print "Number of components:", numComps
01020         for j in range(numComps):
01021             print "Range:", ai.GetRange(j)
01022     # White is boring. Let's color the geometry using a variable.
01023     # First create a lookup table. This object controls how scalar
01024     # values are mapped to colors. See VTK documentation for
01025     # details.
01026     # Map min (0.00678) to blue, max (0.0288) to red
01027     SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
01028     # Color by point array called Pres
01029     SetDisplayProperties(ColorAttributeType = "POINT_DATA")
01030     SetDisplayProperties(ColorArrayName = "Pres")
01031     Render()
01032 
01033 def PrintTrace():
01034     print paravisSM.myParavis.GetTrace()
01035 
01036 def SaveTrace(fileName):
01037     paravisSM.myParavis.SaveTrace(fileName)
01038 
01039 
01040 _add_functions(globals())
01041 
01042 if not servermanager.ActiveConnection:
01043     Connect()
01044 
01045 def ImportFile(theFileName):
01046     paravisSM.ImportFile(theFileName)
01047 
01048 active_objects = ActiveObjects()
01049 active_objects.view = GetRenderView()