[Paraview] Paraview State Saving script

Robert Maynard RobertJMaynard at gmail.com
Tue Aug 28 11:12:06 EDT 2007


I have built a python state saving script for paraview. The reason for the
script was that while the current paraview lookmark feature allows the user
to apply large pipelines onto different data sets, there is no easy way to
switch between different custom views.

By this I mean where the camera is, or what multiple objects are colored by,
or a threshold values. With this script you can build a view you want, than
store it. For example say you want to save a view that is looking from x+,
coloring on z elevation. Than later you can load
this view back, and that will cause all the objects to revert to the
properties you had when you save the state, in this case your camera would
return to x+ and the coloring would revert to z elevation.

If you have any questions please feel free to email me.

#Source Code Follows

#!/usr/bin/env python
#Created by Robert Maynard, 2007
#MIRARCO - Mining Innovation
#use at your own risk

import paraview
import cPickle as pickle

class State:
  '''Allows the user to save states, which is all the display properties for
each Pipeline object and camera. After saving
  states you can than load them back up, reverting all the object and camera
properties to what they where
  on saving. The set of views can also be saved to a file by using pickle so
that you can build up multiple viewStates
  and than display them at a latter time

  Currently Supports:
    saving a state by calling
      addView(statename) statename can be numeric / string

    Loading a state:
      loadView(statename) will load the respective state. If nothing changes
      click on the render window of paraview, that should fix the render
display.

    Pickle Saving all States:
      saveState(filepath+filename) will pickle all the states so that you
can load them up at a different time

      loadState(filepath+filename) will unpickle all the states so that you
can run previously generated states

    Bug:
      Currently items added after a view is stored are not turned off/on
when loading view that do not effect
      that item. This may or may not be helpfull to you


  '''
  def __init__(self):
    #storage for a list of view objects
    self.view = list()
    self.proxies  = {1:'displays',2:'sources', 3:'view_modules'}

  def loadState(self,file):
    '''loads a pickle view file, the passed in value needs
    to be a string that is the path to the pickled view'''
    #loads a State file
    try:
      #open an ascii pickle file
      self.view = pickle.load(open(file))
    except IOError:
      print "file not found"

  def saveState(self,file):
    '''save the current view collection as a ascii pickle'''
    pickle.dump(self.view,open(file,'w'))

  def deleteView(self,name):
    '''deletes the first occurance of a name from the view list'''
    for item in self.view:
      if (item.name == name):
        del item
        return True
    return False

  def renameView(self,oldName, newName):
    '''rename a view with a new name'''
    for item in self.view:
      if (item.name == oldName):
        item.name = newName
        return True
    return False

  def containsView(self,name):
    '''checks to see if a view with the name already exists'''
    return (name in self.view)

  def listViews(self):
    '''lists all the views sorted by name'''
    viewNames = list()
    for item in self.view:
      viewNames.append(item.name)
    #collect all the views and than sort them
    viewNames.sort()
    #display all the names
    for name in viewNames:
      print name
  def loadView(self,name):
    '''loads a select view that has already be saved.
       ex: state.loadView(1)'''
    for v in self.view:
      if (v.name == name):
        self.__load(v.proxy, v.items)

  def addView(self,name):
    '''adds the current state of all items in paraview + cameras as a view.
    loading this view will restore all the saved items to the current state
    ex: state.addView(1)'''
    for key in self.proxies.keys():
      newView = view(name, key, self.__getProperties(key))
      self.view.append(newView)


  def __load(self, proxyKey, items):
    #load the current view object
    proxy = paraview.pyProxyManager().GetProxiesInGroup(self.proxies[proxyKey])


    #reconstruct all the properties.
    if (self.proxies[proxyKey] == 'display'):
      sources = self.__buildSourceNames(proxy)
      for sourceName,disp in zip(sources,proxy):
        for i in items:
          if (i[0] == sourceName):
            self.__reconstructDisplay(proxy, disp,
i[1])
            break
    else:
      for name in proxy:
        for i in items:
          if (i[0] == name):
            self.__reconstructDisplay(proxy, name, i[1])
            if (self.proxies[proxyKey] == 'view_modules'):
              proxy[name].StillRender()
            break

  def __reconstructDisplay(self,proxy, name, propertyList):
    #sets all the properties back to their stored values, by
    #using eval. Hopefully a safer way is found to do this
    for items in propertyList:
      property = items[0]
      value = items[1]
      if (len(value) == 1):
        eval('proxy[name].%s(value[0])' %('Set'+property))
      elif (len(value) == 2):
        eval('proxy[name].%s(value[0],value[1])' %('Set'+property))
      elif (len(value) == 3):
        eval('proxy[name].%s(value[0],value[1],value[2])'
%('Set'+property))
    proxy[name].UpdateVTKObjects()

  def __getProperties(self, proxyKey):
    #get all the data needed in a view here
    proxy = paraview.pyProxyManager().GetProxiesInGroup(self.proxies[proxyKey])

    totalProperties = list()
    if (self.proxies[proxyKey] == 'display'):
      #build a list of source names that correspond to the display objects
      #so that load order wont effect display assocation
      sourceNames = self.__buildSourceNames(proxy)
      #get all the properties from each display object
      for name,item in zip(sourceNames,proxy):
        totalProperties.append( (name ,self.__getPropertyValues(proxy,item))
)
    else:
      #using the stored name for everything else
      for name in proxy:
        totalProperties.append( (name ,self.__getPropertyValues(proxy,name))
)

    return totalProperties

  def __getPropertyValues(self,proxy, name):
    propertyList = proxy[name].ListProperties()
    properties = list()
    for property in propertyList:
        try:
          value = eval('proxy[name].%s()' %("Get"+property))
          float(value[0])
          properties.append( (property,value) )
        #there is a lot of properties we cant save, stuff that is references
to other paraview objects
        #and methods that need no paramaters, instead of making a list of
those, instead we just ignore
        #the errors and dont add them to the list of properties we will
store
        except IndexError:
          pass
        except TypeError:
          pass
        except ValueError:
          pass
        except AttributeError:
          pass
        except SyntaxError:
          pass
    return properties

  def __buildSourceNames(self, proxy):
    #builds all the source names for each display, by using the
    #dump tool procyLabel method
    sourceNames = list()
    for key in proxy.keys():
      sourceNames.append(self.__proxyLabel(proxy[key].GetInput()[0]))
    return sourceNames

  def __proxyLabel( self, proxy ):
    """Returns the given proxy's PV displayed name. Much thanks from the
DumpTool for
    doing this great function"""
    proxyVTK = proxy.SMProxy
    pmanager = paraview.pyProxyManager()
    proxies =  paraview.pyProxyManager().GetProxiesOnConnection(
paraview.ActiveConnection)
    for group in proxies:
      idLabel = pmanager.IsProxyInGroup( proxyVTK, group )
      if idLabel:
          return idLabel
    return None

class view:
  #merely a storage container of view properties
  def __init__(self, name, proxy, items):
    self.proxy = proxy
    self.name = name
    self.items = items

  def __getstate__(self):
    #custom pickle data, so that all the items are stored on
pickling
    pickleDict = dict()
    pickleDict['proxy']=self.proxy
    pickleDict['items']=self.items
    pickleDict['name']=self.name
    return pickleDict

  def __setstate__(self,dict):
    #restore the items and view name when unpickling
    self.proxy = dict['proxy']
    self.items = dict['items']
    self.name = dict['name']
    self.__dict__.update(dict)   # update
attributes
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://public.kitware.com/pipermail/paraview/attachments/20070828/f2e272e8/attachment.html


More information about the ParaView mailing list