Exemple #1
0
    def test_pickle(self):
        """Test if pickler works correctly with FilePaths."""
        t = Test()
        t.f.set("t.vtk")
        cwd = os.getcwd()
        curdir = basename(cwd)

        # Create a dummy file in the parent dir.
        s = BytesIO()
        # Spoof its location.
        s.name = abspath(join(cwd, os.pardir, "t.mv2"))
        # Dump into it
        state_pickler.dump(t, s)

        # Rewind the stream
        s.seek(0)
        # "Move" the file elsewhere
        s.name = join(cwd, "foo", "test", "t.mv2")
        state = state_pickler.load_state(s)
        self.assertEqual(state.f.abs_pth,
                         join(cwd, "foo", "test", curdir, "t.vtk"))

        # Create a dummy file in a subdir.
        s = BytesIO()
        # Spoof its location.
        s.name = abspath(join(cwd, "data", "t.mv2"))
        # Dump into it.
        state_pickler.dump(t, s)

        # Rewind the stream
        s.seek(0)
        # "Move" the file elsewhere
        s.name = join(cwd, "foo", "test", "t.mv2")
        state = state_pickler.load_state(s)
        self.assertEqual(state.f.abs_pth, join(cwd, "foo", "t.vtk"))
Exemple #2
0
 def load_visualization(self, file_or_fname):
     """Given a file/file name this loads the visualization."""
     # Save the state of VTK's global warning display.
     o = vtk.vtkObject
     w = o.GetGlobalWarningDisplay()
     o.SetGlobalWarningDisplay(0) # Turn it off.
     try:
         # Get the state from the file.
         state = state_pickler.load_state(file_or_fname)
         state_pickler.update_state(state)
         # Add the new scenes.
         for scene_state in state.scenes:
             self.new_scene()
             scene = self.scenes[-1]
             # Disable rendering initially.
             if scene.scene is not None:
                 scene.scene.disable_render = True
             # Update the state.
             state_pickler.update_state(scene_state)
             scene.__set_pure_state__(scene_state)
             # Setting the state will automatically reset the
             # disable_render.
             scene.render()
     finally:
         # Reset the warning state.
         o.SetGlobalWarningDisplay(w)
Exemple #3
0
 def load_visualization(self, file_or_fname):
     """Given a file/file name this loads the visualization."""
     # Save the state of VTK's global warning display.
     o = vtk.vtkObject
     w = o.GetGlobalWarningDisplay()
     o.SetGlobalWarningDisplay(0) # Turn it off.
     try:
         # Get the state from the file.
         state = state_pickler.load_state(file_or_fname)
         state_pickler.update_state(state)
         # Add the new scenes.
         for scene_state in state.scenes:
             self.new_scene()
             scene = self.scenes[-1]
             # Disable rendering initially.
             if scene.scene is not None:
                 scene.scene.disable_render = True
             # Update the state.
             state_pickler.update_state(scene_state)
             scene.__set_pure_state__(scene_state)
             # Setting the state will automatically reset the
             # disable_render.
             scene.render()
     finally:
         # Reset the warning state.
         o.SetGlobalWarningDisplay(w)
Exemple #4
0
    def test_pickle(self):
        """Test if pickler works correctly with FilePaths.
        """
        t = Test()
        t.f.set('t.vtk')
        cwd = os.getcwd()
        curdir = basename(cwd)

        # Create a dummy file in the parent dir.
        s = BytesIO()
        # Spoof its location.
        s.name = abspath(join(cwd, os.pardir, 't.mv2'))
        # Dump into it
        state_pickler.dump(t, s)

        # Rewind the stream
        s.seek(0)
        # "Move" the file elsewhere
        s.name = join(cwd, 'foo', 'test', 't.mv2')
        state = state_pickler.load_state(s)
        self.assertEqual(state.f.abs_pth,
                         join(cwd, 'foo', 'test', curdir, 't.vtk'))


        # Create a dummy file in a subdir.
        s = BytesIO()
        # Spoof its location.
        s.name = abspath(join(cwd, 'data', 't.mv2'))
        # Dump into it.
        state_pickler.dump(t, s)

        # Rewind the stream
        s.seek(0)
        # "Move" the file elsewhere
        s.name = join(cwd, 'foo', 'test', 't.mv2')
        state = state_pickler.load_state(s)
        self.assertEqual(state.f.abs_pth,
                         join(cwd, 'foo', 't.vtk'))
Exemple #5
0
from apptools.persistence import state_pickler
from tvtk.api import tvtk

# Local imports.
from mayavi.core.base import Base
from mayavi.core.common import error

from mayavi.core import lut


# The directory that contains the pickled files for colormap
lut_image_dir = os.path.dirname(lut.__file__)
pylab_luts_file = os.path.join(lut_image_dir, 'pylab_luts.pkl')

try:
    pylab_luts = state_pickler.load_state(pylab_luts_file)
except (IOError, ValueError) as exception:
    # IOError: failed to open file
    # ValueError: pickled file is built from an OS w/ different
    #             architecture, or with an incompatible protocol
    message = ("Failed to load pylab colormaps from file:\n"
               "{filepath}\n"
               "Last error: {err_type} {err_message}\n"
               "Some colormaps will not be available. "
               "You may rebuild this file using the script provided "
               "in the mayavi source code: scripts/cm2lut.py")
    warnings.warn(message.format(filepath=pylab_luts_file,
                                 err_type=type(exception).__name__,
                                 err_message=str(exception)))
    pylab_luts = {}
Exemple #6
0

# Enthought library imports.
from traits.api import Instance, Range, Bool, Array, Str, Property, Enum, Button
from traitsui.api import FileEditor, auto_close_message
from apptools.persistence import state_pickler
from tvtk.api import tvtk

# Local imports.
from mayavi.core.base import Base
from mayavi.core.common import error

from mayavi.core import lut

lut_image_dir = os.path.dirname(lut.__file__)
pylab_luts = state_pickler.load_state(os.path.join(lut_image_dir, "pylab_luts.pkl"))

#################################################################
# Utility functions.
#################################################################
def set_lut(vtk_lut, lut_lst):
    """Setup the tvtk.LookupTable (`vtk_lut`) using the passed list of
    lut values."""
    n_col = len(lut_lst)
    vtk_lut.number_of_colors = n_col
    vtk_lut.build()
    for i in range(0, n_col):
        lt = lut_lst[i]
        vtk_lut.set_table_value(i, lt[0], lt[1], lt[2], lt[3])

    return vtk_lut
import subprocess

# Enthought library imports.
from traits.api import Instance, Range, Bool, Array, \
     Str, Property, Enum, Button
from traitsui.api import FileEditor, auto_close_message
from apptools.persistence import state_pickler
from tvtk.api import tvtk

# Local imports.
from mayavi.core.base import Base
from mayavi.core.common import error

from mayavi.core import lut
lut_image_dir = os.path.dirname(lut.__file__)
pylab_luts = state_pickler.load_state(
    os.path.join(lut_image_dir, 'pylab_luts.pkl'))


#################################################################
# Utility functions.
#################################################################
def set_lut(vtk_lut, lut_lst):
    """Setup the tvtk.LookupTable (`vtk_lut`) using the passed list of
    lut values."""
    n_col = len(lut_lst)
    vtk_lut.number_of_colors = n_col
    vtk_lut.build()
    for i in range(0, n_col):
        lt = lut_lst[i]
        vtk_lut.set_table_value(i, lt[0], lt[1], lt[2], lt[3])
Exemple #8
0
from traitsui.api import FileEditor, auto_close_message
from apptools.persistence import state_pickler
from tvtk.api import tvtk

# Local imports.
from mayavi.core.base import Base
from mayavi.core.common import error

from mayavi.core import lut

# The directory that contains the pickled files for colormap
lut_image_dir = os.path.dirname(lut.__file__)
pylab_luts_file = os.path.join(lut_image_dir, 'pylab_luts.pkl')

try:
    pylab_luts = state_pickler.load_state(pylab_luts_file)
except (IOError, ValueError) as exception:
    # IOError: failed to open file
    # ValueError: pickled file is built from an OS w/ different
    #             architecture, or with an incompatible protocol
    message = ("Failed to load pylab colormaps from file:\n"
               "{filepath}\n"
               "Last error: {err_type} {err_message}\n"
               "Some colormaps will not be available. "
               "You may rebuild this file using the script provided "
               "in the mayavi source code: scripts/cm2lut.py")
    warnings.warn(
        message.format(filepath=pylab_luts_file,
                       err_type=type(exception).__name__,
                       err_message=str(exception)))
    pylab_luts = {}
def restore_scene(saved_visualisation, scene_index=0):
    ''' Restore the current scene and modules settings
    according to the scene saved in a visualisation
    file.

    Unmatched data sources are ignored.  Say the current
    scene has only two data sources while the saved scene has
    three, setting for the third data source is ignored.

    Parameters
    ----------
    saved_visualisation : file or fileobj

    scene_index : int
        index of the scene in the saved visualisation.
        default is 0 (first scene)
    '''
    if any(int(num) < 4 for num in MAYAVI_VERSION.split(".")[:3]):
        msg = "restore_scene may not work properly for Mayavi version < 4.4.4"
        logger.warning(msg)

    # get the state of the visualisation
    state = load_state(saved_visualisation)
    update_state(state)

    # reference scene
    ref_scene = state.scenes[scene_index]

    # data sources in the reference scene
    ref_sources = ref_scene.children

    # the scene to be restored
    current_scene = mlab.gcf()

    # data sources in the current scene
    current_sources = current_scene.children

    # warn the user about mismatch data sources
    if len(current_sources) != len(ref_sources):
        msg = ("Current scene has {} sources while the reference has {}. "
               "Mismatch sources are ignored")
        logger.warning(msg.format(len(current_sources), len(ref_sources)))

    # Restore the children for each data source
    # unmatched sources are ignored
    for current_source, ref_source in izip(current_sources, ref_sources):

        # Setup the children
        handle_children_state(current_source.children, ref_source.children)

        # Try restoring each child separately
        # if __set_pure_state__ method is available,
        # we are by-passing the state_pickler.set_state
        for current_child, ref_child in zip(current_source.children,
                                            ref_source.children):
            if hasattr(current_child, "__set_pure_state__"):
                current_child.__set_pure_state__(ref_child)
            else:
                set_state(current_child, ref_child)

    # work around for the bug in restoring camera
    # https://github.com/enthought/mayavi/issues/283
    ref_scene.scene.camera.pop("distance", None)

    # restore scene setting
    try:
        set_state(current_scene.scene, ref_scene.scene)
    except StateSetterError:
        # current scene is an instance of a different class
        # at least restore the camera
        set_state(current_scene.scene.camera,
                  ref_scene.scene.camera)